From d1b5bdf0f97bae85c1e90c7faf78a3eaf7ca33ae Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 29 Oct 2026 12:55:16 -0700 Subject: [PATCH 001/110] Switch: read the on-screen keyboard and type on it with feedback Games open the Switch's own keyboard for names (e.g. BDSP's player name). keyboard_enter_code() types on it blind from an assumed starting key, so it can't recover from a press the keyboard ignored while sliding in, or start from wherever the keyboard left its cursor. SystemKeyboardDetector recognizes the keyboard (OK blue, or grey while the field is empty), find_system_keyboard_cursor() reads the key under the cursor, and system_keyboard_field_has_text() says whether the field is empty. Unit tests cover all three on six reference screenshots (CommandLineTests, NintendoSwitch/SystemKeyboardDetector). type_on_system_keyboard() in FastCodeEntry reads the cursor before each key and moves it with keyboard_get_path(), now declared in the header, over KEYBOARD_POSITIONS, so it shares the key grid and the wrap-around moves with blind code entry and also supports AZERTY. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../ComputerPrograms_UnitTestRunner.cpp | 2 + .../NintendoSwitch_SystemKeyboardDetector.cpp | 141 ++++++++++++++++++ .../NintendoSwitch_SystemKeyboardDetector.h | 66 ++++++++ .../NintendoSwitch_KeyboardCodeEntry.h | 9 ++ .../NintendoSwitch_SystemKeyboardTyping.cpp | 108 ++++++++++++++ .../NintendoSwitch_SystemKeyboardTyping.h | 39 +++++ SerialPrograms/cmake/SourceFiles.cmake | 4 + 7 files changed, 369 insertions(+) create mode 100644 SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp create mode 100644 SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h create mode 100644 SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.cpp create mode 100644 SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 75af30e3e6..e4cc0a7488 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -25,6 +25,7 @@ #include "NintendoSwitch/Inference/NintendoSwitch_CheckOnlineDetector.h" #include "NintendoSwitch/Inference/NintendoSwitch_FailedToConnectDetector.h" +#include "NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h" #include "NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h" #include "NintendoSwitch/Programs/Typewriter/NintendoSwitch_Typewriter_Tests.h" @@ -59,6 +60,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Kernels::add_tests(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); + NintendoSwitch::add_tests_SystemKeyboardDetector(ret); NintendoSwitch::add_tests_UpdatePopupDetector(ret); NintendoSwitch::Typewriter::add_tests_TypewriterTextMapping(ret); NintendoSwitch::PokemonFRLG::add_tests(ret); diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp new file mode 100644 index 0000000000..428abbafa3 --- /dev/null +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp @@ -0,0 +1,141 @@ +/* System Keyboard Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/GlobalAutoPaths.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch_SystemKeyboardDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +// Centres of the four rows of character keys, and of the first column and the +// spacing between columns, as fractions of the screen. +static constexpr double KEY_ROW_Y[] = {0.500, 0.593, 0.681, 0.770}; +static constexpr double KEY_COL_X0 = 0.077; +static constexpr double KEY_COL_STEP = 0.075; + + +SystemKeyboardDetector::SystemKeyboardDetector(Color color) + : m_color(color) + , m_key_panel(0.15, 0.555, 0.65, 0.020) + , m_bottom_bar(0.10, 0.935, 0.35, 0.030) + , m_ok_button(0.875, 0.760, 0.045, 0.020) +{} +void SystemKeyboardDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_key_panel); + items.add(m_color, m_bottom_bar); + items.add(m_color, m_ok_button); +} +bool SystemKeyboardDetector::detect(const ImageViewRGB32& screen){ + if (!is_white(extract_box_reference(screen, m_key_panel)) || + !is_white(extract_box_reference(screen, m_bottom_bar)) + ){ + return false; + } + // OK is blue, or flat grey while the field is empty (disabled). + const ImageStats ok = image_stats(extract_box_reference(screen, m_ok_button)); + return is_solid(ok, {0.172, 0.276, 0.552}) || is_grey(ok, 600, 690); +} + + +bool find_system_keyboard_cursor(const ImageViewRGB32& screen, int& row, int& col){ + // The cursor is a cyan border around one key. Neighbouring keys overlap that border, + // so take the centroid of all cyan pixels and map it to the nearest key. + const ImageFloatBox area(0.02, 0.44, 0.84, 0.38); + ImageViewRGB32 keys = extract_box_reference(screen, area); + double count = 0, sum_x = 0, sum_y = 0; + for (size_t y = 0; y < keys.height(); y++){ + for (size_t x = 0; x < keys.width(); x++){ + const uint32_t pixel = keys.pixel(x, y); + const int red = (pixel >> 16) & 0xff; + const int green = (pixel >> 8) & 0xff; + const int blue = pixel & 0xff; + if (red < 150 && green > 200 && blue > 190){ + count++; + sum_x += (double)x; + sum_y += (double)y; + } + } + } + // The border is about 0.15% of the screen; a few stray pixels are not a cursor. + if (count < 0.0005 * screen.width() * screen.height()){ + return false; + } + const double cx = area.x + sum_x / count / keys.width() * area.width; + const double cy = area.y + sum_y / count / keys.height() * area.height; + col = (int)std::lround((cx - KEY_COL_X0) / KEY_COL_STEP); + row = 0; + for (int r = 1; r < 4; r++){ + if (std::abs(KEY_ROW_Y[r] - cy) < std::abs(KEY_ROW_Y[row] - cy)){ + row = r; + } + } + return 0 <= col && col < 11; +} + +bool system_keyboard_field_has_text(const ImageViewRGB32& screen){ + // Left part of the field, after the caret's position on an empty field. + const ImageStats stats = image_stats(extract_box_reference(screen, ImageFloatBox(0.11, 0.235, 0.19, 0.030))); + return stats.stddev.sum() > 30; +} + + +// One screenshot and what each function should read from it. +class Test_SystemKeyboardDetector : public UnitTest{ +public: + // cursor_row/col: -1 for a screen without the keyboard. + Test_SystemKeyboardDetector(const std::string& image, bool keyboard, int cursor_row, int cursor_col, bool has_text) + : UnitTest("NintendoSwitch::SystemKeyboardDetector - " + image) + , m_image(UNIT_TEST_RESOURCE_PATH() + image) + , m_keyboard(keyboard) + , m_cursor_row(cursor_row) + , m_cursor_col(cursor_col) + , m_has_text(has_text) + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + ImageRGB32 image(m_image); + if (SystemKeyboardDetector().detect(image) != m_keyboard){ + return false; + } + if (!m_keyboard){ + return true; + } + int row = -1; + int col = -1; + return find_system_keyboard_cursor(image, row, col) + && row == m_cursor_row && col == m_cursor_col + && system_keyboard_field_has_text(image) == m_has_text; + } + +private: + std::string m_image; + bool m_keyboard; + int m_cursor_row; + int m_cursor_col; + bool m_has_text; +}; + + +void add_tests_SystemKeyboardDetector(UnitTestDatabase& database){ + const std::string folder = "NintendoSwitch/SystemKeyboardDetector/"; + // The OK button is blue with text in the field and grey without. + database.add(folder + "BDSP-PlayerName-Empty.png", true, 0, 0, false); + database.add(folder + "BDSP-FriendName-Typed.png", true, 0, 0, true); + database.add(folder + "BDSP-Dialog.png", false, -1, -1, false); + database.add(folder + "HomeMenu.png", false, -1, -1, false); + database.add(folder + "HomeMenu-OnlineLicensePopup.png", false, -1, -1, false); + database.add(folder + "UserSelect.png", false, -1, -1, false); +} + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h new file mode 100644 index 0000000000..7a2952a2ce --- /dev/null +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h @@ -0,0 +1,66 @@ +/* System Keyboard Detector + * + * From: https://github.com/PokemonAutomation/ + * + * The Switch's own on-screen keyboard, which games open for names (e.g. the + * player's name in BDSP): detect it, find the key under its cursor, and tell + * whether its text field is empty. Typing with it is in + * Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h. + * + * Measured on 1920x1080 captures of the QWERTY layout. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SystemKeyboardDetector_H +#define PokemonAutomation_NintendoSwitch_SystemKeyboardDetector_H + +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +// White key panel and bottom bar, and the OK button (blue, or grey while the +// field is empty). +class SystemKeyboardDetector : public StaticScreenDetector{ +public: + SystemKeyboardDetector(Color color = COLOR_CYAN); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_key_panel; + ImageFloatBox m_bottom_bar; + ImageFloatBox m_ok_button; +}; +class SystemKeyboardWatcher : public DetectorToFinder{ +public: + SystemKeyboardWatcher(Color color = COLOR_CYAN) + : DetectorToFinder("SystemKeyboardWatcher", std::chrono::milliseconds(250), color) + {} +}; + + +// The key under the cursor, as row (0: digits .. 3: "zxcv") and column (0..10). +// The keyboard remembers the cursor between uses, so read it, don't assume it. +// Returns false if no cursor border is visible. +bool find_system_keyboard_cursor(const ImageViewRGB32& screen, int& row, int& col); + +// Whether the text field holds any text. Pressing B on an empty field closes the +// keyboard, so delete only while this is true. +bool system_keyboard_field_has_text(const ImageViewRGB32& screen); + + + +void add_tests_SystemKeyboardDetector(UnitTestDatabase& database); + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h index 7048582ea0..38f4f4d841 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h @@ -8,10 +8,12 @@ #define PokemonAutomation_NintendoSwitch_KeyboardCodeEntry_H #include +#include #include "Controllers/StandardHid/StandardHid_Keyboard.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" #include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" #include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardEntryMappings.h" +#include "NintendoSwitch_CodeEntryTools.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -19,6 +21,13 @@ namespace FastCodeEntry{ +// The D-pad moves from "source" to "destination" on the on-screen keyboard, +// wrapping around the sides when that is shorter, then ENTER_CHAR. +std::vector keyboard_get_path( + KeyboardEntryPosition source, + KeyboardEntryPosition destination +); + // Automatically select between keyboard or pro controller depending on the // controller type. void keyboard_enter_code( diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.cpp new file mode 100644 index 0000000000..43a3329df5 --- /dev/null +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.cpp @@ -0,0 +1,108 @@ +/* System Keyboard Typing + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h" +#include "NintendoSwitch_KeyboardCodeEntry.h" +#include "NintendoSwitch_SystemKeyboardTyping.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace FastCodeEntry{ + +using namespace std::chrono_literals; + + +namespace{ + +constexpr Milliseconds MOVE_HOLD = 100ms; // One key per press, without auto-repeat. +constexpr Milliseconds MOVE_RELEASE = 200ms; +constexpr Milliseconds WRAP_RELEASE = 400ms; // Wrapping around a side animates for longer. +constexpr Milliseconds SETTLE = 300ms; // Before reading the cursor after moving it. +constexpr Milliseconds KEY_HOLD = 80ms; +constexpr Milliseconds KEY_RELEASE = 300ms; + +// A press made while the keyboard is still sliding in is ignored, so the +// cursor is read again after each try until it is on the target. +constexpr size_t MAX_MOVE_TRIES = 10; + + +bool read_cursor(VideoStream& stream, ProControllerContext& context, KeyboardEntryPosition& position){ + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + int row = -1; + int col = -1; + if (!screen || !find_system_keyboard_cursor(screen, row, col)){ + return false; + } + position = {(uint8_t)row, (uint8_t)col}; + return true; +} + +void move_cursor(VideoStream& stream, ProControllerContext& context, KeyboardEntryPosition target, char ch){ + for (size_t attempt = 0; attempt < MAX_MOVE_TRIES; attempt++){ + KeyboardEntryPosition cursor; + if (!read_cursor(stream, context, cursor)){ + pbf_wait(context, SETTLE); + continue; + } + if (cursor.row == target.row && cursor.col == target.col){ + return; + } + for (CodeEntryAction action : keyboard_get_path(cursor, target)){ + if (!is_move(action)){ + continue; + } + const bool wrap = ((uint8_t)action & 0x80) != 0; + const DpadPosition direction = (DpadPosition)((uint8_t)action & 0x7f); + pbf_press_dpad(context, direction, MOVE_HOLD, wrap ? WRAP_RELEASE : MOVE_RELEASE); + } + pbf_wait(context, SETTLE); + } + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + std::string("System keyboard: the cursor did not reach '") + ch + "'.", + stream + ); +} + +} + + + +void type_on_system_keyboard( + VideoStream& stream, ProControllerContext& context, + const std::string& text, + KeyboardLayout layout +){ + const std::map& positions = KEYBOARD_POSITIONS(layout); + for (char ch : text){ + // Letters are listed under their uppercase key. + auto iter = positions.find((char)std::toupper((unsigned char)ch)); + if (iter == positions.end()){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + std::string("System keyboard: no key for '") + ch + "'.", + stream + ); + } + move_cursor(stream, context, iter->second, ch); + if (std::isupper((unsigned char)ch)){ + pbf_press_button(context, BUTTON_LCLICK, 100ms, 250ms); + } + pbf_press_button(context, BUTTON_A, KEY_HOLD, KEY_RELEASE); + } + context.wait_for_all_requests(); +} + + + +} +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h new file mode 100644 index 0000000000..b0ec331111 --- /dev/null +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h @@ -0,0 +1,39 @@ +/* System Keyboard Typing + * + * From: https://github.com/PokemonAutomation/ + * + * Types text on the Switch's on-screen keyboard with a Pro Controller, reading + * the cursor from the video before each key. Unlike keyboard_enter_code(), + * which moves blind from an assumed starting key, it works wherever the + * keyboard left its cursor and catches presses the keyboard ignored. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SystemKeyboardTyping_H +#define PokemonAutomation_NintendoSwitch_SystemKeyboardTyping_H + +#include +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch_KeyboardEntryMappings.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace FastCodeEntry{ + + +// Types `text` (letters, digits and the symbols on the keyboard's first page) +// on the open keyboard. An uppercase letter is typed with Shift (left stick +// click). Throws, with a screenshot, for a character that has no key, or if +// the cursor can't be read or doesn't reach a key. +void type_on_system_keyboard( + VideoStream& stream, ProControllerContext& context, + const std::string& text, + KeyboardLayout layout = KeyboardLayout::QWERTY +); + + +} +} +} +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 39c48d531e..f82e61647b 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1323,6 +1323,8 @@ file(GLOB LIBRARY_SOURCES Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.cpp Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.h + Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp + Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.cpp Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.cpp @@ -1374,6 +1376,8 @@ file(GLOB LIBRARY_SOURCES Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.cpp Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h + Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.cpp + Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.cpp Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.h Source/NintendoSwitch/Programs/NintendoSwitch_FriendDelete.cpp From 110d05e6a28a791f5fb19f4c8ffb10302384a36c Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 12:51:38 -0800 Subject: [PATCH 002/110] Pokemon AutoStory: share SV's checkpoint retry and save counting Move the game-agnostic part of SV's checkpoint_reattempt_loop and checkpoint_save into Pokemon/AutoStory/Pokemon_CheckpointRetry: the retry policy, reset counter and StoryLog lines, with the game's run, report, reset and give-up as callables. SV keeps its saves and messages and its historical counts (102 attempts, report on the 11th failure). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_AutoStory_Tests.h | 2 + .../AutoStory/Pokemon_CheckpointRetry.cpp | 57 +++++ .../AutoStory/Pokemon_CheckpointRetry.h | 78 ++++++ .../Pokemon_CheckpointRetry_Tests.cpp | 225 ++++++++++++++++++ .../AutoStory/Pokemon_CheckpointRetry_Tests.h | 23 ++ .../AutoStory/PokemonSV_AutoStoryTools.cpp | 206 ++++++++-------- SerialPrograms/cmake/SourceFiles.cmake | 4 + 7 files changed, 492 insertions(+), 103 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 5502b147a4..58dfaaf8cb 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -15,6 +15,7 @@ #include "Pokemon/Options/Pokemon_StoryRangeOptions_Tests.h" #include "Pokemon_AutoStorySelect_Tests.h" #include "Pokemon_AutoStoryStats_Tests.h" +#include "Pokemon_CheckpointRetry_Tests.h" #include "Pokemon_StoryLog_Tests.h" namespace PokemonAutomation{ @@ -25,6 +26,7 @@ namespace Pokemon{ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_AutoStorySelect(database); add_tests_AutoStoryStats(database); + add_tests_CheckpointRetry(database); add_tests_StoryLog(database); add_tests_StoryRangeOptions(database); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp new file mode 100644 index 0000000000..87d9317d07 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp @@ -0,0 +1,57 @@ +/* Checkpoint Retry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryLog.h" +#include "Pokemon_CheckpointRetry.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +size_t run_checkpoint_with_retries( + std::string_view checkpoint, + const CheckpointRetryPolicy& policy, + const CheckpointRetryActions& actions, + AutoStoryStats& stats +){ + actions.log(checkpoint_start_line(checkpoint)); + for (size_t attempt = 1;; attempt++){ + try{ + actions.log(checkpoint_attempt_line(checkpoint, attempt, policy.max_attempts)); + actions.run(attempt); + actions.log(checkpoint_pass_line(checkpoint, attempt)); + return attempt; + }catch (OperationFailedException& e){ + if (attempt == policy.report_at_failure){ + actions.report(e); + } + if (attempt >= policy.max_attempts){ + actions.give_up(e); + throw; + } + actions.log(checkpoint_reset_line(checkpoint, attempt + 1)); + actions.reset(); + stats.m_reset++; + actions.update_stats(); + } + } +} + + +void record_checkpoint_saved( + AutoStoryStats& stats, + const std::function& update_stats, + const std::function& notify +){ + stats.m_checkpoint++; + update_stats(); + notify(CHECKPOINT_SAVED_MESSAGE); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h new file mode 100644 index 0000000000..de9e901255 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h @@ -0,0 +1,78 @@ +/* Checkpoint Retry + * + * From: https://github.com/PokemonAutomation/ + * + * The retry policy of a game whose AutoStory runs each checkpoint in its + * own loop (SV's): run the checkpoint, and on an operation failure reset + * the game to the checkpoint's save and try again, report once for + * debugging after some failures, and give up after the last attempt. + * The game supplies what it does at each step; the policy, the counters + * and the log lines (Pokemon_StoryLog.h) live here. + * + */ + +#ifndef PokemonAutomation_Pokemon_CheckpointRetry_H +#define PokemonAutomation_Pokemon_CheckpointRetry_H + +#include +#include +#include +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_AutoStoryStats.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +struct CheckpointRetryPolicy{ + // Attempts before the checkpoint gives up. + size_t max_attempts; + // The failure count at which the game reports once for debugging. + size_t report_at_failure; +}; + +// What the game does at each step of the loop. +struct CheckpointRetryActions{ + // Runs attempt `attempt`, counting from 1. Throws + // OperationFailedException when the attempt fails. + std::function run; + // Sends the debugging report, with the exception of the failure that + // reached the policy's count. + std::function report; + // Throws the game's final error after the last attempt failed. + std::function give_up; + // Resets the game to the checkpoint's save. + std::function reset; + // Publishes changed stats. + std::function update_stats; + // Writes one log line. + std::function log; +}; + +// Runs `checkpoint` until an attempt passes, and returns that attempt's +// number. Each reset adds to `stats.m_reset`. +size_t run_checkpoint_with_retries( + std::string_view checkpoint, + const CheckpointRetryPolicy& policy, + const CheckpointRetryActions& actions, + AutoStoryStats& stats +); + + +// The status message sent after the game saved at a checkpoint. +inline constexpr std::string_view CHECKPOINT_SAVED_MESSAGE = "Saved at checkpoint."; + +// Counts a checkpoint the game just saved at, publishes the stats and +// sends CHECKPOINT_SAVED_MESSAGE through `notify`. +void record_checkpoint_saved( + AutoStoryStats& stats, + const std::function& update_stats, + const std::function& notify +); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp new file mode 100644 index 0000000000..54f17774af --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp @@ -0,0 +1,225 @@ +/* Checkpoint Retry Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_CheckpointRetry.h" +#include "Pokemon_CheckpointRetry_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +// Thrown by the test's give_up, so the test can tell it from the attempt's. +struct GaveUp{}; + +// A checkpoint whose first `failures` attempts fail. +struct CheckpointRetryInput{ + std::string name; + CheckpointRetryPolicy policy; + size_t failures; +}; + +struct CheckpointRetryExpectation{ + // The attempt that passed; 0 if the loop gave up. + size_t passed_on; + // The failure counts at which the loop reported. + std::vector reports; + size_t resets; + std::vector log; +}; + +// One retry loop run and what it must do. +struct CheckpointRetryCase{ + CheckpointRetryInput input; + CheckpointRetryExpectation expectation; +}; + +// What the loop did through the test's actions. +struct CheckpointRetryRecord{ + size_t passed_on = 0; + std::vector reports; + size_t resets = 0; + std::vector log; +}; + +CheckpointRetryRecord run_case(const CheckpointRetryInput& input, AutoStoryStats& stats){ + CheckpointRetryRecord record; + size_t attempts = 0; + CheckpointRetryActions actions{ + .run = [&](size_t attempt){ + attempts = attempt; + if (attempt <= input.failures){ + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, "failed"); + } + }, + .report = [&](const OperationFailedException&){ + record.reports.push_back(attempts); + }, + .give_up = [](const OperationFailedException&){ + throw GaveUp(); + }, + .reset = [&](){ + record.resets++; + }, + .update_stats = [](){}, + .log = [&](const std::string& line){ + record.log.push_back(line); + }, + }; + try{ + record.passed_on = run_checkpoint_with_retries("01", input.policy, actions, stats); + }catch (GaveUp&){ + record.passed_on = 0; + } + return record; +} + +class Test_CheckpointRetry : public UnitTest{ +public: + Test_CheckpointRetry(CheckpointRetryCase test_case) + : UnitTest(std::format("Pokemon::CheckpointRetry - {}", test_case.input.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + AutoStoryStats stats; + const CheckpointRetryRecord record = run_case(m_case.input, stats); + const CheckpointRetryExpectation& expected = m_case.expectation; + if (record.passed_on != expected.passed_on){ + return std::format("Expected a pass on attempt {}, got {}", expected.passed_on, record.passed_on); + } + if (record.reports != expected.reports){ + return std::format("Expected {} reports, got {}", expected.reports.size(), record.reports.size()); + } + if (record.resets != expected.resets || stats.m_reset.load() != expected.resets){ + return std::format( + "Expected {} resets, got {} (stats {})", + expected.resets, record.resets, stats.m_reset.load() + ); + } + if (record.log != expected.log){ + return std::format("Expected {} log lines, got {}", expected.log.size(), record.log.size()); + } + return true; + } + +private: + const CheckpointRetryCase m_case; +}; + +const CheckpointRetryCase CHECKPOINT_RETRY_CASES[] = { + { + .input = {.name = "one-shot pass", .policy = {.max_attempts = 3, .report_at_failure = 2}, .failures = 0}, + .expectation = { + .passed_on = 1, + .reports = {}, + .resets = 0, + .log = { + "[Checkpoint] 01: start", + "[Checkpoint] 01: attempt 1/3", + "[Checkpoint] 01: passed on attempt 1 (one-shot)", + }, + }, + }, + { + .input = {.name = "pass after a reset", .policy = {.max_attempts = 3, .report_at_failure = 2}, .failures = 1}, + .expectation = { + .passed_on = 2, + .reports = {}, + .resets = 1, + .log = { + "[Checkpoint] 01: start", + "[Checkpoint] 01: attempt 1/3", + "[Checkpoint] 01: failed, resetting for attempt 2", + "[Checkpoint] 01: attempt 2/3", + "[Checkpoint] 01: passed on attempt 2 (1 reset)", + }, + }, + }, + { + .input = {.name = "report once at its failure count", .policy = {.max_attempts = 5, .report_at_failure = 2}, .failures = 3}, + .expectation = { + .passed_on = 4, + .reports = {2}, + .resets = 3, + .log = { + "[Checkpoint] 01: start", + "[Checkpoint] 01: attempt 1/5", + "[Checkpoint] 01: failed, resetting for attempt 2", + "[Checkpoint] 01: attempt 2/5", + "[Checkpoint] 01: failed, resetting for attempt 3", + "[Checkpoint] 01: attempt 3/5", + "[Checkpoint] 01: failed, resetting for attempt 4", + "[Checkpoint] 01: attempt 4/5", + "[Checkpoint] 01: passed on attempt 4 (3 resets)", + }, + }, + }, + { + .input = {.name = "give up after the last attempt, without a reset", .policy = {.max_attempts = 2, .report_at_failure = 2}, .failures = 5}, + .expectation = { + .passed_on = 0, + .reports = {2}, + .resets = 1, + .log = { + "[Checkpoint] 01: start", + "[Checkpoint] 01: attempt 1/2", + "[Checkpoint] 01: failed, resetting for attempt 2", + "[Checkpoint] 01: attempt 2/2", + }, + }, + }, +}; + + +class Test_CheckpointSaved : public UnitTest{ +public: + Test_CheckpointSaved() + : UnitTest("Pokemon::CheckpointRetry - a save counts, publishes and notifies") + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + AutoStoryStats stats; + size_t updates = 0; + std::vector messages; + for (size_t i = 0; i < 2; i++){ + record_checkpoint_saved( + stats, + [&](){ updates++; }, + [&](std::string_view message){ messages.emplace_back(message); } + ); + } + if (stats.m_checkpoint.load() != 2 || updates != 2){ + return std::format("Expected 2 checkpoints and updates, got {} and {}", stats.m_checkpoint.load(), updates); + } + if (messages != std::vector{"Saved at checkpoint.", "Saved at checkpoint."}){ + return std::string("Expected \"Saved at checkpoint.\" per save"); + } + return true; + } +}; + + +} // namespace + + +void add_tests_CheckpointRetry(UnitTestDatabase& database){ + for (const CheckpointRetryCase& test_case : CHECKPOINT_RETRY_CASES){ + database.add(test_case); + } + database.add(); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.h new file mode 100644 index 0000000000..b7b5ccb6f1 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.h @@ -0,0 +1,23 @@ +/* Checkpoint Retry Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_CheckpointRetry_Tests_H +#define PokemonAutomation_Pokemon_CheckpointRetry_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the checkpoint retry loop and checkpoint saves. +void add_tests_CheckpointRetry(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp index c2d61152df..1db01c4ae9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp @@ -4,6 +4,7 @@ * */ +#include #include "Common/Cpp/PrettyPrint.h" #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" #include "CommonFramework/Exceptions/UnexpectedBattleException.h" @@ -29,6 +30,7 @@ #include "VideoGames/PokemonSV/Inference/PokemonSV_PokemonMovesReader.h" #include "VideoGames/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.h" #include "VideoGames/PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.h" +#include "Pokemon/AutoStory/Pokemon_CheckpointRetry.h" #include "PokemonSV_AutoStoryTools.h" //#include @@ -1177,11 +1179,71 @@ void get_on_or_off_ride(const ProgramInfo& info, VideoStream& stream, ProControl } } +namespace{ + +// The loop's historical counts; its messages say 100 attempts and 10 failures. +const Pokemon::CheckpointRetryPolicy SV_CHECKPOINT_RETRY_POLICY{.max_attempts = 102, .report_at_failure = 11}; + +void record_sv_checkpoint_saved( + SingleSwitchProgramEnvironment& env, EventNotificationOption& notif_status_update, AutoStoryStats& stats +){ + Pokemon::record_checkpoint_saved( + stats, + [&env](){ env.update_stats(); }, + [&](std::string_view message){ send_program_status_notification(env, notif_status_update, std::string(message)); } + ); +} + +// `give_up_detail` goes into the final error after its first line: the +// overworld loop names the checkpoint there, the tutorial loop does not. +Pokemon::CheckpointRetryActions sv_checkpoint_retry_actions( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_error_recoverable, + const std::string& checkpoint_text, + std::function run, + std::string give_up_detail +){ + return Pokemon::CheckpointRetryActions{ + .run = std::move(run), + .report = [&env, ¬if_error_recoverable, &checkpoint_text](const OperationFailedException&){ + auto snapshot = env.console.video().snapshot().frame; + send_program_recoverable_error_notification_and_telemetry_report( + env, &env.logger(), env.program_info(), + notif_error_recoverable, + ErrorReportMode::SEND_ERROR_REPORT, + std::format("10 failed attempts. {}", checkpoint_text), + "OperationFailedExceptionWithScreenshot", + *snapshot, + &env.console.history() + ); + }, + .give_up = [&env, give_up_detail = std::move(give_up_detail)](const OperationFailedException& e){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + std::format( + "Autostory checkpoint failed 100 times.\n{}" + "Make sure you selected the correct Start Point, and your character is in the exactly correct starting position." + "Also, make sure you have set the correct Language.\n{}", + give_up_detail, e.message() + ), + env.console + ); + }, + .reset = [&env, &context](){ + context.wait_for_all_requests(); + reset_game(env.program_info(), env.console, context); + }, + .update_stats = [&env](){ env.update_stats(); }, + .log = [&env](const std::string& line){ env.console.log(line); }, + }; +} + +} // namespace + void checkpoint_save(SingleSwitchProgramEnvironment& env, ProControllerContext& context, EventNotificationOption& notif_status_update, AutoStoryStats& stats){ save_game_from_overworld(env.program_info(), env.console, context); - stats.m_checkpoint++; - env.update_stats(); - send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); + record_sv_checkpoint_saved(env, notif_status_update, stats); } @@ -1433,59 +1495,27 @@ void checkpoint_reattempt_loop( std::function&& action, bool day_skip ){ - size_t max_attempts = 100; - for (size_t i = 0;;i++){ - try{ - if (i==0){ - checkpoint_save(env, context, notif_status_update, stats); - } - - if (day_skip && (i > 0 || ENABLE_TEST)){ - day_skip_from_overworld(env.console, context); - save_game_from_overworld(env.program_info(), env.console, context); - } - - env.console.log(checkpoint_text + " Num attempts: " + std::to_string(i)); - - context.wait_for_all_requests(); - action(i); - - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - - break; - }catch (OperationFailedException& e){ - if (i == 10){ // send an error report for debugging if 10 failed attempts for a given checkpoint. - auto snapshot = env.console.video().snapshot().frame; - std::string message = "10 failed attempts. " + checkpoint_text; - send_program_recoverable_error_notification_and_telemetry_report( - env, &env.logger(), env.program_info(), - notif_error_recoverable, - ErrorReportMode::SEND_ERROR_REPORT, - message, - "OperationFailedExceptionWithScreenshot", - *snapshot, - &env.console.history() - ); - } - - if (i > max_attempts){ - OperationFailedExceptionWithScreenshot::fire( - ErrorReportMode::SEND_ERROR_REPORT, - "Autostory checkpoint failed " + std::to_string(max_attempts) + " times.\n" + - checkpoint_text + "\n" - "Make sure you selected the correct Start Point, and your character is in the exactly correct starting position." - "Also, make sure you have set the correct Language.\n" + e.message(), - env.console - ); - } - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - + Pokemon::run_checkpoint_with_retries( + checkpoint_text, SV_CHECKPOINT_RETRY_POLICY, + sv_checkpoint_retry_actions( + env, context, notif_error_recoverable, checkpoint_text, + [&](size_t attempt){ + const size_t i = attempt - 1; + if (i == 0){ + checkpoint_save(env, context, notif_status_update, stats); + } + if (day_skip && (i > 0 || ENABLE_TEST)){ + day_skip_from_overworld(env.console, context); + save_game_from_overworld(env.program_info(), env.console, context); + } + context.wait_for_all_requests(); + action(i); + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + }, + std::format("{}\n", checkpoint_text) + ), + stats + ); } void checkpoint_reattempt_loop_tutorial( @@ -1497,53 +1527,23 @@ void checkpoint_reattempt_loop_tutorial( const std::string& checkpoint_text, std::function&& action ){ - size_t max_attempts = 100; - for (size_t i = 0;;i++){ - try{ - if(i==0){ - save_game_tutorial(env.program_info(), env.console, context); - stats.m_checkpoint++; - env.update_stats(); - send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); - } - - env.console.log(checkpoint_text + " Num attempts: " + std::to_string(i)); - - context.wait_for_all_requests(); - action(i); - - break; - }catch (OperationFailedException& e){ - if (i == 10){ // send an error report for debugging if 10 failed attempts for a given checkpoint. - auto snapshot = env.console.video().snapshot().frame; - std::string message = "10 failed attempts. " + checkpoint_text; - send_program_recoverable_error_notification_and_telemetry_report( - env, &env.logger(), env.program_info(), - notif_error_recoverable, - ErrorReportMode::SEND_ERROR_REPORT, - message, - "OperationFailedExceptionWithScreenshot", - *snapshot, - &env.console.history() - ); - } - - if (i > max_attempts){ - OperationFailedExceptionWithScreenshot::fire( - ErrorReportMode::SEND_ERROR_REPORT, - "Autostory checkpoint failed " + std::to_string(max_attempts) + " times.\n" - "Make sure you selected the correct Start Point, and your character is in the exactly correct starting position." - "Also, make sure you have set the correct Language.\n" + e.message(), - env.console - ); - } - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } + Pokemon::run_checkpoint_with_retries( + checkpoint_text, SV_CHECKPOINT_RETRY_POLICY, + sv_checkpoint_retry_actions( + env, context, notif_error_recoverable, checkpoint_text, + [&](size_t attempt){ + const size_t i = attempt - 1; + if (i == 0){ + save_game_tutorial(env.program_info(), env.console, context); + record_sv_checkpoint_saved(env, notif_status_update, stats); + } + context.wait_for_all_requests(); + action(i); + }, + "" + ), + stats + ); } void move_player_forward( diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 8e292ab767..b9af11f84a 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1479,6 +1479,10 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.h Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h + Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp + Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h + Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.h Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp Source/Pokemon/AutoStory/Pokemon_StoryLog.h Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp From 14144fce7181de4df5ec0ebfc53435112a65ac5a Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 12:52:14 -0800 Subject: [PATCH 003/110] Pokemon AutoStory: CheckpointRetry code-health fixes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_CheckpointRetry.cpp | 6 +- .../AutoStory/Pokemon_CheckpointRetry.h | 25 +++++--- .../Pokemon_CheckpointRetry_Tests.cpp | 60 +++++++++++++++---- .../AutoStory/PokemonSV_AutoStoryTools.cpp | 4 +- 4 files changed, 71 insertions(+), 24 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp index 87d9317d07..3f30be451d 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp @@ -42,9 +42,9 @@ size_t run_checkpoint_with_retries( void record_checkpoint_saved( - AutoStoryStats& stats, - const std::function& update_stats, - const std::function& notify + const CheckpointStep& update_stats, + const std::function& notify, + AutoStoryStats& stats ){ stats.m_checkpoint++; update_stats(); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h index de9e901255..05ac68e781 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h @@ -25,6 +25,7 @@ namespace PokemonAutomation{ namespace Pokemon{ +// How often a checkpoint retries and when it reports. struct CheckpointRetryPolicy{ // Attempts before the checkpoint gives up. size_t max_attempts; @@ -32,6 +33,13 @@ struct CheckpointRetryPolicy{ size_t report_at_failure; }; +// A game step that takes nothing: a reset, a stats update. +using CheckpointStep = std::function; +// A game step on the failure that reached a policy count. +using CheckpointFailureStep = std::function; +// Writes one log line. +using CheckpointLogger = std::function; + // What the game does at each step of the loop. struct CheckpointRetryActions{ // Runs attempt `attempt`, counting from 1. Throws @@ -39,15 +47,14 @@ struct CheckpointRetryActions{ std::function run; // Sends the debugging report, with the exception of the failure that // reached the policy's count. - std::function report; + CheckpointFailureStep report; // Throws the game's final error after the last attempt failed. - std::function give_up; + CheckpointFailureStep give_up; // Resets the game to the checkpoint's save. - std::function reset; + CheckpointStep reset; // Publishes changed stats. - std::function update_stats; - // Writes one log line. - std::function log; + CheckpointStep update_stats; + CheckpointLogger log; }; // Runs `checkpoint` until an attempt passes, and returns that attempt's @@ -66,9 +73,9 @@ inline constexpr std::string_view CHECKPOINT_SAVED_MESSAGE = "Saved at checkpoin // Counts a checkpoint the game just saved at, publishes the stats and // sends CHECKPOINT_SAVED_MESSAGE through `notify`. void record_checkpoint_saved( - AutoStoryStats& stats, - const std::function& update_stats, - const std::function& notify + const CheckpointStep& update_stats, + const std::function& notify, + AutoStoryStats& stats ); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp index 54f17774af..3d1015cbc2 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp @@ -4,6 +4,7 @@ * */ +#include #include #include #include @@ -181,31 +182,68 @@ const CheckpointRetryCase CHECKPOINT_RETRY_CASES[] = { }; +// `saves` checkpoint saves in a row. +struct CheckpointSavedInput{ + std::string name; + size_t saves; +}; + +struct CheckpointSavedExpectation{ + uint64_t checkpoints; + size_t updates; + std::vector messages; +}; + +// Checkpoint saves and what they must count and send. +struct CheckpointSavedCase{ + CheckpointSavedInput input; + CheckpointSavedExpectation expectation; +}; + class Test_CheckpointSaved : public UnitTest{ public: - Test_CheckpointSaved() - : UnitTest("Pokemon::CheckpointRetry - a save counts, publishes and notifies") + Test_CheckpointSaved(CheckpointSavedCase test_case) + : UnitTest(std::format("Pokemon::CheckpointRetry - {}", test_case.input.name)) + , m_case(std::move(test_case)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ AutoStoryStats stats; size_t updates = 0; std::vector messages; - for (size_t i = 0; i < 2; i++){ + for (size_t i = 0; i < m_case.input.saves; i++){ record_checkpoint_saved( - stats, [&](){ updates++; }, - [&](std::string_view message){ messages.emplace_back(message); } + [&](std::string_view message){ messages.emplace_back(message); }, + stats ); } - if (stats.m_checkpoint.load() != 2 || updates != 2){ - return std::format("Expected 2 checkpoints and updates, got {} and {}", stats.m_checkpoint.load(), updates); + const CheckpointSavedExpectation& expected = m_case.expectation; + if (stats.m_checkpoint.load() != expected.checkpoints || updates != expected.updates){ + return std::format( + "Expected {} checkpoints and {} updates, got {} and {}", + expected.checkpoints, expected.updates, stats.m_checkpoint.load(), updates + ); } - if (messages != std::vector{"Saved at checkpoint.", "Saved at checkpoint."}){ - return std::string("Expected \"Saved at checkpoint.\" per save"); + if (messages != expected.messages){ + return std::format("Expected {} messages, got {}", expected.messages.size(), messages.size()); } return true; } + +private: + const CheckpointSavedCase m_case; +}; + +const CheckpointSavedCase CHECKPOINT_SAVED_CASES[] = { + { + .input = {.name = "each save counts, publishes and notifies", .saves = 2}, + .expectation = { + .checkpoints = 2, + .updates = 2, + .messages = {"Saved at checkpoint.", "Saved at checkpoint."}, + }, + }, }; @@ -216,7 +254,9 @@ void add_tests_CheckpointRetry(UnitTestDatabase& database){ for (const CheckpointRetryCase& test_case : CHECKPOINT_RETRY_CASES){ database.add(test_case); } - database.add(); + for (const CheckpointSavedCase& test_case : CHECKPOINT_SAVED_CASES){ + database.add(test_case); + } } diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp index 1db01c4ae9..df9362f3d0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp @@ -1188,9 +1188,9 @@ void record_sv_checkpoint_saved( SingleSwitchProgramEnvironment& env, EventNotificationOption& notif_status_update, AutoStoryStats& stats ){ Pokemon::record_checkpoint_saved( - stats, [&env](){ env.update_stats(); }, - [&](std::string_view message){ send_program_status_notification(env, notif_status_update, std::string(message)); } + [&](std::string_view message){ send_program_status_notification(env, notif_status_update, std::string(message)); }, + stats ); } From 9ea62b9b93f0300ef5af8a24a63ff4af1f29b53f Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 20:37:07 -0800 Subject: [PATCH 004/110] PokemonSV AutoStory: shared checkpoint range options and log lines The tutorial and main story checkpoint dropdowns are now the shared StoryRangeOptions, added under the same keys (START_CHECKPOINT_TUTORIAL, END_CHECKPOINT_TUTORIAL, START_CHECKPOINT_MAINSTORY, END_CHECKPOINT_MAINSTORY) over the same databases, so saved settings load unchanged; the end stays unlocked while running. The start-before-end check is the range's. The checkpoint loops log the shared attempt and reset lines, and the run logs the shared checkpoint start line. Rebased onto autostory/story-range-options (#325) and squashed: it uses only the shared range options (#325) and log lines (#45), not #312. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonSV_AutoStory.cpp | 76 ++++++++----------- .../Programs/AutoStory/PokemonSV_AutoStory.h | 14 ++-- .../AutoStory/PokemonSV_AutoStoryTools.cpp | 8 +- .../AutoStory/PokemonSV_AutoStoryTools.h | 4 +- 4 files changed, 47 insertions(+), 55 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp index 130271139b..945731d147 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp @@ -28,6 +28,7 @@ #include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" #include "Pokemon/Pokemon_Strings.h" #include "Pokemon/AutoStory/Pokemon_AutoStorySelect.h" +#include "Pokemon/AutoStory/Pokemon_StoryLog.h" #include "VideoGames/PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" #include "VideoGames/PokemonSV/PokemonSV_Settings.h" #include "VideoGames/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" @@ -347,6 +348,10 @@ AutoStory::~AutoStory(){ ENDPOINT_TUTORIAL.remove_listener(*this); STARTPOINT_MAINSTORY.remove_listener(*this); ENDPOINT_MAINSTORY.remove_listener(*this); + TUTORIAL_CHECKPOINTS.START_CHECKPOINT.remove_listener(*this); + TUTORIAL_CHECKPOINTS.END_CHECKPOINT.remove_listener(*this); + MAINSTORY_CHECKPOINTS.START_CHECKPOINT.remove_listener(*this); + MAINSTORY_CHECKPOINTS.END_CHECKPOINT.remove_listener(*this); ENABLE_TEST_CHECKPOINTS.remove_listener(*this); ENABLE_MISC_TEST.remove_listener(*this); TEST_PBF_LEFT_JOYSTICK.remove_listener(*this); @@ -395,30 +400,9 @@ AutoStory::AutoStory() LockMode::UNLOCK_WHILE_RUNNING, std::to_string(ALL_SEGMENTS_SELECT_DATABASE().case_list().size()-1) ) - , START_CHECKPOINT_TUTORIAL( - "Start Checkpoint:", //
Program will start with this checkpoint. - TUTORIAL_CHECKPOINTS_SELECT_DATABASE(), - LockMode::LOCK_WHILE_RUNNING, - "0" - ) - , END_CHECKPOINT_TUTORIAL( - "End Checkpoint:", //
Program will stop after completing this checkpoint. - TUTORIAL_CHECKPOINTS_SELECT_DATABASE(), - LockMode::UNLOCK_WHILE_RUNNING, - std::to_string(INDEX_OF_LAST_TUTORIAL_CHECKPOINT) - ) - , START_CHECKPOINT_MAINSTORY( - "Start Checkpoint:", //
Program will start with this checkpoint. - MAINSTORY_CHECKPOINTS_SELECT_DATABASE(), - LockMode::LOCK_WHILE_RUNNING, - std::to_string(INDEX_OF_LAST_TUTORIAL_CHECKPOINT+1) - ) - , END_CHECKPOINT_MAINSTORY( - "End Checkpoint:", //
Program will stop after completing this checkpoint. - MAINSTORY_CHECKPOINTS_SELECT_DATABASE(), - LockMode::UNLOCK_WHILE_RUNNING, - std::to_string(ALL_CHECKPOINTS_SELECT_DATABASE().case_list().size()-1) - ) + // The end is read after each checkpoint, so it stays unlocked. + , TUTORIAL_CHECKPOINTS("Tutorial Checkpoints", TUTORIAL_CHECKPOINTS_SELECT_DATABASE(), LockMode::UNLOCK_WHILE_RUNNING) + , MAINSTORY_CHECKPOINTS("Main Story Checkpoints", MAINSTORY_CHECKPOINTS_SELECT_DATABASE(), LockMode::UNLOCK_WHILE_RUNNING) , SETUP_NOTE{ "NOTE: Make sure you have selected the correct Start Point. " "Make sure your player character is in the exact correct start position for that Start Point, " @@ -710,11 +694,11 @@ AutoStory::AutoStory() PA_ADD_OPTION(ENDPOINT_MAINSTORY); PA_ADD_OPTION(END_DESCRIPTION); - PA_ADD_OPTION(START_CHECKPOINT_TUTORIAL); - PA_ADD_OPTION(START_CHECKPOINT_MAINSTORY); + add_option(TUTORIAL_CHECKPOINTS.START_CHECKPOINT, "START_CHECKPOINT_TUTORIAL"); + add_option(MAINSTORY_CHECKPOINTS.START_CHECKPOINT, "START_CHECKPOINT_MAINSTORY"); PA_ADD_OPTION(START_CHECKPOINT_DESCRIPTION); - PA_ADD_OPTION(END_CHECKPOINT_TUTORIAL); - PA_ADD_OPTION(END_CHECKPOINT_MAINSTORY); + add_option(TUTORIAL_CHECKPOINTS.END_CHECKPOINT, "END_CHECKPOINT_TUTORIAL"); + add_option(MAINSTORY_CHECKPOINTS.END_CHECKPOINT, "END_CHECKPOINT_MAINSTORY"); PA_ADD_OPTION(END_CHECKPOINT_DESCRIPTION); PA_ADD_OPTION(STARTERCHOICE); @@ -738,10 +722,10 @@ AutoStory::AutoStory() STARTPOINT_MAINSTORY.add_listener(*this); ENDPOINT_MAINSTORY.add_listener(*this); - START_CHECKPOINT_TUTORIAL.add_listener(*this); - END_CHECKPOINT_TUTORIAL.add_listener(*this); - START_CHECKPOINT_MAINSTORY.add_listener(*this); - END_CHECKPOINT_MAINSTORY.add_listener(*this); + TUTORIAL_CHECKPOINTS.START_CHECKPOINT.add_listener(*this); + TUTORIAL_CHECKPOINTS.END_CHECKPOINT.add_listener(*this); + MAINSTORY_CHECKPOINTS.START_CHECKPOINT.add_listener(*this); + MAINSTORY_CHECKPOINTS.END_CHECKPOINT.add_listener(*this); ENABLE_ADVANCED_MODE.add_listener(*this); @@ -769,10 +753,10 @@ void AutoStory::on_config_value_changed(void* object){ STARTPOINT_MAINSTORY.set_visibility(mainstory_segments ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); ENDPOINT_MAINSTORY.set_visibility(mainstory_segments ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); - START_CHECKPOINT_TUTORIAL.set_visibility(tutorial_checkpoints ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); - END_CHECKPOINT_TUTORIAL.set_visibility(tutorial_checkpoints ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); - START_CHECKPOINT_MAINSTORY.set_visibility(mainstory_checkpoints ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); - END_CHECKPOINT_MAINSTORY.set_visibility(mainstory_checkpoints ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); + TUTORIAL_CHECKPOINTS.START_CHECKPOINT.set_visibility(tutorial_checkpoints ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); + TUTORIAL_CHECKPOINTS.END_CHECKPOINT.set_visibility(tutorial_checkpoints ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); + MAINSTORY_CHECKPOINTS.START_CHECKPOINT.set_visibility(mainstory_checkpoints ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); + MAINSTORY_CHECKPOINTS.END_CHECKPOINT.set_visibility(mainstory_checkpoints ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); MAINSTORY_NOTE.set_visibility(STORY_SECTION == StorySection::TUTORIAL ? ConfigOptionState::HIDDEN : ConfigOptionState::ENABLED); START_DESCRIPTION.set_text(start_segment_description()); @@ -1063,20 +1047,22 @@ std::string AutoStory::end_checkpoint_description(){ return " End: " + ALL_AUTO_STORY_CHECKPOINT_LIST()[checkpoint_index]->end_text(); } +const Pokemon::StoryRangeOptions& AutoStory::checkpoint_range() const{ + return STORY_SECTION == StorySection::MAIN_STORY ? MAINSTORY_CHECKPOINTS : TUTORIAL_CHECKPOINTS; +} + size_t AutoStory::get_start_checkpoint_index(){ - const bool main_story = STORY_SECTION == StorySection::MAIN_STORY; return story_index( - main_story, - main_story ? START_CHECKPOINT_MAINSTORY.index() : START_CHECKPOINT_TUTORIAL.index(), + STORY_SECTION == StorySection::MAIN_STORY, + checkpoint_range().start_index(), INDEX_OF_LAST_TUTORIAL_CHECKPOINT + 1 ); } size_t AutoStory::get_end_checkpoint_index(){ - const bool main_story = STORY_SECTION == StorySection::MAIN_STORY; return story_index( - main_story, - main_story ? END_CHECKPOINT_MAINSTORY.index() : END_CHECKPOINT_TUTORIAL.index(), + STORY_SECTION == StorySection::MAIN_STORY, + checkpoint_range().end_index(), INDEX_OF_LAST_TUTORIAL_CHECKPOINT + 1 ); } @@ -1216,8 +1202,8 @@ void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContex } if (ENABLE_ADVANCED_MODE){ - if (get_start_checkpoint_index() > get_end_checkpoint_index()){ - throw UserSetupError(env.logger(), "The start checkpoint cannot be later than the end segment."); + if (!checkpoint_range().check_validity().empty()){ + throw UserSetupError(env.logger(), checkpoint_range().check_validity()); } }else{ @@ -1230,7 +1216,7 @@ void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContex require_player(env.console, context, BUTTON_L); if (ENABLE_ADVANCED_MODE){ - env.console.log("Start Checkpoint " + ALL_AUTO_STORY_CHECKPOINT_LIST()[get_start_checkpoint_index()]->name(), COLOR_ORANGE); + env.console.log(Pokemon::checkpoint_start_line(ALL_AUTO_STORY_CHECKPOINT_LIST()[get_start_checkpoint_index()]->name()), COLOR_ORANGE); }else{ env.console.log("Start Segment " + ALL_AUTO_STORY_SEGMENT_LIST()[get_start_segment_index()]->name(), COLOR_ORANGE); } diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.h index d62d9b2ad2..b2ca877499 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.h +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.h @@ -16,6 +16,7 @@ #include "CommonTools/Options/StringSelectOption.h" #include "CommonTools/Options/LanguageOCROption.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "Pokemon/Options/Pokemon_StoryRangeOptions.h" #include "PokemonSV_AutoStoryTools.h" namespace PokemonAutomation{ @@ -69,6 +70,9 @@ class AutoStory : public SingleSwitchProgramInstance, public ConfigOption::Liste std::string start_checkpoint_description(); std::string end_checkpoint_description(); + // The checkpoint range of the chosen section. + const Pokemon::StoryRangeOptions& checkpoint_range() const; + private: OCR::LanguageOCROption LANGUAGE; @@ -85,11 +89,11 @@ class AutoStory : public SingleSwitchProgramInstance, public ConfigOption::Liste StringSelectOption STARTPOINT_MAINSTORY; StringSelectOption ENDPOINT_MAINSTORY; - StringSelectOption START_CHECKPOINT_TUTORIAL; - StringSelectOption END_CHECKPOINT_TUTORIAL; - - StringSelectOption START_CHECKPOINT_MAINSTORY; - StringSelectOption END_CHECKPOINT_MAINSTORY; + // The shared start/end checkpoint range of each section. Their + // dropdowns are added to this program's options directly, under the + // keys saved settings already use. + Pokemon::StoryRangeOptions TUTORIAL_CHECKPOINTS; + Pokemon::StoryRangeOptions MAINSTORY_CHECKPOINTS; StaticTextOption SETUP_NOTE; StaticTextOption MAINSTORY_NOTE; diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp index c2d61152df..759350295e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp @@ -1445,7 +1445,7 @@ void checkpoint_reattempt_loop( save_game_from_overworld(env.program_info(), env.console, context); } - env.console.log(checkpoint_text + " Num attempts: " + std::to_string(i)); + env.console.log(Pokemon::checkpoint_attempt_line(checkpoint_text, i + 1)); context.wait_for_all_requests(); action(i); @@ -1479,7 +1479,7 @@ void checkpoint_reattempt_loop( ); } context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); + env.console.log(Pokemon::checkpoint_reset_line(checkpoint_text, i + 2)); reset_game(env.program_info(), env.console, context); stats.m_reset++; env.update_stats(); @@ -1507,7 +1507,7 @@ void checkpoint_reattempt_loop_tutorial( send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); } - env.console.log(checkpoint_text + " Num attempts: " + std::to_string(i)); + env.console.log(Pokemon::checkpoint_attempt_line(checkpoint_text, i + 1)); context.wait_for_all_requests(); action(i); @@ -1538,7 +1538,7 @@ void checkpoint_reattempt_loop_tutorial( ); } context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); + env.console.log(Pokemon::checkpoint_reset_line(checkpoint_text, i + 2)); reset_game(env.program_info(), env.console, context); stats.m_reset++; env.update_stats(); diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h index e39d8a47da..312533cde7 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h @@ -7,6 +7,7 @@ #ifndef PokemonAutomation_PokemonSV_AutoStoryTools_H #define PokemonAutomation_PokemonSV_AutoStoryTools_H +#include #include #include "CommonFramework/Language.h" #include "CommonFramework/ImageTools/ImageBoxes.h" @@ -15,6 +16,7 @@ #include "ML/Inference/ML_YOLONavigation.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "Pokemon/AutoStory/Pokemon_AutoStoryStats.h" +#include "Pokemon/AutoStory/Pokemon_StoryLog.h" #include "VideoGames/PokemonSV/Programs/PokemonSV_WorldNavigation.h" namespace PokemonAutomation{ @@ -108,7 +110,7 @@ class AutoStory_Checkpoint { AutoStoryStats& stats) const = 0; std::string checkpoint_text() const { - return "Checkpoint:: " + name() + ". Start point: " + start_text(); + return std::format("{}. Start point: {}", name(), start_text()); } }; From ab559c968320e102d25b18f55c3996a23c6e4786 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 01:00:21 -0800 Subject: [PATCH 005/110] Pokemon Navigation: shared fault classes and per-class fault counters for the sims Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../ComputerPrograms_UnitTestRunner.cpp | 2 + .../Simulation/Pokemon_SimFaults.cpp | 94 +++++++++++ .../Navigation/Simulation/Pokemon_SimFaults.h | 109 ++++++++++++ .../Simulation/Pokemon_SimFaults_Tests.cpp | 157 ++++++++++++++++++ .../Simulation/Pokemon_SimFaults_Tests.h | 23 +++ SerialPrograms/cmake/SourceFiles.cmake | 4 + 6 files changed, 389 insertions(+) create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.h diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 45575d5d68..e9710fd73f 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -41,6 +41,7 @@ #include "Pokemon/Navigation/Pokemon_RouteLog_Tests.h" #include "Pokemon/Navigation/Pokemon_RuntimeMap_Tests.h" #include "Pokemon/Navigation/Pokemon_WallRecovery_Tests.h" +#include "Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.h" #include "Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.h" #include "VideoGames/PokemonHome/PokemonHome_Tests.h" #include "VideoGames/PokemonSwSh/PokemonSwSh_Tests.h" @@ -86,6 +87,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_MapData(ret); Pokemon::add_tests_RuntimeMap(ret); Pokemon::add_tests_RouteLog(ret); + Pokemon::add_tests_SimFaults(ret); Pokemon::add_tests_SimGolden(ret); Pokemon::add_tests_AutoStory(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.cpp new file mode 100644 index 0000000000..6d0bf64fb4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.cpp @@ -0,0 +1,94 @@ +/* Sim Faults + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_SimFaults.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const std::vector& fault_classes(){ + static const std::vector classes{ + FaultClass::SCENE_END_POSE, + FaultClass::SCENE_EARLY, + FaultClass::BATTLE_OPENING, + FaultClass::WILD_BATTLES, + FaultClass::LATE_FADE, + FaultClass::SLOW_FADE_IN, + FaultClass::WARP_NO_OP, + FaultClass::DARK_CAVE, + FaultClass::LOST_TAP, + FaultClass::UNSEEN_STEP, + }; + return classes; +} + +std::string_view fault_class_name(FaultClass fault){ + switch (fault){ + case FaultClass::SCENE_END_POSE: + return "scene end pose"; + case FaultClass::SCENE_EARLY: + return "scene early"; + case FaultClass::BATTLE_OPENING: + return "battle opening"; + case FaultClass::WILD_BATTLES: + return "wild battles"; + case FaultClass::LATE_FADE: + return "late fade"; + case FaultClass::SLOW_FADE_IN: + return "slow fade-in"; + case FaultClass::WARP_NO_OP: + return "warp no-op"; + case FaultClass::DARK_CAVE: + return "dark cave"; + case FaultClass::LOST_TAP: + return "lost tap"; + case FaultClass::UNSEEN_STEP: + return "unseen step"; + } + return "?"; +} + + +FaultOccurrences::FaultOccurrences(std::set faulted) + : m_numbers(std::move(faulted)) +{} + +bool FaultOccurrences::next(){ + m_chances++; + if (!m_numbers.contains(m_chances)){ + return false; + } + m_faulted++; + return true; +} + + +SimFaults::SimFaults(std::map> faulted){ + for (auto& [fault, numbers] : faulted){ + m_classes.emplace(fault, FaultOccurrences(std::move(numbers))); + } +} + +bool SimFaults::next(FaultClass fault){ + return m_classes[fault].next(); +} + +int SimFaults::chances(FaultClass fault) const{ + const auto iter = m_classes.find(fault); + return iter == m_classes.end() ? 0 : iter->second.chances(); +} + +int SimFaults::faulted(FaultClass fault) const{ + const auto iter = m_classes.find(fault); + return iter == m_classes.end() ? 0 : iter->second.faulted(); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.h b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.h new file mode 100644 index 0000000000..f58b09b854 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.h @@ -0,0 +1,109 @@ +/* Sim Faults + * + * From: https://github.com/PokemonAutomation/ + * + * The faults the games' overworld simulations inject, shared by BDSP's + * and FRLG's: the classes of failure the consoles showed, and a counter + * per class that says which of a fault's chances to fault. A chance is + * each time the sim reaches a point where the game could fail that way + * (a tap, a warp, a step's end); a test names the chances it faults by + * number, from 1 in the order the sim reaches them. + * + * How a class is injected is each game's (its sim's knobs and its fault + * sweep); a game may inject only some of the classes. + * + */ + +#ifndef PokemonAutomation_Pokemon_SimFaults_H +#define PokemonAutomation_Pokemon_SimFaults_H + +#include +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A class of failure a console showed, which a sim can inject. +enum class FaultClass{ + // A step whose end the game sets (a talk, a scene, a battle) leaves the + // player on another walkable tile next to the expected one. + SCENE_END_POSE, + // A scene starts on the last tiles of the walk before it. + SCENE_EARLY, + // A battle's opening is still playing when a step starts. + BATTLE_OPENING, + // Wild battles while walking, more than a clean run meets. + WILD_BATTLES, + // A warp's fade shows late. + LATE_FADE, + // Every warp's fade-in runs long: a move right after it goes nowhere. + SLOW_FADE_IN, + // A step onto a warp shows the fade's black but does not warp. + WARP_NO_OP, + // A dark cave walked without Flash. + DARK_CAVE, + // A tap the game drops. + LOST_TAP, + // A step tap that moved the player, read as not moved. + UNSEEN_STEP, +}; + +// Every fault class, in the enum's order. +const std::vector& fault_classes(); + +// The class's name for logs: "scene end pose". +std::string_view fault_class_name(FaultClass fault); + + +// Which chances of one fault to fault: those numbered in `faulted`, +// counted from 1 as next() reaches them. +class FaultOccurrences{ +public: + FaultOccurrences() = default; + explicit FaultOccurrences(std::set faulted); + + // Counts one more chance: whether it is one to fault. + bool next(); + + // The chances counted so far. + int chances() const{ + return m_chances; + } + // How many of them were faulted. + int faulted() const{ + return m_faulted; + } + +private: + std::set m_numbers; + int m_chances = 0; + int m_faulted = 0; +}; + + +// A FaultOccurrences per fault class: a class not given counts its +// chances and faults none. +class SimFaults{ +public: + SimFaults() = default; + explicit SimFaults(std::map> faulted); + + // Counts one more chance of `fault`: whether it is one to fault. + bool next(FaultClass fault); + + // The chances of `fault` counted so far, and how many were faulted. + int chances(FaultClass fault) const; + int faulted(FaultClass fault) const; + +private: + std::map m_classes; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp new file mode 100644 index 0000000000..c7ac4b7008 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp @@ -0,0 +1,157 @@ +/* Sim Faults Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The fault counters on their own: which chances a counter faults, what + * it counts, that each class counts apart, and the classes' names. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon_SimFaults.h" +#include "Pokemon_SimFaults_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +struct SimFaultsInput{ + std::string name; + UnitTestResult (*body)(); +}; + +struct SimFaultsExpectation{ + std::string_view description; +}; + +struct SimFaultsTestCase{ + SimFaultsInput input; + SimFaultsExpectation expectation; +}; + +class Test_SimFaults : public UnitTest{ +public: + explicit Test_SimFaults(SimFaultsTestCase scenario) + : UnitTest("Pokemon::Navigation - Sim faults: " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_scenario.input.body(); + } + +private: + SimFaultsTestCase m_scenario; +}; + +// What `chances` chances of FaultClass::LOST_TAP did with `faulted` +// named, taken as a game's sim takes them, a chance of +// FaultClass::WARP_NO_OP (none named) after each. +struct Counted{ + std::vector faulted_at; + int chances = 0; + int faulted = 0; + int other_chances = 0; + int other_faulted = 0; + int never_reached = 0; +}; + +Counted count(const std::set& faulted, int chances){ + SimFaults faults({{FaultClass::LOST_TAP, faulted}}); + Counted out; + for (int chance = 1; chance <= chances; chance++){ + if (faults.next(FaultClass::LOST_TAP)){ + out.faulted_at.push_back(chance); + } + faults.next(FaultClass::WARP_NO_OP); + } + out.chances = faults.chances(FaultClass::LOST_TAP); + out.faulted = faults.faulted(FaultClass::LOST_TAP); + out.other_chances = faults.chances(FaultClass::WARP_NO_OP); + out.other_faulted = faults.faulted(FaultClass::WARP_NO_OP); + out.never_reached = faults.chances(FaultClass::DARK_CAVE); + return out; +} + +// "[1, 3]". +std::string numbers_text(const std::vector& numbers){ + std::string out; + for (int number : numbers){ + out += out.empty() ? std::format("{}", number) : std::format(", {}", number); + } + return std::format("[{}]", out); +} + +UnitTestResult expect_counted(const std::set& faulted, int chances, const std::vector& faulted_at){ + const Counted counted = count(faulted, chances); + if (counted.faulted_at != faulted_at){ + return std::format("Faulted chances {}, expected {}.", numbers_text(counted.faulted_at), numbers_text(faulted_at)); + } + if (counted.chances != chances || counted.faulted != (int)faulted_at.size()){ + return std::format("Counted {} chances, {} faulted; expected {}, {}.", counted.chances, counted.faulted, chances, faulted_at.size()); + } + if (counted.other_chances != chances || counted.other_faulted != 0){ + return std::format("The other class counted {} chances, {} faulted; expected {}, 0.", counted.other_chances, counted.other_faulted, chances); + } + if (counted.never_reached != 0){ + return std::format("A class never reached counted {} chances.", counted.never_reached); + } + return true; +} + +UnitTestResult test_none_named(){ + return expect_counted({}, 3, {}); +} + +UnitTestResult test_named_from_one(){ + return expect_counted({1, 3}, 4, {1, 3}); +} + +UnitTestResult test_never_reached(){ + return expect_counted({2, 9}, 3, {2}); +} + +UnitTestResult test_no_chances(){ + return expect_counted({1}, 0, {}); +} + +UnitTestResult test_class_names(){ + std::map seen; + for (FaultClass fault : fault_classes()){ + const std::string_view name = fault_class_name(fault); + if (name == "?" || !seen.emplace(name, fault).second){ + return std::format("Fault class {} has no name of its own: {}", static_cast(fault), name); + } + } + return true; +} + +const SimFaultsTestCase SIM_FAULTS_CASES[] = { + {.input = {.name = "none named faults none", .body = test_none_named}, .expectation = {.description = "3 chances, none faulted"}}, + {.input = {.name = "the named chances are faulted, from 1", .body = test_named_from_one}, .expectation = {.description = "1 and 3 of 4 faulted"}}, + {.input = {.name = "a chance never reached is not faulted", .body = test_never_reached}, .expectation = {.description = "2 of 3 faulted, 9 never reached"}}, + {.input = {.name = "no chances, nothing counted", .body = test_no_chances}, .expectation = {.description = "0 chances, none faulted"}}, + {.input = {.name = "each class has its own name", .body = test_class_names}, .expectation = {.description = "no two classes share a name"}}, +}; + +} // namespace + + +void add_tests_SimFaults(UnitTestDatabase& database){ + for (const SimFaultsTestCase& scenario : SIM_FAULTS_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.h new file mode 100644 index 0000000000..000b660a23 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.h @@ -0,0 +1,23 @@ +/* Sim Faults Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_SimFaults_Tests_H +#define PokemonAutomation_Pokemon_SimFaults_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers the sim fault counter tests. +void add_tests_SimFaults(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index dc1aad5e85..32169ccf96 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1500,6 +1500,10 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_RouteLog.h Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.h + Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.cpp + Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.h + Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp + Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.h Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp From 9d45af848daac9617d8ee6d8931c42b1497bb722 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 01:39:18 -0800 Subject: [PATCH 006/110] BDSP AutoStory: the fault sweep's classes are the shared ones The sweep uses Pokemon::FaultClass (GRASS_BATTLES is WILD_BATTLES there) and keeps its own names for the sweeps, so the test names and goldens stay as they are. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...PokemonBDSP_AutoStory_FaultSweep_Tests.cpp | 43 +++++++++++-------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp index 8375ffbecc..55795a11da 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp @@ -13,7 +13,7 @@ * (00.02's Starly, lab-B 2026-11-09), at each battle step and at each * step after a walk, which can end in a trainer's sight or in grass. * SimWorldKnobs::battle_opening_before. - * - GRASS_BATTLES: a wild battle on every pass through tall grass, one + * - WILD_BATTLES: a wild battle on every pass through tall grass, one * each 8 grass tiles (00.04, lab-B 2026-11-09 16:14: four in a row on * Route 201, each replan back through the grass, "too many plans"). * SimWorldKnobs::grass. One variant a row: the whole row so. @@ -54,6 +54,7 @@ #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" #include "Pokemon/Navigation/Pokemon_MapData.h" +#include "Pokemon/Navigation/Simulation/Pokemon_SimFaults.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WalkRules.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" @@ -72,29 +73,29 @@ using Pokemon::StoryStep; using Pokemon::StoryStepKind; using Pokemon::TilePos; -enum class FaultClass{ - SCENE_END_POSE, - BATTLE_OPENING, - GRASS_BATTLES, - SCENE_EARLY, - SLOW_FADE_IN, - // Not swept yet: the measured movement table's lost taps (#293). - LOST_TAP, -}; -std::string_view fault_class_name(FaultClass fault){ +using Pokemon::FaultClass; + +// The sweep's name for `fault`: the class and how BDSP's sim injects it. +// Not swept yet: LOST_TAP, the measured movement table's lost taps +// (#293), and the classes only FRLG's sim injects. +std::string_view sweep_name(FaultClass fault){ switch (fault){ case FaultClass::SCENE_END_POSE: return "scene end pose"; case FaultClass::BATTLE_OPENING: return "battle opening at step start"; - case FaultClass::GRASS_BATTLES: + case FaultClass::WILD_BATTLES: return "wild battles on every grass pass"; case FaultClass::SCENE_EARLY: return "scene starts during the walk before it"; case FaultClass::SLOW_FADE_IN: return "slow fade-in after every warp"; case FaultClass::LOST_TAP: - return "lost tap"; + case FaultClass::LATE_FADE: + case FaultClass::WARP_NO_OP: + case FaultClass::DARK_CAVE: + case FaultClass::UNSEEN_STEP: + return Pokemon::fault_class_name(fault); } return "?"; } @@ -251,13 +252,13 @@ struct SweepFailure{ }; UnitTestResult sweep_result(Logger& logger, FaultClass fault, const std::string& row, size_t variants, const std::vector& failures){ - logger.log(std::format("Fault sweep {} {}: {} variants, {} fail.", row, fault_class_name(fault), variants, failures.size())); + logger.log(std::format("Fault sweep {} {}: {} variants, {} fail.", row, sweep_name(fault), variants, failures.size())); if (failures.empty()){ return true; } std::string out = std::format("{} of {} variants fail {}:", failures.size(), variants, row); for (const SweepFailure& failure : failures){ - logger.log(std::format("| {} | {} | {} | {} | {} |", row, failure.step, fault_class_name(fault), failure.variant, failure.stopped)); + logger.log(std::format("| {} | {} | {} | {} | {} |", row, failure.step, sweep_name(fault), failure.variant, failure.stopped)); out += std::format("\n {} {}: {}", failure.step, failure.variant, failure.stopped); } return out; @@ -321,7 +322,7 @@ UnitTestResult sweep_grass_battles(Logger& logger, const StoryCheckpoint& row){ if (!stopped.empty()){ failures.push_back({"", "a battle each 8 grass tiles", stopped}); } - return sweep_result(logger, FaultClass::GRASS_BATTLES, row.id, 1, failures); + return sweep_result(logger, FaultClass::WILD_BATTLES, row.id, 1, failures); } // Row `row` with every warp's fade-in slow, all through the row. @@ -412,7 +413,7 @@ const StoryCheckpoint& table_row(const std::string& id){ class Test_AutoStoryFaultSweep : public UnitTest{ public: explicit Test_AutoStoryFaultSweep(FaultSweepCase test_case) - : UnitTest(std::format("PokemonBDSP::AutoStory - Fault sweep: {}, {}", test_case.input.row, fault_class_name(test_case.input.fault))) + : UnitTest(std::format("PokemonBDSP::AutoStory - Fault sweep: {}, {}", test_case.input.row, sweep_name(test_case.input.fault))) , m_fault(test_case.input.fault) , m_row(table_row(test_case.input.row)) {} @@ -446,13 +447,17 @@ class Test_AutoStoryFaultSweep : public UnitTest{ return sweep_scene_end_pose(logger, m_row); case FaultClass::BATTLE_OPENING: return sweep_battle_opening(logger, m_row); - case FaultClass::GRASS_BATTLES: + case FaultClass::WILD_BATTLES: return sweep_grass_battles(logger, m_row); case FaultClass::SCENE_EARLY: return sweep_scene_early(logger, m_row); case FaultClass::SLOW_FADE_IN: return sweep_slow_fade_in(logger, m_row); case FaultClass::LOST_TAP: + case FaultClass::LATE_FADE: + case FaultClass::WARP_NO_OP: + case FaultClass::DARK_CAVE: + case FaultClass::UNSEEN_STEP: break; } return true; @@ -467,7 +472,7 @@ class Test_AutoStoryFaultSweep : public UnitTest{ const FaultSweepCase FAULT_SWEEP_CASES[] = { {.input = {.fault = FaultClass::SCENE_END_POSE}, .expectation = {}}, {.input = {.fault = FaultClass::BATTLE_OPENING}, .expectation = {}}, - {.input = {.fault = FaultClass::GRASS_BATTLES}, .expectation = {}}, + {.input = {.fault = FaultClass::WILD_BATTLES}, .expectation = {}}, {.input = {.fault = FaultClass::SCENE_EARLY}, .expectation = {}}, {.input = {.fault = FaultClass::SLOW_FADE_IN}, .expectation = {}}, }; From 625bc00718eaed8d5ffe07f0ac6f82f4397f0895 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 10:50:09 -0800 Subject: [PATCH 007/110] runtime-map-tests: link Pokemon_Direction.cpp (MapData uses direction_name) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- devtools/runtime-map-tests/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/devtools/runtime-map-tests/CMakeLists.txt b/devtools/runtime-map-tests/CMakeLists.txt index 8a91248664..eb200ef5cc 100644 --- a/devtools/runtime-map-tests/CMakeLists.txt +++ b/devtools/runtime-map-tests/CMakeLists.txt @@ -11,6 +11,7 @@ add_library(RuntimeMapDecoder STATIC "${NAV}/Pokemon_RuntimeMap.cpp" "${NAV}/Pokemon_MapData.cpp" "${NAV}/Pokemon_Grid.cpp" + "${NAV}/Pokemon_Direction.cpp" "${ROOT}/Common/Cpp/Exceptions.cpp" "${ROOT}/Common/Cpp/Json/JsonValue.cpp" "${ROOT}/Common/Cpp/Json/JsonObject.cpp" From f10f18ffc0d0349017f0c65f9f40cfe5adc4b362 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:15:33 -0800 Subject: [PATCH 008/110] StoryRun tests: one case struct per UnitTest (code-health test-case rule) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StoryRun_Tests.cpp | 151 +++++++++++++++--- 1 file changed, 128 insertions(+), 23 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp index a45f39b5a4..0b47fa5138 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp @@ -260,10 +260,24 @@ const FirstSaveCase FIRST_SAVE_CASES[] = { // A failed attempt's reload loads the save through the game. +struct ReloadInput{ + std::string name; +}; +struct ReloadExpectation{ + size_t loads; + size_t rereads; + std::string log_line; +}; +struct ReloadCase{ + ReloadInput input; + ReloadExpectation expectation; +}; + class Test_StoryReload : public UnitTest{ public: - Test_StoryReload() - : UnitTest("Pokemon::StoryRun - a retry reloads the save") + Test_StoryReload(const ReloadCase& test_case) + : UnitTest(std::format("Pokemon::StoryRun - {}", test_case.input.name)) + , m_case(test_case) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -272,20 +286,46 @@ class Test_StoryReload : public UnitTest{ SegmentHooks hooks = story_segment_hooks(game); RunState state; const Outcome outcome = hooks.reload(state); - if (!outcome.succeeded() || fake.loads != 1 || fake.rereads != 1 || !fake.logged("[Story] retry: loading the save")){ - return std::format("Expected one load and reread, got {} and {} ({})", fake.loads, fake.rereads, to_string(outcome)); + const ReloadExpectation& expected = m_case.expectation; + if (!outcome.succeeded() || fake.loads != expected.loads || fake.rereads != expected.rereads || !fake.logged(expected.log_line)){ + return std::format("Expected {} load and {} reread, got {} and {} ({})", expected.loads, expected.rereads, fake.loads, fake.rereads, to_string(outcome)); } return true; } + +private: + const ReloadCase m_case; +}; + +const ReloadCase RELOAD_CASES[] = { + { + .input = {.name = "a retry reloads the save"}, + .expectation = {.loads = 1, .rereads = 1, .log_line = "[Story] retry: loading the save"}, + }, }; // A run that stopped short throws, logs the failure line and touches // nothing in the game: no reload, no save, no reset to HOME. +struct FailureInput{ + std::string name; + std::string checkpoint; + std::string event; + std::string stopped_after; +}; +struct FailureExpectation{ + std::string message; +}; +struct FailureCase{ + FailureInput input; + FailureExpectation expectation; +}; + class Test_StoryFailureLeavesGame : public UnitTest{ public: - Test_StoryFailureLeavesGame() - : UnitTest("Pokemon::StoryRun - a failed run leaves the game where it failed") + Test_StoryFailureLeavesGame(const FailureCase& test_case) + : UnitTest(std::format("Pokemon::StoryRun - {}", test_case.input.name)) + , m_case(test_case) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -293,18 +333,18 @@ class Test_StoryFailureLeavesGame : public UnitTest{ StoryGameHooks game = fake.hooks(); SegmentReport report; report.completed = false; - report.failed_checkpoint = "00.04b"; - report.failed_event = "talk_mom"; + report.failed_checkpoint = m_case.input.checkpoint; + report.failed_event = m_case.input.event; report.failure = outcome_failed("expect_failed", "dialogue opened"); AutoStoryStats stats; std::string message; try{ - finish_story_run(report, "00.05", stats, game); + finish_story_run(report, m_case.input.stopped_after, stats, game); return "Expected an OperationFailedException"; }catch (OperationFailedException& e){ message = e.message(); } - if (message != "AutoStory stopped at 00.04b talk_mom: expect_failed: dialogue opened"){ + if (message != m_case.expectation.message){ return std::format("Unexpected message: {}", message); } if (!fake.logged(STORY_LEFT_WHERE_FAILED)){ @@ -315,14 +355,37 @@ class Test_StoryFailureLeavesGame : public UnitTest{ } return true; } + +private: + const FailureCase m_case; +}; + +const FailureCase FAILURE_CASES[] = { + { + .input = {.name = "a failed run leaves the game where it failed", .checkpoint = "00.04b", .event = "talk_mom", .stopped_after = "00.05"}, + .expectation = {.message = "AutoStory stopped at 00.04b talk_mom: expect_failed: dialogue opened"}, + }, }; // A completed run logs and returns the line the finish notification sends. +struct FinishedInput{ + std::string name; + std::string last_checkpoint; +}; +struct FinishedExpectation{ + std::string line; +}; +struct FinishedCase{ + FinishedInput input; + FinishedExpectation expectation; +}; + class Test_StoryFinished : public UnitTest{ public: - Test_StoryFinished() - : UnitTest("Pokemon::StoryRun - a completed run is done through its last checkpoint") + Test_StoryFinished(const FinishedCase& test_case) + : UnitTest(std::format("Pokemon::StoryRun - {}", test_case.input.name)) + , m_case(test_case) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -331,20 +394,44 @@ class Test_StoryFinished : public UnitTest{ SegmentReport report; report.completed = true; AutoStoryStats stats; - const std::string done = finish_story_run(report, "00.05", stats, game); - if (done != "AutoStory: done through 00.05." || !fake.logged(done)){ + const std::string done = finish_story_run(report, m_case.input.last_checkpoint, stats, game); + if (done != m_case.expectation.line || !fake.logged(done)){ return std::format("Unexpected finish line: {}", done); } return true; } + +private: + const FinishedCase m_case; +}; + +const FinishedCase FINISHED_CASES[] = { + { + .input = {.name = "a completed run is done through its last checkpoint", .last_checkpoint = "00.05"}, + .expectation = {.line = "AutoStory: done through 00.05."}, + }, }; // A verify run short of its passes throws with the summary. +struct VerifyInput{ + std::string name; + std::string checkpoint; + size_t passes; +}; +struct VerifyExpectation{ + std::string message; +}; +struct VerifyCase{ + VerifyInput input; + VerifyExpectation expectation; +}; + class Test_StoryVerifyFailed : public UnitTest{ public: - Test_StoryVerifyFailed() - : UnitTest("Pokemon::StoryRun - an unverified checkpoint fails with its summary") + Test_StoryVerifyFailed(const VerifyCase& test_case) + : UnitTest(std::format("Pokemon::StoryRun - {}", test_case.input.name)) + , m_case(test_case) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -352,20 +439,30 @@ class Test_StoryVerifyFailed : public UnitTest{ StoryGameHooks game = fake.hooks(); VerifyPolicy policy; VerifyReport report; - report.passes = 1; + report.passes = m_case.input.passes; report.verified = false; std::string message; try{ - finish_story_verify("00.15b", policy, report, game); + finish_story_verify(m_case.input.checkpoint, policy, report, game); return "Expected an OperationFailedException"; }catch (OperationFailedException& e){ message = e.message(); } - if (message != "AutoStory verify: 00.15b 1/3 passed, 2 needed." || !fake.logged(STORY_LEFT_WHERE_FAILED)){ + if (message != m_case.expectation.message || !fake.logged(STORY_LEFT_WHERE_FAILED)){ return std::format("Unexpected message: {}", message); } return true; } + +private: + const VerifyCase m_case; +}; + +const VerifyCase VERIFY_CASES[] = { + { + .input = {.name = "an unverified checkpoint fails with its summary", .checkpoint = "00.15b", .passes = 1}, + .expectation = {.message = "AutoStory verify: 00.15b 1/3 passed, 2 needed."}, + }, }; } // namespace @@ -381,10 +478,18 @@ void add_tests_StoryRun(UnitTestDatabase& database){ for (const FirstSaveCase& test_case : FIRST_SAVE_CASES){ database.add(test_case); } - database.add(); - database.add(); - database.add(); - database.add(); + for (const ReloadCase& test_case : RELOAD_CASES){ + database.add(test_case); + } + for (const FailureCase& test_case : FAILURE_CASES){ + database.add(test_case); + } + for (const FinishedCase& test_case : FINISHED_CASES){ + database.add(test_case); + } + for (const VerifyCase& test_case : VERIFY_CASES){ + database.add(test_case); + } } From ea9b142d530a95c70c3bcee13bf01e948d398a9c Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:33:34 -0800 Subject: [PATCH 009/110] Tests: nest Input and Expectation inside each native test case struct Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon_AuthoredCheckpointJson_Tests.cpp | 32 ++--- .../Data/Pokemon_StoryStepJson_Tests.cpp | 32 ++--- .../Pokemon_StoryEnginePolicy_Tests.cpp | 128 +++++++++--------- .../Engine/Pokemon_StoryEngineRuns_Tests.cpp | 52 +++---- .../Engine/Pokemon_StoryEngine_Tests.cpp | 98 +++++++------- .../Pokemon_AutoStoryStats_Tests.cpp | 32 ++--- .../AutoStory/Pokemon_ScreenEvents_Tests.cpp | 19 ++- .../AutoStory/Pokemon_StoryEvents_Tests.cpp | 20 +-- .../AutoStory/Pokemon_StoryLog_Tests.cpp | 26 ++-- .../Pokemon_StorySavePolicy_Tests.cpp | 26 ++-- .../AutoStory/Pokemon_StorySegments_Tests.cpp | 20 +-- .../Pokemon_StoryStepExecutor_Tests.cpp | 20 +-- .../Types/Pokemon_StoryActionArg_Tests.cpp | 28 ++-- .../Navigation/Pokemon_LegPlanner_Tests.cpp | 20 +-- .../Navigation/Pokemon_LegWalker_Tests.cpp | 20 +-- .../Navigation/Pokemon_MapData_Tests.cpp | 20 +-- .../Navigation/Pokemon_RouteLog_Tests.cpp | 18 +-- .../Navigation/Pokemon_RuntimeMap_Tests.cpp | 24 ++-- .../Navigation/Pokemon_WallRecovery_Tests.cpp | 50 +++---- .../Pokemon_StoryRangeOptions_Tests.cpp | 36 ++--- 20 files changed, 360 insertions(+), 361 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp index 147fa168a9..ae61bbc538 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp @@ -33,24 +33,24 @@ enum class Failure{ MISSING_RESOURCE, }; -struct AuthoredInput{ - std::string name; - std::string json; - std::string game = "frlg"; - bool resource = false; - std::string file = "plan"; -}; +struct AuthoredCase{ + struct Input{ + std::string name; + std::string json; + std::string game = "frlg"; + bool resource = false; + std::string file = "plan"; + }; -struct AuthoredExpectation{ - std::string checkpoint = "00.05"; - std::string execution = R"({"menu":"before_pokedex"})"; - std::vector events = {"first", "second"}; - Failure failure = Failure::NONE; -}; + struct Expectation{ + std::string checkpoint = "00.05"; + std::string execution = R"({"menu":"before_pokedex"})"; + std::vector events = {"first", "second"}; + Failure failure = Failure::NONE; + }; -struct AuthoredCase{ - AuthoredInput input; - AuthoredExpectation expectation; + Input input; + Expectation expectation; }; const AuthoredCase CASES[] = { diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp index 0433258cbb..69f213ad13 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp @@ -36,28 +36,28 @@ enum class Record{ CHECKPOINT, }; -// A record to read, and which kind it is. -struct WireInput{ - std::string_view name; - Record record = Record::STEP; - std::string_view json; -}; - // What a read gives. using ReadRecord = std::variant; // "" when the record read is as expected, else what differs. using ReadCheck = std::string (*)(const ReadRecord& record); -// What reading it gives: a record the check accepts, or a rejection. -struct WireExpectation{ - ReadCheck check = nullptr; - bool rejected = false; -}; - struct WireCase{ - WireInput input; - WireExpectation expectation; + // A record to read, and which kind it is. + struct Input{ + std::string_view name; + Record record = Record::STEP; + std::string_view json; + }; + + // What reading it gives: a record the check accepts, or a rejection. + struct Expectation{ + ReadCheck check = nullptr; + bool rejected = false; + }; + + Input input; + Expectation expectation; }; std::string expect(bool ok, std::string_view what){ @@ -201,7 +201,7 @@ std::vector test_actions(){ // `input` read. -ReadRecord read_record(const WireInput& input){ +ReadRecord read_record(const WireCase::Input& input){ static const std::vector actions = test_actions(); const JsonValue value = parse_json(std::string(input.json)); switch (input.record){ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy_Tests.cpp index 1a208e8862..7dfd736896 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy_Tests.cpp @@ -83,29 +83,29 @@ StoryGame engine_game(std::optional candies){ -// One engine run of 00.31 in `phase`, the player ending on `end_map`. -struct EngineInput{ - std::string_view name; - std::string_view phase; - HashRecord hash = HashRecord::MATCHING; - std::string_view steps = TALK_STEPS; - // Where the talk leaves the player; empty: the talk opens no text. - std::string_view end_map = "RocketHideout_B3F"; - std::optional candies = 2; -}; +struct EngineCase{ + // One engine run of 00.31 in `phase`, the player ending on `end_map`. + struct Input{ + std::string_view name; + std::string_view phase; + HashRecord hash = HashRecord::MATCHING; + std::string_view steps = TALK_STEPS; + // Where the talk leaves the player; empty: the talk opens no text. + std::string_view end_map = "RocketHideout_B3F"; + std::optional candies = 2; + }; -// The save mode chosen, the verdict, whether the game saved (each save -// logs "[Test] save") and a line the run logged. -struct EngineExpectation{ - StorySaveMode mode = StorySaveMode::NONE; - CheckpointVerdict verdict = CheckpointVerdict::PASSED; - size_t saves = 0; - std::string_view line = {}; -}; + // The save mode chosen, the verdict, whether the game saved (each save + // logs "[Test] save") and a line the run logged. + struct Expectation{ + StorySaveMode mode = StorySaveMode::NONE; + CheckpointVerdict verdict = CheckpointVerdict::PASSED; + size_t saves = 0; + std::string_view line = {}; + }; -struct EngineCase{ - EngineInput input; - EngineExpectation expectation; + Input input; + Expectation expectation; }; const EngineCase ENGINE_CASES[] = { @@ -201,23 +201,23 @@ class StoryEngineSaveTest : public UnitTest{ -// Two checkpoints' events, hashed with the built-in actions. -struct HashInput{ - std::string_view name; - std::string_view a; - std::string_view b; -}; +struct HashCase{ + // Two checkpoints' events, hashed with the built-in actions. + struct Input{ + std::string_view name; + std::string_view a; + std::string_view b; + }; -// Whether they hash the same, and `a`'s hash when pinned: a change to it -// means every recorded verification goes stale. -struct HashExpectation{ - bool same = true; - std::optional hash_a = std::nullopt; -}; + // Whether they hash the same, and `a`'s hash when pinned: a change to it + // means every recorded verification goes stale. + struct Expectation{ + bool same = true; + std::optional hash_a = std::nullopt; + }; -struct HashCase{ - HashInput input; - HashExpectation expectation; + Input input; + Expectation expectation; }; inline constexpr std::string_view ROUTE_B3F = R"([{"id": "go", "kind": "route", "args": {"target": {"map": "RocketHideout_B3F", "tiles": [[12, 13]]}}}])"; @@ -271,23 +271,23 @@ class StoryStepsHashTest : public UnitTest{ -// A checkpoint's "metadata", read. -struct MetadataInput{ - std::string_view name; - std::string_view metadata; -}; +struct MetadataCase{ + // A checkpoint's "metadata", read. + struct Input{ + std::string_view name; + std::string_view metadata; + }; -// The error the read throws (contained), or what it read. -struct MetadataExpectation{ - std::string_view error = {}; - StoryPhase phase = StoryPhase::TESTING; - std::string_view steps_hash = {}; - size_t items = 0; -}; + // The error the read throws (contained), or what it read. + struct Expectation{ + std::string_view error = {}; + StoryPhase phase = StoryPhase::TESTING; + std::string_view steps_hash = {}; + size_t items = 0; + }; -struct MetadataCase{ - MetadataInput input; - MetadataExpectation expectation; + Input input; + Expectation expectation; }; const MetadataCase METADATA_CASES[] = { @@ -341,21 +341,21 @@ class StoryMetadataTest : public UnitTest{ -// What a look showed, classified by ScreenMachine states that match on -// observations. -struct ScreenInput{ - std::string_view name; - std::vector events; -}; +struct ScreenCase{ + // What a look showed, classified by ScreenMachine states that match on + // observations. + struct Input{ + std::string_view name; + std::vector events; + }; -// The state matched; none when no state did. -struct ScreenExpectation{ - std::optional state = std::nullopt; -}; + // The state matched; none when no state did. + struct Expectation{ + std::optional state = std::nullopt; + }; -struct ScreenCase{ - ScreenInput input; - ScreenExpectation expectation; + Input input; + Expectation expectation; }; const ScreenCase SCREEN_CASES[] = { diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp index d272a19648..e15bd54774 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp @@ -585,22 +585,22 @@ std::string segment_no_reload_for_console_only(CancellableScope& scope){ // Gap 7: the first checkpoint is retried after a reload; one after it // only when the one before saved at its end (#329). -struct SegmentInput{ - std::string_view name; - StoryPhase phase; - // Which checkpoint fails once: 0 or 1. - size_t flaky = 0; -}; +struct SegmentCase{ + struct Input{ + std::string_view name; + StoryPhase phase; + // Which checkpoint fails once: 0 or 1. + size_t flaky = 0; + }; -struct SegmentExpectation{ - bool completed = false; - size_t reloads = 0; - size_t saves = 0; -}; + struct Expectation{ + bool completed = false; + size_t reloads = 0; + size_t saves = 0; + }; -struct SegmentCase{ - SegmentInput input; - SegmentExpectation expectation; + Input input; + Expectation expectation; }; const SegmentCase SEGMENT_CASES[] = { @@ -675,20 +675,20 @@ std::string verify_saves_after_all_passed(CancellableScope& scope){ } -// One check above, by name. -struct RunsInput{ - std::string_view name; - std::string (*check)(CancellableScope& scope); -}; +struct RunsCase{ + // One check above, by name. + struct Input{ + std::string_view name; + std::string (*check)(CancellableScope& scope); + }; -// The check's error: none. -struct RunsExpectation{ - std::string_view error = {}; -}; + // The check's error: none. + struct Expectation{ + std::string_view error = {}; + }; -struct RunsCase{ - RunsInput input; - RunsExpectation expectation; + Input input; + Expectation expectation; }; const RunsCase RUNS_CASES[] = { diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp index 4548921c9b..4e16d05e13 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp @@ -127,24 +127,24 @@ StoryStep make_step(StoryStepKind kind, std::string action, StoryActionArgs args -// A step checked and, when it lints clean, dispatched on a backend that -// shows talk text once, then the overworld. -struct RegistryInput{ - std::string_view name; - StoryStep step; -}; - -// The lint errors joined by "; ", then (for a clean step) the failure and -// the inputs sent. -struct RegistryExpectation{ - std::string_view lint = {}; - std::string_view failure = {}; - std::string_view inputs = {}; -}; - struct RegistryCase{ - RegistryInput input; - RegistryExpectation expectation; + // A step checked and, when it lints clean, dispatched on a backend that + // shows talk text once, then the overworld. + struct Input{ + std::string_view name; + StoryStep step; + }; + + // The lint errors joined by "; ", then (for a clean step) the failure and + // the inputs sent. + struct Expectation{ + std::string_view lint = {}; + std::string_view failure = {}; + std::string_view inputs = {}; + }; + + Input input; + Expectation expectation; }; const RegistryCase REGISTRY_CASES[] = { @@ -208,26 +208,26 @@ class StoryActionRegistryTest : public UnitTest{ -// One step, read from JSON, run by the step runner on a backend that -// shows the overworld, with `flags` set and the "door_open" reader -// reading `door_open`. -struct RunnerInput{ - std::string_view name; - std::string_view step; - std::vector flags = {}; - std::optional door_open = std::nullopt; -}; - -// The failure, a line the run logged and the map of the outcome's pose. -struct RunnerExpectation{ - std::string_view failure = {}; - std::string_view line = {}; - std::string_view pose_map = {}; -}; - struct RunnerCase{ - RunnerInput input; - RunnerExpectation expectation; + // One step, read from JSON, run by the step runner on a backend that + // shows the overworld, with `flags` set and the "door_open" reader + // reading `door_open`. + struct Input{ + std::string_view name; + std::string_view step; + std::vector flags = {}; + std::optional door_open = std::nullopt; + }; + + // The failure, a line the run logged and the map of the outcome's pose. + struct Expectation{ + std::string_view failure = {}; + std::string_view line = {}; + std::string_view pose_map = {}; + }; + + Input input; + Expectation expectation; }; const RunnerCase RUNNER_CASES[] = { @@ -283,20 +283,20 @@ class StoryStepRunnerTest : public UnitTest{ -// take_warp north to B3F, from B4F, on a scripted game. -struct WarpInput{ - std::string_view name; - std::vector> looks; -}; - -// How take_warp ended: "" for arrived. -struct WarpExpectation{ - std::string_view failure = {}; -}; - struct WarpCase{ - WarpInput input; - WarpExpectation expectation; + // take_warp north to B3F, from B4F, on a scripted game. + struct Input{ + std::string_view name; + std::vector> looks; + }; + + // How take_warp ended: "" for arrived. + struct Expectation{ + std::string_view failure = {}; + }; + + Input input; + Expectation expectation; }; const WarpCase WARP_CASES[] = { diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp index 453a975516..044c77b930 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp @@ -18,23 +18,23 @@ namespace Pokemon{ namespace{ -// Counts added to fresh stats, in order. -struct StoryCountsInput{ - std::string name; - std::vector added; -}; - -// The stats after them: counts add up rather than replace. -struct StoryCountsExpectation{ - uint64_t segments; - uint64_t checkpoints; - uint64_t resets; -}; - // Counts recorded into the AutoStory stats and the totals they must reach. struct StoryCountsCase{ - StoryCountsInput input; - StoryCountsExpectation expectation; + // Counts added to fresh stats, in order. + struct Input{ + std::string name; + std::vector added; + }; + + // The stats after them: counts add up rather than replace. + struct Expectation{ + uint64_t segments; + uint64_t checkpoints; + uint64_t resets; + }; + + Input input; + Expectation expectation; }; class Test_StoryCounts : public UnitTest{ @@ -49,7 +49,7 @@ class Test_StoryCounts : public UnitTest{ for (const StoryRunCounts& counts : m_case.input.added){ record_story_counts(counts, stats); } - const StoryCountsExpectation& expected = m_case.expectation; + const StoryCountsCase::Expectation& expected = m_case.expectation; if (stats.m_segment != expected.segments || stats.m_checkpoint != expected.checkpoints || stats.m_reset != expected.resets){ return std::format( "Expected {} segments, {} checkpoints and {} resets, got {}, {} and {}", diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp index 82aae9bf03..f7c7e32402 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp @@ -131,17 +131,16 @@ UnitTestResult test_watcher(){ } -struct ScreenEventsInput{ - std::string name; - std::function body; -}; - -struct ScreenEventsExpectation{ -}; - struct ScreenEventsCase{ - ScreenEventsInput input; - ScreenEventsExpectation expectation; + struct Input{ + std::string name; + std::function body; + }; + struct Expectation{ + }; + + Input input; + Expectation expectation; }; class Test_ScreenEvents : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp index a1d485644e..cafb66cd54 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp @@ -611,18 +611,18 @@ UnitTestResult test_lint(){ } -struct StoryEventInput{ - std::string name; - UnitTestResult (*test)(); -}; +struct StoryEventTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; -struct StoryEventExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct StoryEventTestCase{ - StoryEventInput input; - StoryEventExpectation expectation; + Input input; + Expectation expectation; }; class Test_StoryEvents : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp index 1cc32c258b..5172022a55 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp @@ -16,21 +16,21 @@ namespace Pokemon{ namespace{ -// A formatter's line, made when the table is built. -struct StoryLogInput{ - std::string name; - std::string line; -}; - -// The exact line: the lab watcher and the engine tests read these. -struct StoryLogExpectation{ - std::string line; -}; - // One formatter call and the line it must make. struct StoryLogCase{ - StoryLogInput input; - StoryLogExpectation expectation; + // A formatter's line, made when the table is built. + struct Input{ + std::string name; + std::string line; + }; + + // The exact line: the lab watcher and the engine tests read these. + struct Expectation{ + std::string line; + }; + + Input input; + Expectation expectation; }; class Test_StoryLog : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.cpp index bae25ec95a..72dcc9961a 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.cpp @@ -391,21 +391,21 @@ UnitTestResult test_end_pose_from_the_plan(){ } -// The scenario to run. -struct SavePolicyInput{ - std::string name; - UnitTestResult (*test)() = nullptr; -}; - -// What the scenario checks; it returns its own failure. -struct SavePolicyExpectation{ - std::string_view description; -}; - // A save-policy scenario and its expected result. struct SavePolicyCase{ - SavePolicyInput input; - SavePolicyExpectation expectation; + // The scenario to run. + struct Input{ + std::string name; + UnitTestResult (*test)() = nullptr; + }; + + // What the scenario checks; it returns its own failure. + struct Expectation{ + std::string_view description; + }; + + Input input; + Expectation expectation; }; class Test_StorySavePolicy : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp index c4073dd8d5..efcacab7ca 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp @@ -407,18 +407,18 @@ UnitTestResult test_describe(){ } -struct StorySegmentInput{ - std::string name; - UnitTestResult (*test)(); -}; +struct StorySegmentTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; -struct StorySegmentExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct StorySegmentTestCase{ - StorySegmentInput input; - StorySegmentExpectation expectation; + Input input; + Expectation expectation; }; class Test_StorySegments : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp index 1d9ef32865..e22aa36eea 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp @@ -727,18 +727,18 @@ UnitTestResult test_lint(){ } -struct StoryStepInput{ - std::string name; - UnitTestResult (*test)(); -}; +struct StoryStepTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; -struct StoryStepExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct StoryStepTestCase{ - StoryStepInput input; - StoryStepExpectation expectation; + Input input; + Expectation expectation; }; class Test_StoryStepExecutor : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp index 50cda4ade3..d26fb413e3 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp @@ -36,21 +36,21 @@ const StoryActionSpec& mart_spec(){ return spec; } -// Args checked against the Mart's spec, then filled in. -struct ArgsInput{ - std::string_view name; - StoryActionArgs args; -}; - -// The errors joined by "; ", and the args with their fallbacks. -struct ArgsExpectation{ - std::string_view error = {}; - StoryActionArgs filled = {}; -}; - struct ArgsCase{ - ArgsInput input; - ArgsExpectation expectation; + // Args checked against the Mart's spec, then filled in. + struct Input{ + std::string_view name; + StoryActionArgs args; + }; + + // The errors joined by "; ", and the args with their fallbacks. + struct Expectation{ + std::string_view error = {}; + StoryActionArgs filled = {}; + }; + + Input input; + Expectation expectation; }; const ArgsCase CASES[] = { diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp index 0d2db0642b..eea9549166 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp @@ -329,18 +329,18 @@ UnitTestResult test_unreachable(){ } -struct LegPlannerInput{ - std::string name; - UnitTestResult (*test)(); -}; +struct LegPlannerTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; -struct LegPlannerExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct LegPlannerTestCase{ - LegPlannerInput input; - LegPlannerExpectation expectation; + Input input; + Expectation expectation; }; class Test_LegPlanner : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp index e676450cb0..a43e06f966 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp @@ -224,18 +224,18 @@ UnitTestResult test_watch_along(){ } -struct LegWalkerInput{ - std::string name; - UnitTestResult (*test)(); -}; +struct LegWalkerTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; -struct LegWalkerExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct LegWalkerTestCase{ - LegWalkerInput input; - LegWalkerExpectation expectation; + Input input; + Expectation expectation; }; class Test_LegWalker : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp index 25c3ecfcb8..fcf299992e 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp @@ -401,18 +401,18 @@ UnitTestResult test_built_in_maps(){ return true; } -struct MapDataTestInput{ - std::string name; - UnitTestResult (*test)(); -}; +struct MapDataTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; -struct MapDataTestExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct MapDataTestCase{ - MapDataTestInput input; - MapDataTestExpectation expectation; + Input input; + Expectation expectation; }; class Test_MapData : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp index 843fc32db0..5715211f01 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp @@ -22,16 +22,16 @@ namespace Pokemon{ namespace{ -struct RouteLogInput{ - std::string name; - std::string line; -}; -struct RouteLogExpectation{ - std::string expected; -}; struct RouteLogTestCase{ - RouteLogInput input; - RouteLogExpectation expectation; + struct Input{ + std::string name; + std::string line; + }; + struct Expectation{ + std::string expected; + }; + Input input; + Expectation expectation; }; class Test_RouteLog : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp index 343416ca4d..254d51fc68 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp @@ -18,19 +18,19 @@ namespace PokemonAutomation{ namespace Pokemon{ namespace{ -struct RuntimeMapInput{ - std::string_view name; - std::string_view fields; -}; - -struct RuntimeMapExpectation{ - std::string_view error = {}; - std::string_view normalized_fields = {}; -}; - struct RuntimeMapCase{ - RuntimeMapInput input; - RuntimeMapExpectation expectation; + struct Input{ + std::string_view name; + std::string_view fields; + }; + + struct Expectation{ + std::string_view error = {}; + std::string_view normalized_fields = {}; + }; + + Input input; + Expectation expectation; }; const std::string GOLDEN_V2 = R"( diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_WallRecovery_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_WallRecovery_Tests.cpp index f563a0f9aa..e3a68cfaa6 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_WallRecovery_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_WallRecovery_Tests.cpp @@ -69,21 +69,21 @@ std::string describe_holds(std::span holds){ } // Inputs and expectations are separate aggregates; each registered test owns one row. -struct CorridorInput{ - std::string name; - std::vector positions; - std::optional person; - size_t budget; -}; +struct CorridorTestCase{ + struct Input{ + std::string name; + std::vector positions; + std::optional person; + size_t budget; + }; -struct CorridorExpectation{ - std::optional first_anchor; - std::vector holds; -}; + struct Expectation{ + std::optional first_anchor; + std::vector holds; + }; -struct CorridorTestCase{ - CorridorInput input; - CorridorExpectation expectation; + Input input; + Expectation expectation; }; class Test_WallRecovery : public UnitTest{ @@ -187,20 +187,20 @@ class CornerPolicy{ } }; -struct CornerInput{ - std::string name; - std::array positions; - size_t budget; -}; +struct CornerTestCase{ + struct Input{ + std::string name; + std::array positions; + size_t budget; + }; -struct CornerExpectation{ - std::optional first_anchor; - std::vector holds; -}; + struct Expectation{ + std::optional first_anchor; + std::vector holds; + }; -struct CornerTestCase{ - CornerInput input; - CornerExpectation expectation; + Input input; + Expectation expectation; }; class Test_WallRecoveryCorner : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp index 4cd40b9e7e..a0f621aafa 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp @@ -47,25 +47,25 @@ const StringSelectDatabase& main_story_database(){ return database; } -// The start and end set by slug, as saved settings load them; empty -// leaves the default. -struct StoryRangeInput{ - std::string name; - std::string start_slug; - std::string end_slug; -}; - -// The indexes in the dropdown, and whether the range is valid. -struct StoryRangeExpectation{ - size_t start; - size_t end; - bool valid; -}; - // A range chosen in the main story's dropdowns and what the group reads from it. struct StoryRangeCase{ - StoryRangeInput input; - StoryRangeExpectation expectation; + // The start and end set by slug, as saved settings load them; empty + // leaves the default. + struct Input{ + std::string name; + std::string start_slug; + std::string end_slug; + }; + + // The indexes in the dropdown, and whether the range is valid. + struct Expectation{ + size_t start; + size_t end; + bool valid; + }; + + Input input; + Expectation expectation; }; class Test_StoryRange : public UnitTest{ @@ -83,7 +83,7 @@ class Test_StoryRange : public UnitTest{ if (!m_case.input.end_slug.empty()){ range.END_CHECKPOINT.set_by_slug(m_case.input.end_slug); } - const StoryRangeExpectation& expected = m_case.expectation; + const StoryRangeCase::Expectation& expected = m_case.expectation; if (range.start_index() != expected.start || range.end_index() != expected.end){ return std::format( "Expected indexes {} to {}, got {} to {}", From 3be04b248f3f1a409ab6fd83104b191498b1afac Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:34:29 -0800 Subject: [PATCH 010/110] Tests: nest Input and Expectation inside each native test case struct Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_Interrupts_Tests.cpp | 83 +++++++++-------- .../AutoStory/Pokemon_SceneJudges_Tests.cpp | 18 ++-- .../AutoStory/Pokemon_Transitions_Tests.cpp | 90 +++++++++---------- 3 files changed, 94 insertions(+), 97 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp index f321c506ab..c5d55435a2 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp @@ -186,17 +186,16 @@ UnitTestResult test_watcher_log(){ } -struct InterruptsInput{ - std::string name; - std::function body; -}; - -struct InterruptsExpectation{ -}; - struct InterruptsCase{ - InterruptsInput input; - InterruptsExpectation expectation; + struct Input{ + std::string name; + std::function body; + }; + struct Expectation{ + }; + + Input input; + Expectation expectation; }; class Test_Interrupts : public UnitTest{ @@ -214,23 +213,22 @@ class Test_Interrupts : public UnitTest{ }; -// A synthetic scene, and the window of it to judge. -struct ClassifyInput{ - std::string name; - std::vector frames; - int until_ms = 0; - InterruptKnobs knobs = {}; - int window_from_ms = 0; -}; - -struct ClassifyExpectation{ - // describe(verdict, T0). - std::string verdict; -}; - struct ClassifyCase{ - ClassifyInput input; - ClassifyExpectation expectation; + // A synthetic scene, and the window of it to judge. + struct Input{ + std::string name; + std::vector frames; + int until_ms = 0; + InterruptKnobs knobs = {}; + int window_from_ms = 0; + }; + struct Expectation{ + // describe(verdict, T0). + std::string verdict; + }; + + Input input; + Expectation expectation; }; class Test_InterruptClassify : public UnitTest{ @@ -240,7 +238,7 @@ class Test_InterruptClassify : public UnitTest{ , m_case(std::move(test_case)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const ClassifyInput& input = m_case.input; + const ClassifyCase::Input& input = m_case.input; const ScreenEventLog log = log_of(input.frames, input.until_ms); const InterruptWindow window{T0 + Milliseconds(input.window_from_ms), T0 + Milliseconds(input.until_ms)}; const InterruptVerdict verdict = classify_interrupt(log, window, input.knobs); @@ -252,22 +250,21 @@ class Test_InterruptClassify : public UnitTest{ }; -// A synthetic scene, classified over all of it, and the lags to time it. -struct StepTimeInput{ - std::string name; - std::vector frames; - int until_ms = 0; - std::vector lags; -}; - -struct StepTimeExpectation{ - // "+700 ms" from T0, or "none". - std::string step; -}; - struct StepTimeCase{ - StepTimeInput input; - StepTimeExpectation expectation; + // A synthetic scene, classified over all of it, and the lags to time it. + struct Input{ + std::string name; + std::vector frames; + int until_ms = 0; + std::vector lags; + }; + struct Expectation{ + // "+700 ms" from T0, or "none". + std::string step; + }; + + Input input; + Expectation expectation; }; class Test_InterruptStepTime : public UnitTest{ @@ -277,7 +274,7 @@ class Test_InterruptStepTime : public UnitTest{ , m_case(std::move(test_case)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const StepTimeInput& input = m_case.input; + const StepTimeCase::Input& input = m_case.input; const InterruptVerdict verdict = classify_interrupt(log_of(input.frames, input.until_ms), whole(input.until_ms), {}); const std::optional step = interrupt_step_time(verdict, input.lags); const std::string got = step diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp index 7073e27efb..33904b16f6 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp @@ -113,17 +113,17 @@ UnitTestResult test_talk_over(){ } -struct SceneJudgesInput{ - std::string name; - std::function body; -}; +struct SceneJudgesCase{ + struct Input{ + std::string name; + std::function body; + }; -struct SceneJudgesExpectation{ -}; + struct Expectation{ + }; -struct SceneJudgesCase{ - SceneJudgesInput input; - SceneJudgesExpectation expectation; + Input input; + Expectation expectation; }; class Test_SceneJudges : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp index ef4818a42e..75baebe6c3 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp @@ -78,25 +78,25 @@ std::string run_tracker(const std::vector& spans, TransitionTracker& track } -// A synthetic stream of frames, through one game's profile. -struct TrackInput{ - std::string name; - std::vector spans; - const FadeProfile* profile = &BDSP_FADE_PROFILE; - bool compare = true; -}; - -struct TrackExpectation{ - // The transitions completed, as run_tracker() puts them. - std::string transitions; - // What judge_warp() makes of the tracker's current() at the end; empty - // for none. - std::string warp = ""; -}; - struct TrackCase{ - TrackInput input; - TrackExpectation expectation; + // A synthetic stream of frames, through one game's profile. + struct Input{ + std::string name; + std::vector spans; + const FadeProfile* profile = &BDSP_FADE_PROFILE; + bool compare = true; + }; + + struct Expectation{ + // The transitions completed, as run_tracker() puts them. + std::string transitions; + // What judge_warp() makes of the tracker's current() at the end; empty + // for none. + std::string warp = ""; + }; + + Input input; + Expectation expectation; }; class Test_TransitionTracker : public UnitTest{ @@ -106,7 +106,7 @@ class Test_TransitionTracker : public UnitTest{ , m_case(std::move(test_case)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const TrackInput& input = m_case.input; + const TrackCase::Input& input = m_case.input; TransitionTracker tracker(*input.profile, input.compare ? compare_means : TransitionTracker::CompareScenes()); const std::string got = run_tracker(input.spans, tracker); if (got != m_case.expectation.transitions){ @@ -161,21 +161,21 @@ UnitTestResult test_sample_of_frame(){ } -// Captured frames: CommandLineTests//Transitions// holds -// frames named by their time in ms ("0.png", "250.png"), and expected.txt -// with the transitions run_tracker() should report (no scene comparison). -struct CapturedInput{ - std::string game; - const FadeProfile* profile; -}; - -// Each case folder's expected.txt holds its expectation. -struct CapturedExpectation{ -}; - struct CapturedCase{ - CapturedInput input; - CapturedExpectation expectation; + // Captured frames: CommandLineTests//Transitions// holds + // frames named by their time in ms ("0.png", "250.png"), and expected.txt + // with the transitions run_tracker() should report (no scene comparison). + struct Input{ + std::string game; + const FadeProfile* profile; + }; + + // Each case folder's expected.txt holds its expectation. + struct Expectation{ + }; + + Input input; + Expectation expectation; }; std::string track_captured_case(const Filesystem::Path& folder, const FadeProfile& profile){ @@ -226,22 +226,22 @@ class Test_CapturedTransitions : public UnitTest{ } private: - CapturedInput m_input; + CapturedCase::Input m_input; }; -struct TransitionsInput{ - std::string name; - UnitTestResult (*body)(); -}; +struct TransitionsCase{ + struct Input{ + std::string name; + UnitTestResult (*body)(); + }; -// The body checks its own expectations. -struct TransitionsExpectation{ -}; + // The body checks its own expectations. + struct Expectation{ + }; -struct TransitionsCase{ - TransitionsInput input; - TransitionsExpectation expectation; + Input input; + Expectation expectation; }; class Test_Transitions : public UnitTest{ @@ -255,7 +255,7 @@ class Test_Transitions : public UnitTest{ } private: - TransitionsInput m_input; + TransitionsCase::Input m_input; }; } // namespace From 3c4d8671e11387e5d80e873f972124262aa0bdaf Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:35:25 -0800 Subject: [PATCH 011/110] Tests: nest Input and Expectation inside each native test case struct Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StoryActions_Tests.cpp | 20 +-- .../Pokemon_StoryInterrupts_Tests.cpp | 20 +-- .../AutoStory/Pokemon_StoryRun_Tests.cpp | 142 +++++++++--------- .../Pokemon_ConnectedMaps_Tests.cpp | 68 +++++---- .../Pokemon_MoveMechanics_Tests.cpp | 22 +-- ...okemonFRLG_AutoStoryScreenEvents_Tests.cpp | 24 +-- 6 files changed, 149 insertions(+), 147 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp index 4e3b98983a..a4e8020210 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp @@ -253,18 +253,18 @@ UnitTestResult test_guard_stop_rethrows(){ } -struct StoryActionsInput{ - std::string_view name; - UnitTestResult (*test)(); -}; +struct StoryActionsCase{ + struct Input{ + std::string_view name; + UnitTestResult (*test)(); + }; -struct StoryActionsExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct StoryActionsCase{ - StoryActionsInput input; - StoryActionsExpectation expectation; + Input input; + Expectation expectation; }; class Test_StoryActions : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp index 234e0d926b..f02b59c42f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp @@ -592,18 +592,18 @@ UnitTestResult test_settle_of_a_look(){ } -struct StoryInterruptsInput{ - std::string_view name; - UnitTestResult (*test)(); -}; +struct StoryInterruptsCase{ + struct Input{ + std::string_view name; + UnitTestResult (*test)(); + }; -struct StoryInterruptsExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct StoryInterruptsCase{ - StoryInterruptsInput input; - StoryInterruptsExpectation expectation; + Input input; + Expectation expectation; }; class Test_StoryInterrupts : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp index 0b47fa5138..7d9f3d6e99 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp @@ -62,21 +62,21 @@ struct FakeGame{ }; // A start as the program asks for it, and what the game must have done. -struct StartInput{ - std::string name; - StoryStart start; - std::string place_error; - StoryPreflight preflight; -}; -struct StartExpectation{ - bool succeeds; - size_t loads; - size_t rereads; - bool save_loaded; -}; struct StartCase{ - StartInput input; - StartExpectation expectation; + struct Input{ + std::string name; + StoryStart start; + std::string place_error; + StoryPreflight preflight; + }; + struct Expectation{ + bool succeeds; + size_t loads; + size_t rereads; + bool save_loaded; + }; + Input input; + Expectation expectation; }; constexpr StoryPreflight READY{.video_alive = true, .controller_ready = true, .game_running = true}; @@ -176,16 +176,16 @@ const StartCase START_CASES[] = { // A preflight's checks, and the failure it reads as: the setup's, not // the story's, naming every check that failed. -struct PreflightInput{ - std::string name; - StoryPreflight preflight; -}; -struct PreflightExpectation{ - std::string outcome; -}; struct PreflightCase{ - PreflightInput input; - PreflightExpectation expectation; + struct Input{ + std::string name; + StoryPreflight preflight; + }; + struct Expectation{ + std::string outcome; + }; + Input input; + Expectation expectation; }; class Test_StoryPreflight : public UnitTest{ @@ -223,15 +223,15 @@ const PreflightCase PREFLIGHT_CASES[] = { // Whether the first checkpoint saves at its start: only a new game's. After // a load the save is already there; from the game as it is the place is // unconfirmed (console B, 2026-11-11: "save" ran first on HOME). -struct FirstSaveInput{ - StoryStart start; -}; -struct FirstSaveExpectation{ - bool saves; -}; struct FirstSaveCase{ - FirstSaveInput input; - FirstSaveExpectation expectation; + struct Input{ + StoryStart start; + }; + struct Expectation{ + bool saves; + }; + Input input; + Expectation expectation; }; class Test_StoryFirstSave : public UnitTest{ @@ -260,17 +260,17 @@ const FirstSaveCase FIRST_SAVE_CASES[] = { // A failed attempt's reload loads the save through the game. -struct ReloadInput{ - std::string name; -}; -struct ReloadExpectation{ - size_t loads; - size_t rereads; - std::string log_line; -}; struct ReloadCase{ - ReloadInput input; - ReloadExpectation expectation; + struct Input{ + std::string name; + }; + struct Expectation{ + size_t loads; + size_t rereads; + std::string log_line; + }; + Input input; + Expectation expectation; }; class Test_StoryReload : public UnitTest{ @@ -307,18 +307,18 @@ const ReloadCase RELOAD_CASES[] = { // A run that stopped short throws, logs the failure line and touches // nothing in the game: no reload, no save, no reset to HOME. -struct FailureInput{ - std::string name; - std::string checkpoint; - std::string event; - std::string stopped_after; -}; -struct FailureExpectation{ - std::string message; -}; struct FailureCase{ - FailureInput input; - FailureExpectation expectation; + struct Input{ + std::string name; + std::string checkpoint; + std::string event; + std::string stopped_after; + }; + struct Expectation{ + std::string message; + }; + Input input; + Expectation expectation; }; class Test_StoryFailureLeavesGame : public UnitTest{ @@ -369,16 +369,16 @@ const FailureCase FAILURE_CASES[] = { // A completed run logs and returns the line the finish notification sends. -struct FinishedInput{ - std::string name; - std::string last_checkpoint; -}; -struct FinishedExpectation{ - std::string line; -}; struct FinishedCase{ - FinishedInput input; - FinishedExpectation expectation; + struct Input{ + std::string name; + std::string last_checkpoint; + }; + struct Expectation{ + std::string line; + }; + Input input; + Expectation expectation; }; class Test_StoryFinished : public UnitTest{ @@ -414,17 +414,17 @@ const FinishedCase FINISHED_CASES[] = { // A verify run short of its passes throws with the summary. -struct VerifyInput{ - std::string name; - std::string checkpoint; - size_t passes; -}; -struct VerifyExpectation{ - std::string message; -}; struct VerifyCase{ - VerifyInput input; - VerifyExpectation expectation; + struct Input{ + std::string name; + std::string checkpoint; + size_t passes; + }; + struct Expectation{ + std::string message; + }; + Input input; + Expectation expectation; }; class Test_StoryVerifyFailed : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp index ceafa9304d..788bfe9b84 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp @@ -68,14 +68,8 @@ std::string describe(const ConnectedMaps& world, const std::optional& return std::format("{} {}", world.map(place->map).name, to_string(place->tile)); } -// Where a step or a warp should put the player, or nothing for nowhere. -struct PlaceExpectation{ - std::optional place; -}; - // Why `actual` is not `expected`, if it is not. -std::optional mismatch(const ConnectedMaps& world, const std::optional& actual, const PlaceExpectation& expectation){ - const std::optional& expected = expectation.place; +std::optional mismatch(const ConnectedMaps& world, const std::optional& actual, const std::optional& expected){ std::optional wanted; if (expected){ wanted = MapPlace{*world.find(expected->map), expected->tile}; @@ -87,14 +81,18 @@ std::optional mismatch(const ConnectedMaps& world, const std::optio } -struct StepInput{ - std::string_view name; - NamedPlace from; - Direction direction; -}; struct StepCase{ - StepInput input; - PlaceExpectation expectation; + struct Input{ + std::string_view name; + NamedPlace from; + Direction direction; + }; + // Where the step should put the player, or nothing for nowhere. + struct Expectation{ + std::optional place; + }; + Input input; + Expectation expectation; }; class Test_ConnectedMaps_Step : public UnitTest{ @@ -104,9 +102,9 @@ class Test_ConnectedMaps_Step : public UnitTest{ {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ const ConnectedMaps world(test_maps()); - const StepInput& input = m_scenario.input; + const StepCase::Input& input = m_scenario.input; const MapPlace from{*world.find(input.from.map), input.from.tile}; - if (std::optional error = mismatch(world, world.neighbour(from, input.direction), m_scenario.expectation)){ + if (std::optional error = mismatch(world, world.neighbour(from, input.direction), m_scenario.expectation.place)){ return *error; } return true; @@ -159,13 +157,17 @@ const StepCase STEP_CASES[] = { }; -struct WarpInput{ - std::string_view name; - MapWarp warp; -}; struct WarpCase{ - WarpInput input; - PlaceExpectation expectation; + struct Input{ + std::string_view name; + MapWarp warp; + }; + // Where the warp should put the player, or nothing for nowhere. + struct Expectation{ + std::optional place; + }; + Input input; + Expectation expectation; }; class Test_ConnectedMaps_Warp : public UnitTest{ @@ -175,7 +177,7 @@ class Test_ConnectedMaps_Warp : public UnitTest{ {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ const ConnectedMaps world(test_maps()); - if (std::optional error = mismatch(world, world.warp_arrival(m_scenario.input.warp), m_scenario.expectation)){ + if (std::optional error = mismatch(world, world.warp_arrival(m_scenario.input.warp), m_scenario.expectation.place)){ return *error; } return true; @@ -204,17 +206,17 @@ const WarpCase WARP_CASES[] = { }; -struct StalePlaceInput{ - std::string_view name; - size_t map; -}; -struct StalePlaceExpectation{ - // Whether reading the place throws InternalProgramError. - bool rejected = false; -}; struct StalePlaceCase{ - StalePlaceInput input; - StalePlaceExpectation expectation; + struct Input{ + std::string_view name; + size_t map; + }; + struct Expectation{ + // Whether reading the place throws InternalProgramError. + bool rejected = false; + }; + Input input; + Expectation expectation; }; // A place whose map index is past the loaded maps (from another world, or diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp index c0de39e0f5..bf50a717ec 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp @@ -18,18 +18,18 @@ namespace Pokemon{ namespace{ -struct MoveMechanicsInput{ - std::string_view game; - MoveMechanics mechanics; -}; -struct MoveMechanicsExpectation{ - // How the walker presses an open leg on foot (the user's pick, - // 2026-11-11: BDSP taps, FRLG timed holds). - OpenLegPress open_legs_on_foot; -}; struct MoveMechanicsCase{ - MoveMechanicsInput input; - MoveMechanicsExpectation expectation; + struct Input{ + std::string_view game; + MoveMechanics mechanics; + }; + struct Expectation{ + // How the walker presses an open leg on foot (the user's pick, + // 2026-11-11: BDSP taps, FRLG timed holds). + OpenLegPress open_legs_on_foot; + }; + Input input; + Expectation expectation; }; // Why `faster` is not faster than `slower` on both axes, if it is not. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp index 8bd21ac0f9..f71a8a3aae 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp @@ -26,19 +26,19 @@ using Pokemon::ScreenEvents; namespace{ -struct ScreenEventsInput{ - std::string name; - // The frame's colour; 0 for no frame. - uint32_t color; -}; - -struct ScreenEventsExpectation{ - ScreenEvents events; -}; - struct ScreenEventsCase{ - ScreenEventsInput input; - ScreenEventsExpectation expectation; + struct Input{ + std::string name; + // The frame's colour; 0 for no frame. + uint32_t color; + }; + + struct Expectation{ + ScreenEvents events; + }; + + Input input; + Expectation expectation; }; class Test_AutoStoryScreenEvents : public UnitTest{ From b3990fd0304bc85b3b2d48d313df7a57c355d54d Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:35:42 -0800 Subject: [PATCH 012/110] Tests: nest Input and Expectation inside each native test case struct Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Simulation/Pokemon_SimGolden_Tests.cpp | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp index a71b34adc8..06b48f2f5f 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp @@ -20,18 +20,18 @@ namespace Pokemon{ namespace{ -struct SimGoldenInput{ - std::string name; - UnitTestResult (*body)(Logger& logger); -}; +struct SimGoldenTestCase{ + struct Input{ + std::string name; + UnitTestResult (*body)(Logger& logger); + }; -struct SimGoldenExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct SimGoldenTestCase{ - SimGoldenInput input; - SimGoldenExpectation expectation; + Input input; + Expectation expectation; }; class Test_SimGolden : public UnitTest{ From 373d5bc8822cbc9b38eb07f232f02ff13ec30d92 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:35:52 -0800 Subject: [PATCH 013/110] Tests: nest Input and Expectation inside each native test case struct Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Simulation/Pokemon_SimFaults_Tests.cpp | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp index c7ac4b7008..957a88e0bd 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp @@ -24,18 +24,18 @@ namespace Pokemon{ namespace{ -struct SimFaultsInput{ - std::string name; - UnitTestResult (*body)(); -}; +struct SimFaultsTestCase{ + struct Input{ + std::string name; + UnitTestResult (*body)(); + }; -struct SimFaultsExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct SimFaultsTestCase{ - SimFaultsInput input; - SimFaultsExpectation expectation; + Input input; + Expectation expectation; }; class Test_SimFaults : public UnitTest{ From b681c75f392ddadf1ec052447c416b0efd1889d5 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:41:39 -0800 Subject: [PATCH 014/110] StoryRun tests: use ReloadCase::Expectation in the reload test Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp index 7d9f3d6e99..78a24e0399 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp @@ -286,7 +286,7 @@ class Test_StoryReload : public UnitTest{ SegmentHooks hooks = story_segment_hooks(game); RunState state; const Outcome outcome = hooks.reload(state); - const ReloadExpectation& expected = m_case.expectation; + const ReloadCase::Expectation& expected = m_case.expectation; if (!outcome.succeeded() || fake.loads != expected.loads || fake.rereads != expected.rereads || !fake.logged(expected.log_line)){ return std::format("Expected {} load and {} reread, got {} and {} ({})", expected.loads, expected.rereads, fake.loads, fake.rereads, to_string(outcome)); } From 91d62357f5d04fbf7aa38fcfd1dd9fd5da1819e8 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:59:44 -0800 Subject: [PATCH 015/110] Review fixes: comment content, designated initializers, include placement, README counts Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon/Navigation/Pokemon_LegTypes.h | 3 ++- .../Pokemon/Navigation/Pokemon_LegWalker.h | 3 +-- .../Navigation/Pokemon_LegWalker_Tests.cpp | 26 +++++++++---------- .../Pokemon/Navigation/Pokemon_MapFeatures.h | 2 +- .../Pokemon/Navigation/Pokemon_MapTiles.h | 2 +- .../Pokemon/Navigation/Pokemon_RouteLog.h | 3 +-- .../Pokemon/Navigation/Pokemon_RouteLogLegs.h | 2 +- .../Navigation/Pokemon_RouteLogTypes.h | 2 +- .../Navigation/Pokemon_RuntimeMap_Tests.cpp | 5 ++-- devtools/runtime-map-tests/README.md | 9 ++++--- 10 files changed, 29 insertions(+), 28 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h index c1a7401c3b..c8b79dc4e6 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h @@ -2,7 +2,8 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_LegWalker.h, unchanged; it includes this header. + * A leg of a route walk: what to walk (LegSpec) and what the walk found (LegResult). + * Pokemon_LegWalker.h builds on it. * */ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h index 31be625cb4..c00ecc7910 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h @@ -68,8 +68,7 @@ LegResult walk_leg_with(const LegSpec& leg, const LegCalls& calls, size_t max_in // keeps whether it fired. A warp's fade can be over before the hold onto // the warp ends, so a wait for it that starts after the hold sees nothing: // the walk watches the hold with this, then waits on with the same watcher -// if it has not fired (FRLG 00.27, console B, 2026-11-09 01:41, the warp to -// CeruleanCity: the watch started 1.3 s into the hold and missed the fade). +// if it has not fired. class WatchAlong : public VisualInferenceCallback{ public: explicit WatchAlong(VisualInferenceCallback& watcher) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp index a43e06f966..10e2593ab0 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp @@ -57,13 +57,13 @@ struct ScriptedLeg{ // An interrupt set off by step `step`, seen DELAY after it ends. HoldOutcome after_step(int step){ - return HoldOutcome{0, TILE * step + DELAY}; + return HoldOutcome{.interrupt = 0, .elapsed = TILE * step + DELAY}; } UnitTestResult test_hold_times(){ - const LegSpec open{Direction::EAST, 4, false, TILE}; - const LegSpec wall{Direction::EAST, 4, true, TILE}; + const LegSpec open{.direction = Direction::EAST, .tiles = 4, .to_wall = false, .tile_time = TILE}; + const LegSpec wall{.direction = Direction::EAST, .tiles = 4, .to_wall = true, .tile_time = TILE}; if (leg_hold(open, 4) != TILE * 3 + TILE / 2){ return std::format("Open leg: {}ms", leg_hold(open, 4).count()); } @@ -83,7 +83,7 @@ UnitTestResult test_hold_times(){ } UnitTestResult test_tiles_before_interrupt(){ - const LegSpec leg{Direction::EAST, 8, false, TILE}; + const LegSpec leg{.direction = Direction::EAST, .tiles = 8, .to_wall = false, .tile_time = TILE}; for (int step = 0; step <= 8; step++){ for (Milliseconds jitter : {-100ms, 0ms, 100ms}){ const int walked = tiles_before_interrupt(leg, TILE * step + DELAY + jitter, DELAY, 8); @@ -104,7 +104,7 @@ UnitTestResult test_tiles_before_interrupt(){ UnitTestResult test_wall_leg_walked_again(){ ScriptedLeg script; script.outcomes = {after_step(2)}; - const LegSpec leg{Direction::NORTH, 6, true, TILE}; + const LegSpec leg{.direction = Direction::NORTH, .tiles = 6, .to_wall = true, .tile_time = TILE}; const LegResult result = walk_leg_with(leg, script.calls(), 5); if (script.holds.size() != 2 || script.holds[1] != leg_hold(leg, 6)){ return "Expected the whole leg held again."; @@ -118,7 +118,7 @@ UnitTestResult test_wall_leg_walked_again(){ UnitTestResult test_open_leg_rest_walked(){ ScriptedLeg script; script.outcomes = {after_step(2)}; - const LegSpec leg{Direction::NORTH, 6, false, TILE}; + const LegSpec leg{.direction = Direction::NORTH, .tiles = 6, .to_wall = false, .tile_time = TILE}; const LegResult result = walk_leg_with(leg, script.calls(), 5); if (script.holds.size() != 2 || script.holds[1] != leg_hold(leg, 4)){ return "Expected the remaining 4 tiles held."; @@ -132,7 +132,7 @@ UnitTestResult test_open_leg_rest_walked(){ UnitTestResult test_open_leg_interrupted_at_end(){ ScriptedLeg script; script.outcomes = {after_step(6)}; - const LegSpec leg{Direction::NORTH, 6, false, TILE}; + const LegSpec leg{.direction = Direction::NORTH, .tiles = 6, .to_wall = false, .tile_time = TILE}; walk_leg_with(leg, script.calls(), 5); if (script.holds.size() != 1){ return "Nothing was left to walk after the last step."; @@ -145,7 +145,7 @@ UnitTestResult test_open_leg_interrupted_at_end(){ UnitTestResult test_open_leg_stops(){ ScriptedLeg script; script.outcomes = {after_step(2)}; - LegSpec leg{Direction::NORTH, 6, false, TILE}; + LegSpec leg{.direction = Direction::NORTH, .tiles = 6, .to_wall = false, .tile_time = TILE}; leg.stop_on_interrupt = true; const LegResult result = walk_leg_with(leg, script.calls(), 5); if (script.holds.size() != 1 || !result.stopped || result.exact || script.cleared.size() != 1){ @@ -157,12 +157,12 @@ UnitTestResult test_open_leg_stops(){ return true; } -// Console B, 2026-11-01, run 16: held south into a sign, the leg to a wall -// was interrupted by its message 600ms into every hold, six times. +// Held south into a sign: the leg to a wall is interrupted by the sign's +// message 600ms into every hold, again and again. UnitTestResult test_wall_leg_blocked(){ ScriptedLeg script; - script.outcomes = {HoldOutcome{0, 2200ms}, HoldOutcome{0, 600ms}, HoldOutcome{0, 600ms}}; - LegSpec leg{Direction::SOUTH, 23, true, TILE}; + script.outcomes = {HoldOutcome{.interrupt = 0, .elapsed = 2200ms}, HoldOutcome{.interrupt = 0, .elapsed = 600ms}, HoldOutcome{.interrupt = 0, .elapsed = 600ms}}; + LegSpec leg{.direction = Direction::SOUTH, .tiles = 23, .to_wall = true, .tile_time = TILE}; leg.stop_if_blocked = true; const LegResult result = walk_leg_with(leg, script.calls(), 5); if (script.holds.size() != 2 || !result.stopped){ @@ -176,7 +176,7 @@ UnitTestResult test_too_many_interruptions(){ for (int c = 0; c < 4; c++){ script.outcomes.push_back(after_step(0)); } - const LegSpec leg{Direction::NORTH, 6, true, TILE}; + const LegSpec leg{.direction = Direction::NORTH, .tiles = 6, .to_wall = true, .tile_time = TILE}; try{ walk_leg_with(leg, script.calls(), 3); }catch (std::runtime_error&){ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h index e7af9fd8be..b39d50bbf7 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h @@ -2,7 +2,7 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_MapData.h, unchanged; it includes this header. + * The features a map's tiles can carry. Pokemon_MapData.h builds on it. * */ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h index 6f3cf1373e..63ebf79735 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h @@ -2,7 +2,7 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_MapData.h, unchanged; it includes this header. + * A map's tile grid. Pokemon_MapData.h builds on it. * */ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h index 17cdaef020..4a907f056d 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h @@ -4,8 +4,7 @@ * * The log lines a route walk writes, shared by the games' walkers so that * every game's log reads the same and devtools/maps can draw any run's - * routes from it. These are BDSP AutoStory's route lines, lifted from - * PokemonBDSP_AutoStory_RouteWalk.cpp, with what the other games need: + * routes from it. These are BDSP AutoStory's route lines, with what the other games need: * * [Route] To the grass: plan from Route 202 (15, 25), Route 202 (16, 25): east 15 (to wall) to Route 202 (23, 25), Route 202 (30, 26); north 5 (to wall) to Route 202 (23, 24) * [Route] Leg 1/2: east 15 (to wall) to Route 202 (23, 25), Route 202 (30, 26) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogLegs.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogLegs.h index bfe6778a8e..c1da9ce723 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogLegs.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogLegs.h @@ -2,7 +2,7 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_RouteLog.h, unchanged; it includes this header. + * The legs of a route as its log lines name them. Pokemon_RouteLog.h builds on it. * */ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h index c98a70d243..cbdd909b62 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h @@ -2,7 +2,7 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_RouteLog.h, unchanged; it includes this header. + * The types of a route log's lines. Pokemon_RouteLog.h builds on it. * */ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp index 254d51fc68..81a28b60e1 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp @@ -3,14 +3,15 @@ * From: https://github.com/PokemonAutomation/ */ #include -#include #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Json/JsonArray.h" #include "Common/Cpp/Json/JsonObject.h" #include "Pokemon_MapData.h" #include "Pokemon_RuntimeMap.h" -#ifndef PA_RUNTIME_MAP_STANDALONE +#ifdef PA_RUNTIME_MAP_STANDALONE +#include +#else #include "Pokemon_RuntimeMap_Tests.h" #endif diff --git a/devtools/runtime-map-tests/README.md b/devtools/runtime-map-tests/README.md index 18235bb554..77b34cd011 100644 --- a/devtools/runtime-map-tests/README.md +++ b/devtools/runtime-map-tests/README.md @@ -30,14 +30,15 @@ cmake --build /path/to/build -j4 ctest --test-dir /path/to/build --output-on-failure ``` -The focused target also runs all eight existing registered MapData cases, -including their legacy diagnostics and embedded map assets. The 26 new cases are registered in the application's native test +The focused target also runs the existing registered MapData cases, +including their legacy diagnostics and embedded map assets. The runtime-map cases are registered in the application's native test database. They cover v1 compatibility, mixed/malformed versions and pairs, inclusive wander bounds, object groups, interaction-vs-item rejection, coordinate events and complete normalized JSON parity, including unknown metadata. -For real data, prepare a clean PokemonSimulation checkout at -`40717c7c809c415c751fd7a348dfc1895f7ec3d7` (merged #53), then run: +For real data, prepare a clean PokemonSimulation checkout at the revision +that `.github/workflows/runtime-map-reader.yml` pins (CI passes it as +`--publisher-revision`; the script refuses any other), then run: ```sh python3 devtools/runtime-map-tests/prepare_parity.py \ From 2c1815bb44f52246c51f82138fb9b0c5fc860b88 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:01:15 -0800 Subject: [PATCH 016/110] Review fixes: comment content, optional instead of a max() sentinel, shared expect_equal, frame-name parsing Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon/AutoStory/Pokemon_FadeProfiles.h | 9 ++---- .../Pokemon/AutoStory/Pokemon_Interrupts.cpp | 2 ++ .../AutoStory/Pokemon_Interrupts_Tests.cpp | 11 ++----- .../Pokemon/AutoStory/Pokemon_SceneJudges.cpp | 32 +++++++++---------- .../Pokemon/AutoStory/Pokemon_SceneJudges.h | 19 +++++------ .../AutoStory/Pokemon_SceneJudges_Tests.cpp | 16 +++------- .../Pokemon/AutoStory/Pokemon_TestExpect.h | 31 ++++++++++++++++++ .../AutoStory/Pokemon_Transitions_Tests.cpp | 17 ++++++++-- .../Pokemon/AutoStory/Pokemon_WarpJudge.h | 3 +- SerialPrograms/cmake/SourceFiles.cmake | 1 + 10 files changed, 86 insertions(+), 55 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_FadeProfiles.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_FadeProfiles.h index a4dd2ac915..7a2ac6ac4e 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_FadeProfiles.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_FadeProfiles.h @@ -2,7 +2,8 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_Transitions.h, unchanged; it includes this header. + * Per-game fade thresholds (FadeProfile) and the transition kinds the tracker + * reports. Their definitions are in Pokemon_Transitions.cpp. * */ @@ -10,12 +11,8 @@ #define PokemonAutomation_Pokemon_FadeProfiles_H #include -#include -#include #include #include "Common/Cpp/Time.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -64,7 +61,7 @@ struct FadeProfile{ }; // BDSP. The uniform tier is the shared walk's (FADE_MAX_STDDEV_SUM, the -// Oreburgh Gate's textured floor is no fade, lab-B 2026-11-08); the partial +// Oreburgh Gate's textured floor is no fade); the partial // tier is run_into_door()'s 60, which caught the doorway's dim fade frames. // A cave mouth's fade is dim (45 to 64 a channel), hence the dark sum of 225. // The flash and white-fade holds are provisional: no console frames of an diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp index 53aedfbe7c..57740f5820 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp @@ -5,7 +5,9 @@ */ #include +#include #include +#include #include "Pokemon_Interrupts.h" namespace PokemonAutomation{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp index c5d55435a2..111d42035f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp @@ -8,7 +8,6 @@ */ #include -#include #include #include #include @@ -18,6 +17,7 @@ #include "Pokemon_Interrupts.h" #include "Pokemon_Interrupts_Tests.h" #include "Pokemon_ScreenEvents.h" +#include "Pokemon_TestExpect.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -28,13 +28,6 @@ using namespace std::chrono_literals; const WallClock T0 = WallClock() + std::chrono::hours(1); -UnitTestResult expect_equal(const std::string& what, const std::string& got, const std::string& expected){ - if (got == expected){ - return true; - } - return std::format("{}: expected \"{}\", got \"{}\"", what, expected, got); -} - // One frame of a synthetic scene: its events, at `ms` after T0. struct Frame{ int ms; @@ -189,7 +182,7 @@ UnitTestResult test_watcher_log(){ struct InterruptsCase{ struct Input{ std::string name; - std::function body; + UnitTestResult (*body)(); }; struct Expectation{ }; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp index 4ded229245..bc587ba860 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp @@ -33,37 +33,37 @@ std::string describe(const WarpSeen& seen){ } -SceneMove TalkOver::look(const ScreenEvents& look, WallClock now){ - if (look.has(ScreenEvent::BATTLE_STARTED)){ - m_quiet_since = WallClock::max(); - m_calm_since = WallClock::max(); +SceneMove TalkOver::look(const ScreenEvents& events, WallClock now){ + if (events.has(ScreenEvent::BATTLE_STARTED)){ + m_quiet_since.reset(); + m_calm_since.reset(); return SceneMove::BATTLE; } - m_fade_showing = fade_in(look); + m_fade_showing = fade_in(events); if (m_fade_showing != WarpFade::NONE){ m_fade = m_fade_showing; } - m_banner |= look.has(ScreenEvent::LOCATION_BANNER); - const bool box = look.has(ScreenEvent::DIALOG_BOX); + m_banner |= events.has(ScreenEvent::LOCATION_BANNER); + const bool box = events.has(ScreenEvent::DIALOG_BOX); // A fade is never calm: BDSP's overworld reads a black frame as no // box, and black stays still, so a closing fade counted as quiet and - // ended Mom's scene as it went down (lab-B 2026-11-09 14:33). + // ended the scene as it went down. const bool calm = !box && m_fade_showing == WarpFade::NONE && - look.has(ScreenEvent::PLAYER_CAN_MOVE) && warped(); - const bool quiet = calm && look.has(ScreenEvent::SCREEN_STILL); + events.has(ScreenEvent::PLAYER_CAN_MOVE) && warped(); + const bool quiet = calm && events.has(ScreenEvent::SCREEN_STILL); if (!calm){ - m_calm_since = WallClock::max(); - }else if (m_calm_since == WallClock::max()){ + m_calm_since.reset(); + }else if (!m_calm_since.has_value()){ m_calm_since = now; } if (!quiet){ - m_quiet_since = WallClock::max(); - }else if (m_quiet_since == WallClock::max()){ + m_quiet_since.reset(); + }else if (!m_quiet_since.has_value()){ m_quiet_since = now; } const bool over = - (quiet && now - m_quiet_since >= TALK_OVER_QUIET) || - (calm && now - m_calm_since >= TALK_OVER_CALM); + (quiet && now - *m_quiet_since >= TALK_OVER_QUIET) || + (calm && now - *m_calm_since >= TALK_OVER_CALM); if (over && m_rule.end_on_quiet){ return SceneMove::DONE; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h index 908dcaa39c..c3d3e44593 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h @@ -13,6 +13,7 @@ #ifndef PokemonAutomation_Pokemon_SceneJudges_H #define PokemonAutomation_Pokemon_SceneJudges_H +#include #include #include "Common/Cpp/Time.h" #include "Pokemon_ScreenEvents.h" @@ -51,18 +52,17 @@ enum class SceneMove{ // What ends a talk-over, besides the quiet. struct TalkOverRule{ // A map change must come first: a fade or the banner. Only the quiet - // after it counts: r30's scene went quiet for 5 s before the fade home. + // after it counts: a scene can go quiet for 5 s before the fade home. bool warp = false; // False when a battle is to follow (a trainer's lines pause for more - // than 4 s before it, r210d): no quiet ends the talk then. + // than 4 s before it): no quiet ends the talk then. bool end_on_quiet = true; }; // The overworld with no box and a still screen this long ends it: a scene -// pauses while someone walks off (Dawn and Barry after Rowan leaves, r23), -// a scripted walk-in ran 5 s with no text before Mom spoke (r31), and -// Roark's badge speech pauses for the fanfare (lab-B 2026-10-31 09:45 and -// 2026-11-08 15:06). The clock is the last look that was not quiet. +// pauses while someone walks off, a scripted walk-in can run 5 s with no +// text before someone speaks, and a speech pauses for a fanfare. The clock +// is the last look that was not quiet. constexpr Milliseconds TALK_OVER_QUIET = Milliseconds(5000); // The overworld with no box this long ends it, still or not: wanderers or // grass can keep the screen from ever being still. @@ -80,7 +80,7 @@ class TalkOver{ : m_rule(rule) {} - SceneMove look(const ScreenEvents& look, WallClock now); + SceneMove look(const ScreenEvents& events, WallClock now); // Whether the warp the rule asks for has shown (true without one). bool warped() const; @@ -93,8 +93,9 @@ class TalkOver{ WarpFade m_fade = WarpFade::NONE; WarpFade m_fade_showing = WarpFade::NONE; bool m_banner = false; - WallClock m_quiet_since = WallClock::max(); - WallClock m_calm_since = WallClock::max(); + // Since when the screen has been quiet, and calm; none when it is not. + std::optional m_quiet_since; + std::optional m_calm_since; }; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp index 33904b16f6..de8fdc5bc2 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp @@ -7,13 +7,13 @@ */ #include -#include #include #include #include #include "Common/Cpp/TestRunners/UnitTest.h" #include "Pokemon_SceneJudges.h" #include "Pokemon_SceneJudges_Tests.h" +#include "Pokemon_TestExpect.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -22,13 +22,6 @@ namespace{ using namespace std::chrono_literals; -UnitTestResult expect_equal(const std::string& what, const std::string& got, const std::string& expected){ - if (got == expected){ - return true; - } - return std::format("{}: expected \"{}\", got \"{}\"", what, expected, got); -} - UnitTestResult test_warp_seen(){ WarpSeen seen = note_warp({}, {ScreenEvent::DIALOG_BOX}, "Route 203"); @@ -93,9 +86,8 @@ UnitTestResult test_talk_over(){ SceneMove::DONE, 6}, {"no quiet ends a talk before a battle", {.end_on_quiet = false}, repeat(QUIET, 30), SceneMove::DONE, -1}, {"a battle", {.end_on_quiet = false}, concat(repeat(QUIET, 6), {ScreenEvents{ScreenEvent::BATTLE_STARTED}}), SceneMove::BATTLE, 6}, - // Mom's Running Shoes scene (lab-B 2026-11-09 14:33): quiet, then - // the scene's closing fade. It ended at the fade's start and the - // next step's input landed in the fade. + // Quiet, then the scene's closing fade: the scene must not end at + // the fade's start, or the next step's input lands in the fade. {"a closing fade starts the quiet over", {}, concat(concat(repeat(QUIET, 4), repeat(FADED, 3)), repeat(QUIET, 8)), SceneMove::DONE, 12}, @@ -116,7 +108,7 @@ UnitTestResult test_talk_over(){ struct SceneJudgesCase{ struct Input{ std::string name; - std::function body; + UnitTestResult (*body)(); }; struct Expectation{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h new file mode 100644 index 0000000000..6b8c6221ea --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h @@ -0,0 +1,31 @@ +/* Test Expect + * + * From: https://github.com/PokemonAutomation/ + * + * Checks the unit tests of the AutoStory judges share. + * + */ + +#ifndef PokemonAutomation_Pokemon_TestExpect_H +#define PokemonAutomation_Pokemon_TestExpect_H + +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Passes when `got` is `expected`; else fails naming `what`. +inline UnitTestResult expect_equal(const std::string& what, const std::string& got, const std::string& expected){ + if (got == expected){ + return true; + } + return std::format("{}: expected \"{}\", got \"{}\"", what, expected, got); +} + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp index 75baebe6c3..18ef603a22 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp @@ -9,6 +9,8 @@ */ #include +#include +#include #include #include #include @@ -181,9 +183,20 @@ struct CapturedCase{ std::string track_captured_case(const Filesystem::Path& folder, const FadeProfile& profile){ std::vector> frames; for (const Filesystem::Path& file : Filesystem::list_directory(folder)){ - if (file.extension().string() == ".png"){ - frames.emplace_back(std::stoi(file.stem().string()), file); + std::string extension = file.extension().string(); + std::transform(extension.begin(), extension.end(), extension.begin(), [](unsigned char c){ + return static_cast(std::tolower(c)); + }); + if (extension != ".png"){ + continue; } + const std::string stem = file.stem().string(); + int ms = 0; + const auto parsed = std::from_chars(stem.data(), stem.data() + stem.size(), ms); + if (parsed.ec != std::errc() || parsed.ptr != stem.data() + stem.size()){ + return std::format("frame {} is not named by its time in ms", file.filename().string()); + } + frames.emplace_back(ms, file); } std::sort(frames.begin(), frames.end(), [](const auto& a, const auto& b){ return a.first < b.first; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_WarpJudge.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_WarpJudge.h index ab112a4362..c2b1eb594c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_WarpJudge.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_WarpJudge.h @@ -2,7 +2,8 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_Interrupts.h, unchanged; it includes this header. + * The warp judge: whether a fade was a warp, from a game's timing. Its + * definitions are in Pokemon_Interrupts.cpp. * */ diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index cdabb865d6..b96f9e31c0 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1609,6 +1609,7 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.h Source/Pokemon/AutoStory/Pokemon_TilePose.cpp Source/Pokemon/AutoStory/Pokemon_TilePose.h + Source/Pokemon/AutoStory/Pokemon_TestExpect.h Source/Pokemon/AutoStory/Pokemon_Transitions.cpp Source/Pokemon/AutoStory/Pokemon_Transitions.h Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp From f89bc00eb33d506e7bd838ec3e88f911b29bf467 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:02:04 -0800 Subject: [PATCH 017/110] TestExpect.h: namespace-close comments Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h index 6b8c6221ea..203bed4d21 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h @@ -26,6 +26,6 @@ inline UnitTestResult expect_equal(const std::string& what, const std::string& g } -} -} +} // namespace Pokemon +} // namespace PokemonAutomation #endif From 8eb6f347ef066595d951c6b9b594d1b29978be25 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:02:58 -0800 Subject: [PATCH 018/110] StoryActions: tests for a handler that throws and the HOME menu after a failed step (red) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon_StoryInterrupts_Tests.cpp | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp index f02b59c42f..779fec7300 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp @@ -568,6 +568,78 @@ UnitTestResult test_home_menu_stops_the_segment(){ return true; } +// A handler that drives the console can lose it. That fails the step as +// interrupt_failed, like a handler that returns a failure: it must not +// escape the executor, and the step is not run. +UnitTestResult test_handler_throws(){ + FakeGame game; + game.screens = {dialog()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers = InterruptHandlerTable(); + interrupts.handlers.add(InterruptKind::DIALOG, InterruptHandler{ + .handle = [&game](const InterruptVerdict&, RunState&) -> Outcome{ + game.trace.push_back("clear dialog"); + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, "the console is gone"); + }, + .pose = InterruptPose::UNCHANGED, + }); + try{ + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (run.outcome.failure != "interrupt_failed"){ + return std::format("Expected interrupt_failed, got {}", to_string(run.outcome)); + } + }catch (OperationFailedException& e){ + return std::format("The handler's failure escaped the executor: {}", e.message()); + } + return expect_trace(game, {"look", "clear dialog", "told dialog interrupt_failed: dialog: operation_failed: the console is gone"}); +} + +// The same loss after a step failed, while the executor looks for what +// explains the failure: the step's own failure is kept. +UnitTestResult test_handler_throws_after_a_failure(){ + FakeGame game; + game.screens = {quiet(), dialog()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers = InterruptHandlerTable(); + interrupts.handlers.add(InterruptKind::DIALOG, InterruptHandler{ + .handle = [&game](const InterruptVerdict&, RunState&) -> Outcome{ + game.trace.push_back("clear dialog"); + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, "the console is gone"); + }, + .pose = InterruptPose::UNCHANGED, + }); + try{ + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk"), FakeAction{.failures = 1}); + if (run.outcome.failure != "dialog"){ + return std::format("Expected the step's own failure, got {}", to_string(run.outcome)); + } + }catch (OperationFailedException& e){ + return std::format("The handler's failure escaped the executor: {}", e.message()); + } + return true; +} + +// A step that fails and then shows the HOME menu did not fail on its own: +// the game is not running, so the segment must stop instead of recovering +// or reloading with the game closed. +UnitTestResult test_home_menu_after_a_failed_step(){ + for (bool throws : {false, true}){ + FakeGame game; + game.screens = {quiet(), home_menu()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk"), FakeAction{.failures = 1, .throws = throws}); + if (run.outcome.failure != "game_not_running"){ + return std::format("Expected game_not_running after a step that {} and then showed HOME, got {}", + throws ? "threw" : "failed", to_string(run.outcome)); + } + const size_t runs = static_cast(std::count(game.trace.begin(), game.trace.end(), "run walk")); + if (runs != 1){ + return std::format("Expected the step run once, got {} runs", runs); + } + } + return true; +} + UnitTestResult test_settle_of_a_look(){ struct Row{ std::string name; @@ -717,6 +789,18 @@ const StoryInterruptsCase STORY_INTERRUPTS_CASES[] = { .input = {.name = "the HOME menu stops the segment", .test = test_home_menu_stops_the_segment}, .expectation = {.description = "no recovery in place, no reload"}, }, + { + .input = {.name = "a handler that throws fails the step", .test = test_handler_throws}, + .expectation = {.description = "interrupt_failed, the step not run, nothing escapes"}, + }, + { + .input = {.name = "a handler that throws after a failed step", .test = test_handler_throws_after_a_failure}, + .expectation = {.description = "the step's own failure, nothing escapes"}, + }, + { + .input = {.name = "the HOME menu after a failed step", .test = test_home_menu_after_a_failed_step}, + .expectation = {.description = "game_not_running instead of the step's failure, run once"}, + }, }; } // namespace From 27f818676b8f06f931b2ccd9666ef74b1dad7730 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:04:42 -0800 Subject: [PATCH 019/110] Review fixes: a throwing interrupt handler fails the step, HOME after a failed step stops the segment; comment content, include order, named literals, optional frame colour Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_AutoStory_Tests.h | 2 +- .../AutoStory/Pokemon_InterruptHandlers.h | 3 +- .../AutoStory/Pokemon_StoryActions.cpp | 28 +++++++++++++++---- .../Pokemon/AutoStory/Pokemon_StoryActions.h | 14 ++++++++-- .../AutoStory/Pokemon_StoryActions_Tests.h | 2 +- .../AutoStory/Pokemon_StoryInterrupts.cpp | 14 +++++++++- .../AutoStory/Pokemon_StoryInterrupts.h | 7 +---- .../Pokemon_StoryInterrupts_Tests.cpp | 7 ++--- .../AutoStory/Pokemon_StoryPreflight.cpp | 8 +++++- .../Pokemon/AutoStory/Pokemon_StoryRun.h | 4 +-- .../AutoStory/Pokemon_StoryRun_Tests.cpp | 11 ++++---- .../Pokemon_MoveMechanics_Tests.cpp | 4 +-- .../PokemonFRLG/PokemonFRLG_Tests.cpp | 2 +- ...okemonFRLG_AutoStoryScreenEvents_Tests.cpp | 11 ++++---- 14 files changed, 78 insertions(+), 39 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 906540637b..0e51776983 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -19,7 +19,6 @@ #include "Engine/Pokemon_StoryEngine_Tests.h" #include "Pokemon/Options/Pokemon_StoryRangeOptions_Tests.h" #include "Pokemon_AutoStorySelect_Tests.h" -#include "Pokemon_StoryRun_Tests.h" #include "Pokemon_AutoStoryStats_Tests.h" #include "Pokemon_Interrupts_Tests.h" #include "Pokemon_SceneJudges_Tests.h" @@ -28,6 +27,7 @@ #include "Pokemon_StoryEvents_Tests.h" #include "Pokemon_StoryInterrupts_Tests.h" #include "Pokemon_StoryLog_Tests.h" +#include "Pokemon_StoryRun_Tests.h" #include "Pokemon_StorySavePolicy_Tests.h" #include "Pokemon_StorySegments_Tests.h" #include "Pokemon_StoryStepExecutor_Tests.h" diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h index c574b2503f..ffe9602115 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h @@ -2,7 +2,8 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_StoryInterrupts.h, unchanged; it includes this header. + * The table of a game's interrupt handlers and the screen look they read. + * Pokemon_StoryInterrupts.h builds on it. * */ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp index 5ecbd69f35..2e7376990e 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp @@ -107,13 +107,25 @@ Outcome TableExecutor::run(const StoryStep& step, RunState& state){ } try{ Outcome outcome = run_action(step, state); - if (outcome.succeeded() || !cleared_after_failure(step, state, cleared)){ + if (outcome.succeeded()){ + return outcome; + } + switch (look_after_failure(step, state, cleared)){ + case AfterFailure::RETRY: + continue; + case AfterFailure::GAME_NOT_RUNNING: + return outcome_game_not_running(); + case AfterFailure::KEEP: return outcome; } }catch (OperationFailedException& e){ - if (cleared_after_failure(step, state, cleared)){ + const AfterFailure after = look_after_failure(step, state, cleared); + if (after == AfterFailure::RETRY){ continue; } + if (after == AfterFailure::GAME_NOT_RUNNING){ + return outcome_game_not_running(); + } if (m_guard.stops_on_failure(step)){ throw; } @@ -153,11 +165,15 @@ std::optional TableExecutor::clear_interrupts(const StoryStep& step, Ru return std::nullopt; } -// Whether an interrupt explains the failure of `step`: one showed after -// it failed and is cleared, so the step runs again. -bool TableExecutor::cleared_after_failure(const StoryStep& step, RunState& state, size_t& cleared){ +// What explains the failure of `step`, if anything: an interrupt that +// showed after it failed and is cleared, or the game not running. +AfterFailure TableExecutor::look_after_failure(const StoryStep& step, RunState& state, size_t& cleared){ const size_t before = cleared; - return !clear_interrupts(step, state, cleared) && cleared > before; + const std::optional failed = clear_interrupts(step, state, cleared); + if (failed){ + return failed->failure == GAME_NOT_RUNNING ? AfterFailure::GAME_NOT_RUNNING : AfterFailure::KEEP; + } + return cleared > before ? AfterFailure::RETRY : AfterFailure::KEEP; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h index 3e2792a695..23711eb83c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h @@ -23,7 +23,6 @@ #include #include #include -#include #include #include #include @@ -109,6 +108,17 @@ class StepGuard{ }; +// What a look at the screen after a step failed found. +enum class AfterFailure{ + // Nothing explains the failure: it is the step's own. + KEEP, + // An interrupt explains it and is cleared: the step runs again. + RETRY, + // The game is not running (the Switch's HOME menu): the failure is + // that, and the step is not run again. + GAME_NOT_RUNNING, +}; + // Runs each step with the table's action for it, inside `guard`. class TableExecutor : public StoryStepExecutor{ public: @@ -138,7 +148,7 @@ class TableExecutor : public StoryStepExecutor{ private: std::optional clear_interrupts(const StoryStep& step, RunState& state, size_t& cleared); - bool cleared_after_failure(const StoryStep& step, RunState& state, size_t& cleared); + AfterFailure look_after_failure(const StoryStep& step, RunState& state, size_t& cleared); const StoryActionTable& m_table; StepGuard& m_guard; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h index d3593d58f6..6f6f908d18 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h @@ -13,7 +13,7 @@ namespace PokemonAutomation{ namespace Pokemon{ -// Registers unit tests for story action tables, the variant parser and the table executor. +// Registers unit tests for story action tables, checkpoint lint and the table executor. void add_tests_StoryActions(UnitTestDatabase& database); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp index 0012c5d2eb..8c50b18d37 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp @@ -10,6 +10,7 @@ #include #include #include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" #include "Pokemon_StoryInterrupts.h" namespace PokemonAutomation{ @@ -146,6 +147,17 @@ std::string describe(const ScreenSettle& settle){ } +// The handler's outcome. A handler drives the console, which it can lose: +// that is a failed outcome too, not an exception for the executor's caller. +Outcome run_handler(const InterruptHandler& handler, const InterruptVerdict& verdict, RunState& state){ + try{ + return handler.handle(verdict, state); + }catch (OperationFailedException& e){ + return outcome_failed("operation_failed", e.message()); + } +} + + InterruptCheck clear_story_interrupt(const StoryInterrupts& interrupts, const StoryStep& step, RunState& state){ InterruptCheck out; out.verdict = settled_verdict(interrupts, step.kind, out.screen); @@ -171,7 +183,7 @@ InterruptCheck clear_story_interrupt(const StoryInterrupts& interrupts, const St out.outcome = outcome_failed("unhandled_interrupt", std::format("{} before {}", interrupt_kind_name(kind), step.name)); return out; } - const Outcome handled = handler->handle(out.verdict, state); + const Outcome handled = run_handler(*handler, out.verdict, state); if (!handled.succeeded()){ out.outcome = outcome_failed("interrupt_failed", std::format("{}: {}", interrupt_kind_name(kind), to_string(handled))); return out; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h index 2bceba34c6..61945b8459 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h @@ -34,17 +34,12 @@ #ifndef PokemonAutomation_Pokemon_StoryInterrupts_H #define PokemonAutomation_Pokemon_StoryInterrupts_H -#include -#include -#include -#include #include -#include +#include "Pokemon_InterruptHandlers.h" #include "Pokemon_Interrupts.h" #include "Pokemon_ScreenEvents.h" #include "Pokemon_StoryEvents.h" #include "Pokemon_StoryStepExecutor.h" -#include "Pokemon_InterruptHandlers.h" namespace PokemonAutomation{ namespace Pokemon{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp index 779fec7300..e994e11745 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp @@ -347,8 +347,8 @@ UnitTestResult test_unsettled_before_a_battle(){ } // A battle's opening still playing when a walk step begins: the walk -// before it ended in grass or in a trainer's sight (BDSP fault sweep, 51 -// steps of 00.01-01.11). The looks wait for the battle, past max_looks, +// before it ended in grass or in a trainer's sight. The looks wait for the +// battle, past max_looks, // and its handler clears it before the step. UnitTestResult test_opening_before_a_walk(ScreenLook opening, ScreenLook battle, const std::string& kind, const std::string& handler){ FakeGame game; @@ -492,8 +492,7 @@ UnitTestResult test_screen_before_each_step(){ }); } -// The program started on the HOME menu (lab-B 2026-11-09 15:31: "before -// save: settled overworld", then X on HOME and a 22-tile walk on it). The +// The program started with the game closed and the HOME menu showing. The // screen is told as HOME and the step fails at once, before any input, // and before a step that starts on a battle's opening too. UnitTestResult test_home_menu_before_a_step(){ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp index 2b56c6b435..5266a751e7 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp @@ -26,6 +26,12 @@ namespace{ // Color bars are seven flat vertical stripes of different colors. constexpr size_t BAR_COUNT = 7; +// Each stripe is sampled in its middle, away from its edges: inset by this +// fraction of its width on each side, and from the top for this fraction of +// the frame's height. +constexpr double BAR_INSET = 0.25; +constexpr double BAR_TOP = 0.1; +constexpr double BAR_HEIGHT = 0.5; // A stripe flatter than this (stddev sum) is one solid color. constexpr double BAR_MAX_STDDEV = 30; // Two stripes this far apart (RGB distance) are different bars. @@ -37,7 +43,7 @@ bool shows_color_bars(const ImageViewRGB32& frame){ std::array bars; for (size_t c = 0; c < BAR_COUNT; c++){ const double width = 1.0 / BAR_COUNT; - const ImageFloatBox stripe(c * width + width * 0.25, 0.1, width * 0.5, 0.5); + const ImageFloatBox stripe(c * width + width * BAR_INSET, BAR_TOP, width * (1 - 2 * BAR_INSET), BAR_HEIGHT); const ImageStats stats = image_stats(extract_box_reference(frame, stripe)); if (stats.stddev.sum() > BAR_MAX_STDDEV){ return false; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h index 9215d63a1c..d888b9f73d 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h @@ -19,8 +19,8 @@ * run before anything is saved. * - The first checkpoint's own save at its start runs only for a new * game: after a load the save is already there, and from the game as - * it is the place is unconfirmed (console B, 2026-11-11: a run on the - * HOME menu "saved" first). + * it is the place is unconfirmed (the game may be on the HOME + * menu). * - A failure leaves the game where it failed. Nothing here closes the * game; the user (or the next run from the save) resumes from there. * diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp index 78a24e0399..b1c187331b 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp @@ -134,8 +134,8 @@ class Test_StoryStart : public UnitTest{ }; const StartCase START_CASES[] = { - // Console B, 2026-11-11: a BDSP run started at 00.04b with the game - // left at 00.04d walked from 00.04d's position. + // A game left at a later checkpoint must not be walked from: a + // checkpoint with a save loads that save first. { .input = {.name = "a checkpoint with a save loads it first", .start = StoryStart::FROM_SAVE, .place_error = "", .preflight = READY}, .expectation = {.succeeds = true, .loads = 1, .rereads = 1, .save_loaded = true}, @@ -152,9 +152,8 @@ const StartCase START_CASES[] = { .input = {.name = "a live start loads nothing", .start = StoryStart::LIVE, .place_error = "", .preflight = READY}, .expectation = {.succeeds = true, .loads = 0, .rereads = 0, .save_loaded = false}, }, - // Console B, 2026-11-11 13:32: the game was on HOME; the run saved, - // pressed X/R/ZL on HOME, then "loaded" nothing. The preflight stops it - // before any press. + // The game is on the HOME menu: every press would go to the console's + // menus, so the preflight stops the run before any press. { .input = {.name = "the HOME menu stops the run before the load", .start = StoryStart::FROM_SAVE, .place_error = "", .preflight = ON_HOME}, .expectation = {.succeeds = false, .loads = 0, .rereads = 0, .save_loaded = false}, @@ -222,7 +221,7 @@ const PreflightCase PREFLIGHT_CASES[] = { // Whether the first checkpoint saves at its start: only a new game's. After // a load the save is already there; from the game as it is the place is -// unconfirmed (console B, 2026-11-11: "save" ran first on HOME). +// unconfirmed (the game may be on the HOME menu). struct FirstSaveCase{ struct Input{ StoryStart start; diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp index bf50a717ec..fced1d74eb 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp @@ -24,8 +24,8 @@ struct MoveMechanicsCase{ MoveMechanics mechanics; }; struct Expectation{ - // How the walker presses an open leg on foot (the user's pick, - // 2026-11-11: BDSP taps, FRLG timed holds). + // How the walker presses an open leg on foot (BDSP taps, FRLG + // timed holds). OpenLegPress open_legs_on_foot; }; Input input; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index aab4b660f9..f2fad841a4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -8,7 +8,6 @@ #include "Common/Cpp/Filesystem/Filesystem.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "CommonFramework/StaticGlobals.h" -#include "Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.h" #include "Inference/Box/PokemonFRLG_BoxCellOccupiedDetector.h" #include "Inference/Box/PokemonFRLG_BoxCellReader.h" #include "Inference/Box/PokemonFRLG_BoxGenderReader.h" @@ -28,6 +27,7 @@ #include "Inference/PokemonFRLG_StatsReader.h" #include "Inference/PokemonFRLG_TrainerIdReader.h" #include "Inference/PokemonFRLG_WildEncounterReader.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.h" #include "Programs/BoxOrganization/PokemonFRLG_BoxSorter_Tests.h" #include "Tests/TestUtils.h" diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp index f71a8a3aae..d2a2d5d332 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp @@ -10,6 +10,7 @@ */ #include +#include #include #include #include "Common/Cpp/TestRunners/UnitTest.h" @@ -29,8 +30,8 @@ namespace{ struct ScreenEventsCase{ struct Input{ std::string name; - // The frame's colour; 0 for no frame. - uint32_t color; + // The frame's colour; none for no frame. + std::optional color; }; struct Expectation{ @@ -50,9 +51,9 @@ class Test_AutoStoryScreenEvents : public UnitTest{ virtual UnitTestResult run(Logger&, CancellableScope&) const override{ VideoSnapshot frame; - if (m_case.input.color != 0){ + if (m_case.input.color.has_value()){ ImageRGB32 image(1920, 1080); - image.fill(m_case.input.color); + image.fill(*m_case.input.color); frame = VideoSnapshot(std::move(image), WallClock()); } FrlgScreenObserver observer; @@ -72,7 +73,7 @@ class Test_AutoStoryScreenEvents : public UnitTest{ const ScreenEventsCase SCREEN_EVENTS_CASES[] = { { - .input = {"no frame shows nothing", 0}, + .input = {"no frame shows nothing", std::nullopt}, .expectation = {{}}, }, { From 047fd8a153b36c5b23bc0b8d3e69d6e100bbc828 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:05:38 -0800 Subject: [PATCH 020/110] Review fixes: first_golden_difference returns an optional, with_crlf is public and tested, Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Simulation/Pokemon_SimGolden.cpp | 42 +++++++++---------- .../Navigation/Simulation/Pokemon_SimGolden.h | 10 ++++- .../Simulation/Pokemon_SimGolden_Tests.cpp | 28 +++++++++++-- 3 files changed, 53 insertions(+), 27 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp index ea8b6fe80d..0ab221c99e 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include "Common/Cpp/Filesystem/FileIO.h" #include "Pokemon_SimGolden.h" @@ -16,22 +17,6 @@ namespace Pokemon{ namespace{ -// `text` with every "\n" made "\r\n" and no "\r" of its own. -std::string with_crlf(std::string_view text){ - std::string out; - out.reserve(text.size() + text.size() / 16); - for (char ch : text){ - if (ch == '\r'){ - continue; - } - if (ch == '\n'){ - out += '\r'; - } - out += ch; - } - return out; -} - // Line `begin` of `text` up to its "\n", without a "\r" at its end. std::string_view line_at(std::string_view text, size_t begin){ if (begin >= text.size()){ @@ -57,6 +42,21 @@ size_t next_line(std::string_view text, size_t begin){ } // namespace +std::string with_crlf(std::string_view text){ + std::string out; + out.reserve(text.size() + text.size() / 16); + for (char ch : text){ + if (ch == '\r'){ + continue; + } + if (ch == '\n'){ + out += '\r'; + } + out += ch; + } + return out; +} + bool sim_golden_update_requested(){ // code-health: allow char_pointer -- std::getenv returns a const char pointer const char* value = std::getenv(std::string(SIM_GOLDEN_UPDATE_VARIABLE).c_str()); @@ -81,7 +81,7 @@ std::string sim_golden_text(std::string_view about, const std::vector first_golden_difference(std::string_view golden, std::string_view actual){ size_t a = 0; size_t b = 0; for (size_t line = 1; a < golden.size() || b < actual.size(); line++){ @@ -99,7 +99,7 @@ std::string first_golden_difference(std::string_view golden, std::string_view ac a = next_line(golden, a); b = next_line(actual, b); } - return ""; + return std::nullopt; } UnitTestResult check_sim_golden(Logger& logger, const std::string& path, const std::string& text){ @@ -116,11 +116,11 @@ UnitTestResult check_sim_golden(Logger& logger, const std::string& path, const s if (!file_to_string(path, golden)){ return std::format("No golden at {}: run with {}=1 to write it.", path, SIM_GOLDEN_UPDATE_VARIABLE); } - const std::string difference = first_golden_difference(golden, text); - if (!difference.empty()){ + const std::optional difference = first_golden_difference(golden, text); + if (difference.has_value()){ return std::format( "{} differs from the simulation at {}\nRun with {}=1 to rewrite it if the change is meant.", - path, difference, SIM_GOLDEN_UPDATE_VARIABLE + path, *difference, SIM_GOLDEN_UPDATE_VARIABLE ); } return true; diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h index 4d3210a1fc..23486fe72e 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h @@ -18,6 +18,7 @@ #ifndef PokemonAutomation_Pokemon_SimGolden_H #define PokemonAutomation_Pokemon_SimGolden_H +#include #include #include #include @@ -41,9 +42,14 @@ std::string sim_golden_path(std::string_view source_file, std::string_view name) // ended by "\n". std::string sim_golden_text(std::string_view about, const std::vector& lines); +// `text` with every "\n" made "\r\n" and no "\r" of its own: the line +// endings the goldens are written with. +std::string with_crlf(std::string_view text); + // The first line where `golden` and `actual` differ, carriage returns -// ignored: "line N:\n--- golden: ...\n+++ actual: ...". "" if none. -std::string first_golden_difference(std::string_view golden, std::string_view actual); +// ignored: "line N:\n--- golden: ...\n+++ actual: ...". None if they are +// the same. +std::optional first_golden_difference(std::string_view golden, std::string_view actual); // Checks `text` against the golden file at `path`, or rewrites the file // with it when SIM_GOLDEN_UPDATE_VARIABLE is set. Fails with the first diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp index 06b48f2f5f..552dcd42cb 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp @@ -7,8 +7,10 @@ * */ +#include #include #include +#include #include "Common/Cpp/TestRunners/UnitTest.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Pokemon_SimGolden.h" @@ -55,6 +57,11 @@ UnitTestResult expect_equal(std::string_view what, std::string_view actual, std: return std::string(what) + ": expected \"" + std::string(expected) + "\", got \"" + std::string(actual) + "\"."; } +// The difference as text for expect_equal(): "(none)" when the texts match. +std::string difference_of(std::string_view golden, std::string_view actual){ + return first_golden_difference(golden, actual).value_or("(none)"); +} + UnitTestResult test_path_beside_source(Logger&){ UnitTestResult result = expect_equal("posix", sim_golden_path("/a/b/Test.cpp", "x.golden.txt"), "/a/b/x.golden.txt"); if (result.result != UnitTestResult::PASSED){ @@ -72,30 +79,42 @@ UnitTestResult test_text(Logger&){ } UnitTestResult test_same_text_ignoring_crlf(Logger&){ - return expect_equal("difference", first_golden_difference("# x\r\na\r\nb\r\n", "# x\na\nb\n"), ""); + return expect_equal("difference", difference_of("# x\r\na\r\nb\r\n", "# x\na\nb\n"), "(none)"); } UnitTestResult test_first_differing_line(Logger&){ return expect_equal( - "difference", first_golden_difference("# x\r\na\r\nb\r\n", "# x\na\nc\n"), + "difference", difference_of("# x\r\na\r\nb\r\n", "# x\na\nc\n"), "line 3:\n--- golden: b\n+++ actual: c" ); } UnitTestResult test_extra_line(Logger&){ UnitTestResult result = expect_equal( - "longer actual", first_golden_difference("a\n", "a\nb\n"), + "longer actual", difference_of("a\n", "a\nb\n"), "line 2:\n--- golden: (end of file)\n+++ actual: b" ); if (result.result != UnitTestResult::PASSED){ return result; } return expect_equal( - "shorter actual", first_golden_difference("a\nb\n", "a\n"), + "shorter actual", difference_of("a\nb\n", "a\n"), "line 2:\n--- golden: b\n+++ actual: (end of file)" ); } +UnitTestResult test_with_crlf(Logger&){ + UnitTestResult result = expect_equal("bare LF", with_crlf("a\nb\n"), "a\r\nb\r\n"); + if (result.result != UnitTestResult::PASSED){ + return result; + } + result = expect_equal("CRLF", with_crlf("a\r\nb\r\n"), "a\r\nb\r\n"); + if (result.result != UnitTestResult::PASSED){ + return result; + } + return expect_equal("mixed and a stray CR", with_crlf("a\r\nb\rc\n"), "a\r\nbc\r\n"); +} + UnitTestResult test_missing_golden_fails(Logger& logger){ if (sim_golden_update_requested()){ return UnitTestResult(UnitTestResult::SKIPPED, "the goldens are being rewritten"); @@ -113,6 +132,7 @@ const SimGoldenTestCase SIM_GOLDEN_CASES[] = { {.input = {.name = "CRLF and LF text compare the same", .body = test_same_text_ignoring_crlf}, .expectation = {}}, {.input = {.name = "the first differing line is reported", .body = test_first_differing_line}, .expectation = {}}, {.input = {.name = "a line more or less is reported", .body = test_extra_line}, .expectation = {}}, + {.input = {.name = "goldens are written with exactly one CRLF a line", .body = test_with_crlf}, .expectation = {}}, {.input = {.name = "a missing golden fails", .body = test_missing_golden_fails}, .expectation = {}}, }; From 801c8bf75563b59f77c71382a27c0b5ed50f7ea8 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:06:33 -0800 Subject: [PATCH 021/110] Review fixes: fault_classes() checked against the enum, plain separator, static_cast, Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Simulation/Pokemon_SimFaults_Tests.cpp | 29 +++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp index 957a88e0bd..73b884ff6f 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include "Common/Cpp/TestRunners/UnitTest.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" @@ -85,7 +86,10 @@ Counted count(const std::set& faulted, int chances){ std::string numbers_text(const std::vector& numbers){ std::string out; for (int number : numbers){ - out += out.empty() ? std::format("{}", number) : std::format(", {}", number); + if (!out.empty()){ + out += ", "; + } + out += std::format("{}", number); } return std::format("[{}]", out); } @@ -95,7 +99,7 @@ UnitTestResult expect_counted(const std::set& faulted, int chances, const s if (counted.faulted_at != faulted_at){ return std::format("Faulted chances {}, expected {}.", numbers_text(counted.faulted_at), numbers_text(faulted_at)); } - if (counted.chances != chances || counted.faulted != (int)faulted_at.size()){ + if (counted.chances != chances || counted.faulted != static_cast(faulted_at.size())){ return std::format("Counted {} chances, {} faulted; expected {}, {}.", counted.chances, counted.faulted, chances, faulted_at.size()); } if (counted.other_chances != chances || counted.other_faulted != 0){ @@ -134,12 +138,33 @@ UnitTestResult test_class_names(){ return true; } +// fault_classes() restates the enum, so it must list every value: the +// names stop at the first value past the enum's last (fault_class_name() +// is a switch, so a value with no name fails to build). +UnitTestResult test_classes_match_enum(){ + const std::vector& classes = fault_classes(); + size_t named = 0; + while (fault_class_name(static_cast(named)) != "?"){ + named++; + } + if (named != classes.size()){ + return std::format("The enum has {} classes, fault_classes() lists {}.", named, classes.size()); + } + for (size_t c = 0; c < classes.size(); c++){ + if (classes[c] != static_cast(c)){ + return std::format("fault_classes() lists {} at position {}, not in the enum's order.", static_cast(classes[c]), c); + } + } + return true; +} + const SimFaultsTestCase SIM_FAULTS_CASES[] = { {.input = {.name = "none named faults none", .body = test_none_named}, .expectation = {.description = "3 chances, none faulted"}}, {.input = {.name = "the named chances are faulted, from 1", .body = test_named_from_one}, .expectation = {.description = "1 and 3 of 4 faulted"}}, {.input = {.name = "a chance never reached is not faulted", .body = test_never_reached}, .expectation = {.description = "2 of 3 faulted, 9 never reached"}}, {.input = {.name = "no chances, nothing counted", .body = test_no_chances}, .expectation = {.description = "0 chances, none faulted"}}, {.input = {.name = "each class has its own name", .body = test_class_names}, .expectation = {.description = "no two classes share a name"}}, + {.input = {.name = "fault_classes() lists every class in order", .body = test_classes_match_enum}, .expectation = {.description = "the list is the enum's values, in order"}}, }; } // namespace From c2101fe5bd3b218992baeed42d2f2d3b48577cb9 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:14:25 -0800 Subject: [PATCH 022/110] runtime-map tests: README passes the pinned publisher revision The README's prepare_parity.py command had no --publisher-revision, and the script's default pin was older than the workflow's, so following the README on the pinned checkout failed. The default now matches the workflow pin. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- devtools/runtime-map-tests/README.md | 4 +++- devtools/runtime-map-tests/prepare_parity.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/devtools/runtime-map-tests/README.md b/devtools/runtime-map-tests/README.md index 77b34cd011..e1ae46d4b9 100644 --- a/devtools/runtime-map-tests/README.md +++ b/devtools/runtime-map-tests/README.md @@ -42,7 +42,9 @@ that `.github/workflows/runtime-map-reader.yml` pins (CI passes it as ```sh python3 devtools/runtime-map-tests/prepare_parity.py \ - --publisher /path/to/PokemonSimulation --out /tmp/runtime-map-pairs.json + --publisher /path/to/PokemonSimulation \ + --publisher-revision \ + --out /tmp/runtime-map-pairs.json /path/to/build/RuntimeMapTests /tmp/runtime-map-pairs.json ``` diff --git a/devtools/runtime-map-tests/prepare_parity.py b/devtools/runtime-map-tests/prepare_parity.py index fb1cdea9ef..80519e81ee 100644 --- a/devtools/runtime-map-tests/prepare_parity.py +++ b/devtools/runtime-map-tests/prepare_parity.py @@ -16,7 +16,7 @@ import sys -PUBLISHER_REVISION = '40717c7c809c415c751fd7a348dfc1895f7ec3d7' +PUBLISHER_REVISION = '906956e94fc912ae9adb0e44845da780f3bc7e4c' def main(): From 1836dd3713bbcf2dd202a4446a4c6b8d3597c80d Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 18:49:52 -0800 Subject: [PATCH 023/110] AutoStory: shared RNG handoff contract Moved unchanged from bdsp/autostory-starter-rng (7a46b79b4), so that BDSP and FRLG both build on it from the shared base. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_AutoStory_Tests.h | 2 + .../AutoStory/Pokemon_StoryRngHandoff.cpp | 38 ++++++ .../AutoStory/Pokemon_StoryRngHandoff.h | 64 ++++++++++ .../Pokemon_StoryRngHandoff_Tests.cpp | 113 ++++++++++++++++++ .../AutoStory/Pokemon_StoryRngHandoff_Tests.h | 23 ++++ SerialPrograms/cmake/SourceFiles.cmake | 4 + 6 files changed, 244 insertions(+) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index fad5698fcc..a04e1a1c77 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -23,6 +23,7 @@ #include "Pokemon_ScreenEvents_Tests.h" #include "Pokemon_StoryEvents_Tests.h" #include "Pokemon_StoryLog_Tests.h" +#include "Pokemon_StoryRngHandoff_Tests.h" #include "Pokemon_StorySavePolicy_Tests.h" #include "Pokemon_StorySegments_Tests.h" #include "Pokemon_StoryStepExecutor_Tests.h" @@ -37,6 +38,7 @@ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_AutoStorySelect(database); add_tests_AutoStoryStats(database); add_tests_StoryLog(database); + add_tests_StoryRngHandoff(database); add_tests_StoryRangeOptions(database); add_tests_StoryEvents(database); add_tests_StorySegments(database); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp new file mode 100644 index 0000000000..e23256397a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp @@ -0,0 +1,38 @@ +/* Story RNG Handoff + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryRngHandoff.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +RngHandoffMode rng_handoff_mode(bool stop, bool run){ + if (run){ + return RngHandoffMode::RUN; + } + return stop ? RngHandoffMode::STOP : RngHandoffMode::OFF; +} + +bool RngHandoffResult::succeeded() const{ + return failure.empty(); +} + +Outcome run_rng_handoff(Logger& logger, const std::string& program, const RngHandoffCall& call){ + const RngHandoffResult result = call(); + if (!result.succeeded()){ + throw_and_log(logger, ErrorReportMode::SEND_ERROR_REPORT, result.failure); + } + logger.log(program + " succeeded: " + result.summary, COLOR_BLUE); + return outcome_ok(); +} + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h new file mode 100644 index 0000000000..140d20e5ea --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h @@ -0,0 +1,64 @@ +/* Story RNG Handoff + * + * From: https://github.com/PokemonAutomation/ + * + * The part of an AutoStory run that hands the game to an RNG program (BDSP + * Starter RNG, FRLG Starter RNG and Gift RNG) and takes it back. A game + * supplies the program's call; the contract around it is shared: + * + * - A handoff row has a mode: OFF (the story plays it by hand), STOP (the run + * ends after the row's handoff save, for the user to run the RNG program) + * or RUN (the story calls the RNG program itself and continues). + * - The call ends in an RngHandoffResult: no failure means the game stands + * where the story goes on; a failure is the reason it does not. + * - A failed RUN stops the program. It never retries the row: the program's + * own reset loop is the retry, and a reload of the save would lose a + * shiny it caught. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRngHandoff_H +#define PokemonAutomation_Pokemon_StoryRngHandoff_H + +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Pokemon_StoryOutcome.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +enum class RngHandoffMode{ + OFF, + STOP, + RUN, +}; + +// The mode for a handoff's two options: RUN takes precedence over STOP. +RngHandoffMode rng_handoff_mode(bool stop, bool run); + + +// How an RNG program's call ended, as the story needs it. +struct RngHandoffResult{ + // Empty: the game stands where the story goes on. Otherwise why it does not. + std::string failure; + // What a success did, for the log: the resets used, the target hit. + std::string summary; + + bool succeeded() const; +}; + +// The call a handoff row runs in place of its steps. +using RngHandoffCall = std::function; + +// Runs `call` for the RNG program `program` ("Starter RNG"). A success is +// logged with its summary and returned as an ok Outcome. A failure throws +// OperationFailedException with an error report, so that no row retry +// reruns the program's reset loop. +Outcome run_rng_handoff(Logger& logger, const std::string& program, const RngHandoffCall& call); + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp new file mode 100644 index 0000000000..72a847d509 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp @@ -0,0 +1,113 @@ +/* Story RNG Handoff Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryRngHandoff.h" +#include "Pokemon_StoryRngHandoff_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +// rng_handoff_mode()'s two options. +struct ModeInput{ + bool stop; + bool run; +}; + +struct ModeCase{ + ModeInput input; + RngHandoffMode expected; +}; + +const ModeCase MODE_CASES[] = { + {.input = {.stop = false, .run = false}, .expected = RngHandoffMode::OFF}, + {.input = {.stop = true, .run = false}, .expected = RngHandoffMode::STOP}, + {.input = {.stop = false, .run = true}, .expected = RngHandoffMode::RUN}, + {.input = {.stop = true, .run = true}, .expected = RngHandoffMode::RUN}, +}; + +class Test_RngHandoffMode : public UnitTest{ +public: + Test_RngHandoffMode() + : UnitTest("Pokemon::StoryRngHandoff - RUN takes precedence over STOP") + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + for (const ModeCase& item : MODE_CASES){ + if (rng_handoff_mode(item.input.stop, item.input.run) != item.expected){ + return std::format( + "stop={}, run={}: wrong mode", item.input.stop, item.input.run + ); + } + } + return true; + } +}; + +// A success is an ok Outcome and calls the program once. +class Test_RngHandoffSuccess : public UnitTest{ +public: + Test_RngHandoffSuccess() + : UnitTest("Pokemon::StoryRngHandoff - a success is ok") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + int calls = 0; + const Outcome outcome = run_rng_handoff(logger, "Test RNG", [&]{ + calls++; + return RngHandoffResult{.summary = "2 resets"}; + }); + if (!outcome.succeeded()){ + return "Expected an ok outcome"; + } + if (calls != 1){ + return std::format("Expected 1 call, got {}", calls); + } + return true; + } +}; + +// A failure throws, once: nothing reruns the program. +class Test_RngHandoffFailure : public UnitTest{ +public: + Test_RngHandoffFailure() + : UnitTest("Pokemon::StoryRngHandoff - a failure throws without a retry") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + int calls = 0; + try{ + run_rng_handoff(logger, "Test RNG", [&]{ + calls++; + return RngHandoffResult{.failure = "out of resets"}; + }); + }catch (OperationFailedException&){ + if (calls != 1){ + return std::format("Expected 1 call, got {}", calls); + } + return true; + } + return "Expected OperationFailedException"; + } +}; + +} // namespace + + +void add_tests_StoryRngHandoff(UnitTestDatabase& database){ + database.add(); + database.add(); + database.add(); +} + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h new file mode 100644 index 0000000000..aca6f82c1b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h @@ -0,0 +1,23 @@ +/* Story RNG Handoff Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRngHandoff_Tests_H +#define PokemonAutomation_Pokemon_StoryRngHandoff_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the shared RNG handoff contract. +void add_tests_StoryRngHandoff(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 79a8c47dae..739b7096d0 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1531,6 +1531,10 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_AutoStorySelect.h Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.cpp Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h + Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp + Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h + Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.cpp Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp From 00624b4c3556b0968d83b68ea413dc40c7703e07 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 18:50:09 -0800 Subject: [PATCH 024/110] AutoStory RNG handoff: a program's end can be the user's turn FRLG's loop also ends where the user takes over (target hit but not shiny, attempts spent); that is a stop with a message, not an error. A shiny is a continuation whose rows the game builds, so the seam carries no rows. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StoryRngHandoff.cpp | 17 ++++++++- .../AutoStory/Pokemon_StoryRngHandoff.h | 17 ++++++++- .../Pokemon_StoryRngHandoff_Tests.cpp | 38 +++++++++++++++++++ 3 files changed, 70 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp index e23256397a..1d0d290e1c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp @@ -24,12 +24,27 @@ bool RngHandoffResult::succeeded() const{ return failure.empty(); } -Outcome run_rng_handoff(Logger& logger, const std::string& program, const RngHandoffCall& call){ +std::optional run_rng_handoff_or_user_turn( + Logger& logger, const std::string& program, const RngHandoffCall& call +){ const RngHandoffResult result = call(); if (!result.succeeded()){ throw_and_log(logger, ErrorReportMode::SEND_ERROR_REPORT, result.failure); } + if (!result.user_turn.empty()){ + logger.log(program + " stopped for the user: " + result.user_turn, COLOR_BLUE); + return result.user_turn; + } logger.log(program + " succeeded: " + result.summary, COLOR_BLUE); + return std::nullopt; +} + +Outcome run_rng_handoff(Logger& logger, const std::string& program, const RngHandoffCall& call){ + const std::optional user_turn = run_rng_handoff_or_user_turn(logger, program, call); + if (user_turn){ + // A story action has no stop to give the user's turn to. + throw_and_log(logger, ErrorReportMode::SEND_ERROR_REPORT, *user_turn); + } return outcome_ok(); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h index 140d20e5ea..a3f14f1d38 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h @@ -10,7 +10,11 @@ * ends after the row's handoff save, for the user to run the RNG program) * or RUN (the story calls the RNG program itself and continues). * - The call ends in an RngHandoffResult: no failure means the game stands - * where the story goes on; a failure is the reason it does not. + * where the story goes on; a failure is the reason it does not. A game + * whose program can also end where the user takes over (FRLG: the target + * hit but not shiny, the attempts spent) gives that end a user_turn, which + * is a stop and not an error. What the story runs after a continuation + * (FRLG: the rows after a shiny) is the game's, built from the call. * - A failed RUN stops the program. It never retries the row: the program's * own reset loop is the retry, and a reload of the save would lose a * shiny it caught. @@ -21,6 +25,7 @@ #define PokemonAutomation_Pokemon_StoryRngHandoff_H #include +#include #include #include "Common/Cpp/Logging/AbstractLogger.h" #include "Pokemon_StoryOutcome.h" @@ -45,6 +50,9 @@ struct RngHandoffResult{ std::string failure; // What a success did, for the log: the resets used, the target hit. std::string summary; + // Not empty (and no failure): the program ended where the user takes + // over, with this for them. The run stops without an error report. + std::string user_turn; bool succeeded() const; }; @@ -58,6 +66,13 @@ using RngHandoffCall = std::function; // reruns the program's reset loop. Outcome run_rng_handoff(Logger& logger, const std::string& program, const RngHandoffCall& call); +// As run_rng_handoff(), for a program whose call may end in the user's turn: +// returns that message, which is logged, and the run stops there. Returns +// nothing when the game stands where the story goes on. +std::optional run_rng_handoff_or_user_turn( + Logger& logger, const std::string& program, const RngHandoffCall& call +); + } // namespace Pokemon } // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp index 72a847d509..3608fb064b 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp @@ -5,6 +5,7 @@ */ #include +#include #include #include "Common/Cpp/TestRunners/UnitTest.h" #include "CommonFramework/Exceptions/OperationFailedException.h" @@ -99,6 +100,42 @@ class Test_RngHandoffFailure : public UnitTest{ } }; +// The user's turn is returned, not thrown, once. +class Test_RngHandoffUserTurn : public UnitTest{ +public: + Test_RngHandoffUserTurn() + : UnitTest("Pokemon::StoryRngHandoff - a user's turn is returned, not an error") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + int calls = 0; + const std::optional turn = run_rng_handoff_or_user_turn(logger, "Test RNG", [&]{ + calls++; + return RngHandoffResult{.user_turn = "save by hand"}; + }); + if (!turn || *turn != "save by hand"){ + return "Expected the user's turn"; + } + if (calls != 1){ + return std::format("Expected 1 call, got {}", calls); + } + const std::optional none = run_rng_handoff_or_user_turn(logger, "Test RNG", []{ + return RngHandoffResult{.summary = "shiny"}; + }); + if (none){ + return "A success has no user's turn"; + } + try{ + run_rng_handoff_or_user_turn(logger, "Test RNG", []{ + return RngHandoffResult{.failure = "out of resets", .user_turn = "ignored"}; + }); + }catch (OperationFailedException&){ + return true; + } + return "A failure must throw even with a user's turn"; + } +}; + } // namespace @@ -106,6 +143,7 @@ void add_tests_StoryRngHandoff(UnitTestDatabase& database){ database.add(); database.add(); database.add(); + database.add(); } From eed3b65e0746a34cecb501affa9c9752d16075ae Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 18:52:07 -0800 Subject: [PATCH 025/110] AutoStory RNG handoff: options struct for the mode, test table Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StoryRngHandoff.cpp | 6 +- .../AutoStory/Pokemon_StoryRngHandoff.h | 9 +- .../Pokemon_StoryRngHandoff_Tests.cpp | 204 +++++++++--------- 3 files changed, 119 insertions(+), 100 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp index 1d0d290e1c..67fc164c82 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp @@ -13,11 +13,11 @@ namespace PokemonAutomation{ namespace Pokemon{ -RngHandoffMode rng_handoff_mode(bool stop, bool run){ - if (run){ +RngHandoffMode rng_handoff_mode(const RngHandoffOptions& options){ + if (options.run){ return RngHandoffMode::RUN; } - return stop ? RngHandoffMode::STOP : RngHandoffMode::OFF; + return options.stop ? RngHandoffMode::STOP : RngHandoffMode::OFF; } bool RngHandoffResult::succeeded() const{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h index a3f14f1d38..7887658546 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h @@ -34,14 +34,21 @@ namespace PokemonAutomation{ namespace Pokemon{ +// What a handoff row does with its RNG program. enum class RngHandoffMode{ OFF, STOP, RUN, }; +// A handoff's two options. +struct RngHandoffOptions{ + bool stop = false; + bool run = false; +}; + // The mode for a handoff's two options: RUN takes precedence over STOP. -RngHandoffMode rng_handoff_mode(bool stop, bool run); +RngHandoffMode rng_handoff_mode(const RngHandoffOptions& options); // How an RNG program's call ended, as the story needs it. diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp index 3608fb064b..e6d72119a4 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include "Common/Cpp/TestRunners/UnitTest.h" #include "CommonFramework/Exceptions/OperationFailedException.h" #include "Pokemon_StoryRngHandoff.h" @@ -17,133 +18,144 @@ namespace Pokemon{ namespace{ -// rng_handoff_mode()'s two options. -struct ModeInput{ - bool stop; - bool run; +struct RngHandoffInput{ + std::string_view name; + UnitTestResult (*body)(Logger& logger); }; -struct ModeCase{ - ModeInput input; - RngHandoffMode expected; +struct RngHandoffExpectation{ + std::string_view description; }; -const ModeCase MODE_CASES[] = { - {.input = {.stop = false, .run = false}, .expected = RngHandoffMode::OFF}, - {.input = {.stop = true, .run = false}, .expected = RngHandoffMode::STOP}, - {.input = {.stop = false, .run = true}, .expected = RngHandoffMode::RUN}, - {.input = {.stop = true, .run = true}, .expected = RngHandoffMode::RUN}, +struct RngHandoffTestCase{ + RngHandoffInput input; + RngHandoffExpectation expectation; }; -class Test_RngHandoffMode : public UnitTest{ +class Test_RngHandoff : public UnitTest{ public: - Test_RngHandoffMode() - : UnitTest("Pokemon::StoryRngHandoff - RUN takes precedence over STOP") + explicit Test_RngHandoff(RngHandoffTestCase scenario) + : UnitTest("Pokemon::StoryRngHandoff - " + std::string(scenario.input.name)) + , m_scenario(scenario) {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - for (const ModeCase& item : MODE_CASES){ - if (rng_handoff_mode(item.input.stop, item.input.run) != item.expected){ - return std::format( - "stop={}, run={}: wrong mode", item.input.stop, item.input.run - ); - } - } - return true; + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + return m_scenario.input.body(logger); } + +private: + RngHandoffTestCase m_scenario; }; +// rng_handoff_mode()'s two options. +UnitTestResult test_mode(Logger&){ + struct Case{ + RngHandoffOptions options; + RngHandoffMode expected; + }; + const Case cases[] = { + {.options = {.stop = false, .run = false}, .expected = RngHandoffMode::OFF}, + {.options = {.stop = true, .run = false}, .expected = RngHandoffMode::STOP}, + {.options = {.stop = false, .run = true}, .expected = RngHandoffMode::RUN}, + {.options = {.stop = true, .run = true}, .expected = RngHandoffMode::RUN}, + }; + for (const Case& item : cases){ + if (rng_handoff_mode(item.options) != item.expected){ + return std::format("stop={}, run={}: wrong mode", item.options.stop, item.options.run); + } + } + return true; +} + // A success is an ok Outcome and calls the program once. -class Test_RngHandoffSuccess : public UnitTest{ -public: - Test_RngHandoffSuccess() - : UnitTest("Pokemon::StoryRngHandoff - a success is ok") - {} +UnitTestResult test_success(Logger& logger){ + int calls = 0; + const Outcome outcome = run_rng_handoff(logger, "Test RNG", [&]{ + calls++; + return RngHandoffResult{.summary = "2 resets"}; + }); + if (!outcome.succeeded()){ + return "Expected an ok outcome"; + } + if (calls != 1){ + return std::format("Expected 1 call, got {}", calls); + } + return true; +} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - int calls = 0; - const Outcome outcome = run_rng_handoff(logger, "Test RNG", [&]{ +// A failure throws, once: nothing reruns the program. +UnitTestResult test_failure(Logger& logger){ + int calls = 0; + try{ + run_rng_handoff(logger, "Test RNG", [&]{ calls++; - return RngHandoffResult{.summary = "2 resets"}; + return RngHandoffResult{.failure = "out of resets"}; }); - if (!outcome.succeeded()){ - return "Expected an ok outcome"; - } + }catch (OperationFailedException&){ if (calls != 1){ return std::format("Expected 1 call, got {}", calls); } return true; } -}; - -// A failure throws, once: nothing reruns the program. -class Test_RngHandoffFailure : public UnitTest{ -public: - Test_RngHandoffFailure() - : UnitTest("Pokemon::StoryRngHandoff - a failure throws without a retry") - {} + return "Expected OperationFailedException"; +} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - int calls = 0; - try{ - run_rng_handoff(logger, "Test RNG", [&]{ - calls++; - return RngHandoffResult{.failure = "out of resets"}; - }); - }catch (OperationFailedException&){ - if (calls != 1){ - return std::format("Expected 1 call, got {}", calls); - } - return true; - } - return "Expected OperationFailedException"; +// The user's turn is returned, not thrown, once; a success has none; a +// failure throws even with one. +UnitTestResult test_user_turn(Logger& logger){ + int calls = 0; + const std::optional turn = run_rng_handoff_or_user_turn(logger, "Test RNG", [&]{ + calls++; + return RngHandoffResult{.user_turn = "save by hand"}; + }); + if (!turn || *turn != "save by hand"){ + return "Expected the user's turn"; } -}; - -// The user's turn is returned, not thrown, once. -class Test_RngHandoffUserTurn : public UnitTest{ -public: - Test_RngHandoffUserTurn() - : UnitTest("Pokemon::StoryRngHandoff - a user's turn is returned, not an error") - {} - - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - int calls = 0; - const std::optional turn = run_rng_handoff_or_user_turn(logger, "Test RNG", [&]{ - calls++; - return RngHandoffResult{.user_turn = "save by hand"}; - }); - if (!turn || *turn != "save by hand"){ - return "Expected the user's turn"; - } - if (calls != 1){ - return std::format("Expected 1 call, got {}", calls); - } - const std::optional none = run_rng_handoff_or_user_turn(logger, "Test RNG", []{ - return RngHandoffResult{.summary = "shiny"}; + if (calls != 1){ + return std::format("Expected 1 call, got {}", calls); + } + const std::optional none = run_rng_handoff_or_user_turn(logger, "Test RNG", []{ + return RngHandoffResult{.summary = "shiny"}; + }); + if (none){ + return "A success has no user's turn"; + } + try{ + run_rng_handoff_or_user_turn(logger, "Test RNG", []{ + return RngHandoffResult{.failure = "out of resets", .user_turn = "ignored"}; }); - if (none){ - return "A success has no user's turn"; - } - try{ - run_rng_handoff_or_user_turn(logger, "Test RNG", []{ - return RngHandoffResult{.failure = "out of resets", .user_turn = "ignored"}; - }); - }catch (OperationFailedException&){ - return true; - } - return "A failure must throw even with a user's turn"; + }catch (OperationFailedException&){ + return true; } + return "A failure must throw even with a user's turn"; +} + +const RngHandoffTestCase RNG_HANDOFF_CASES[] = { + { + .input = {.name = "RUN takes precedence over STOP", .body = test_mode}, + .expectation = {.description = "RUN wins when both options are on"}, + }, + { + .input = {.name = "a success is ok", .body = test_success}, + .expectation = {.description = "an ok outcome after one call"}, + }, + { + .input = {.name = "a failure throws without a retry", .body = test_failure}, + .expectation = {.description = "OperationFailedException after one call"}, + }, + { + .input = {.name = "a user's turn is returned, not an error", .body = test_user_turn}, + .expectation = {.description = "the message comes back; a failure still throws"}, + }, }; } // namespace void add_tests_StoryRngHandoff(UnitTestDatabase& database){ - database.add(); - database.add(); - database.add(); - database.add(); + for (const RngHandoffTestCase& scenario : RNG_HANDOFF_CASES){ + database.add(scenario); + } } From 47e077953654f4b5bc510f5fc12a1df5f47d0557 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 22:51:55 -0800 Subject: [PATCH 026/110] AutoStory: breakpoints, pause before each step and each leg (hook, option, engine) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Engine/Pokemon_StoryActionRegistry.cpp | 3 +- .../Engine/Pokemon_StoryActionRegistry.h | 7 + .../Engine/Pokemon_StoryBuiltinActions.cpp | 10 +- .../AutoStory/Engine/Pokemon_StoryEngine.cpp | 27 +++- .../Engine/Pokemon_StoryEngineRuns_Tests.cpp | 142 ++++++++++++++++++ .../AutoStory/Engine/Pokemon_StoryGame.h | 12 ++ .../Types/Pokemon_StoryBreakpoints.cpp | 103 +++++++++++++ .../Types/Pokemon_StoryBreakpoints.h | 97 ++++++++++++ .../Options/Pokemon_StoryRunOptions.cpp | 22 +++ .../Pokemon/Options/Pokemon_StoryRunOptions.h | 6 + SerialPrograms/cmake/SourceFiles.cmake | 2 + 11 files changed, 426 insertions(+), 5 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryBreakpoints.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryBreakpoints.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.cpp index 9313165a6e..3f09cfaeb6 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.cpp @@ -82,6 +82,7 @@ StoryActionRegistry::StoryActionRegistry(const StoryGame& ga : m_game(game) , m_actions(builtin_story_handlers()) , m_game_problems(tile_arg_problems(game)) + , m_pause(game.breakpoints, game.pause_point) { // A game's action replaces the built-in of its kind and name in place, // so a kind's default stays the built-in one's position. @@ -172,7 +173,7 @@ Outcome StoryActionRegistry::dispatch(StoryBackend& backend, )); } const StoryActionArgs args = with_fallbacks(action->spec, step.args); - return action->handler(backend, StoryActionCall{.step = step, .args = args}, state); + return action->handler(backend, StoryActionCall{.step = step, .args = args, .pause = m_pause}, state); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.h index f8adbc6c6f..7c2e923acf 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.h @@ -58,6 +58,12 @@ class StoryActionRegistry{ // actions fails too. std::vector lint(const StoryCheckpoint& checkpoint) const; + // The pause points of this game's run (StoryGame::breakpoints and + // pause_point). Mutable state of the run, not of the game's actions. + StoryPausePoints& pause_points() const{ + return m_pause; + } + // Runs `step`'s action with its args' fallbacks filled in; a step with // no registered action fails as unsupported_step(), a console_only // action on another backend as CONSOLE_ONLY, before any input. @@ -73,6 +79,7 @@ class StoryActionRegistry{ std::vector m_specs; // What is wrong with the game's own actions, reported with every lint. std::vector m_game_problems; + mutable StoryPausePoints m_pause; }; // Instantiated once, in Pokemon_StoryActionRegistry.cpp. diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBuiltinActions.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBuiltinActions.cpp index 24e610dca6..7846f0aa04 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBuiltinActions.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBuiltinActions.cpp @@ -97,7 +97,15 @@ inline std::optional after_legs(const Pose& start, const std::vector Outcome walk_legs(StoryBackend& backend, const StoryActionCall& call, RunState& state){ const std::vector& legs = story_arg>(call.args, "legs"); - for (const StoryLeg& leg : legs){ + const std::vector start = tiles_of(state.pose); + std::optional tile = start.size() == 1 ? std::optional(start[0]) : std::nullopt; + for (size_t index = 0; index < legs.size(); index++){ + const StoryLeg& leg = legs[index]; + for (int c = 0; tile && c < leg.tiles; c++){ + tile = tile->next(leg.direction); + } + call.pause.before_leg(story_leg_pause_label(index, legs.size(), leg.direction, leg.tiles, tile)); + backend.scope().throw_if_cancelled(); for (int c = 0; c < leg.tiles; c++){ backend.tap(leg.direction); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.cpp index e215a54d82..2b090b4a71 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.cpp @@ -25,17 +25,20 @@ namespace{ template class RunnerExecutor : public StoryStepExecutor{ public: - RunnerExecutor(StoryStepRunner& runner, const StoryGame& game) + RunnerExecutor(StoryStepRunner& runner, const StoryGame& game, StoryPausePoints& pause) : m_runner(runner) , m_game(game) + , m_pause(pause) {} virtual void begin_attempt(const StoryCheckpoint& data) override{ + m_checkpoint = &data; if (m_game.begin_attempt){ m_game.begin_attempt(data); } } virtual Outcome run(const StoryStep& step, RunState& state) override{ + m_pause.before_step(pause_label(step)); return m_runner.act(step, state); } virtual bool holds(std::string_view condition, RunState& state) override{ @@ -43,8 +46,22 @@ class RunnerExecutor : public StoryStepExecutor{ } private: + // The step's place in its checkpoint (step names are unique, which the + // lint checks). + std::string pause_label(const StoryStep& step) const{ + size_t index = 0; + if (m_checkpoint != nullptr){ + while (index < m_checkpoint->steps.size() && m_checkpoint->steps[index].name != step.name){ + index++; + } + } + return story_step_pause_label(m_checkpoint == nullptr ? "" : m_checkpoint->id, index, step.name); + } + StoryStepRunner& m_runner; const StoryGame& m_game; + StoryPausePoints& m_pause; + const StoryCheckpoint* m_checkpoint = nullptr; }; // `game` with its SAVE step "save" saving `current` only while `mode` is @@ -166,7 +183,11 @@ StoryEngine::StoryEngine(const StoryGame& game, StoryBackend , m_backend(backend) , m_registry(m_game) , m_runner(m_registry, backend) -{} +{ + m_registry.pause_points().set_log([&backend](std::string_view line){ + backend.log(line); + }); +} template std::string StoryEngine::steps_hash(const StoryCheckpoint& checkpoint) const{ @@ -337,7 +358,7 @@ VerifyReport StoryEngine::verify_checkpoint(const StoryCheckpoint& che template CheckpointReport StoryEngine::run_steps(const StoryCheckpoint& checkpoint, RunState& state){ - RunnerExecutor executor(m_runner, m_game); + RunnerExecutor executor(m_runner, m_game, m_registry.pause_points()); Checkpoint events = build_story_checkpoint(checkpoint, executor, &m_prepared); if (m_game.interrupts){ events.interrupts = m_game.interrupts(m_backend); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp index d272a19648..4b69890477 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp @@ -675,6 +675,143 @@ std::string verify_saves_after_all_passed(CancellableScope& scope){ } +// A game whose "mark" action records "run " and whose pause hook +// records "pause