From 19b6f2e9f1b8aa83947457622483019f5bdf39ad Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 10 Nov 2026 23:27:06 -0800 Subject: [PATCH 01/20] Revert "AutoStory core: move nav/story-steps' 2D actions out of autostory/engine" This reverts commit b305df5b96c87d94c6105180d73ba8274ace8201. --- .../AutoStory/Pokemon_AutoStory_Tests.h | 4 + .../AutoStory/Pokemon_InterruptHandlers.h | 95 +++ .../AutoStory/Pokemon_StoryActions.cpp | 166 ++++ .../Pokemon/AutoStory/Pokemon_StoryActions.h | 152 ++++ .../AutoStory/Pokemon_StoryActions_Tests.cpp | 323 ++++++++ .../AutoStory/Pokemon_StoryActions_Tests.h | 23 + .../AutoStory/Pokemon_StoryInterrupts.cpp | 186 +++++ .../AutoStory/Pokemon_StoryInterrupts.h | 96 +++ .../Pokemon_StoryInterrupts_Tests.cpp | 734 ++++++++++++++++++ .../AutoStory/Pokemon_StoryInterrupts_Tests.h | 23 + .../PokemonFRLG/PokemonFRLG_Tests.cpp | 2 + .../PokemonFRLG_AutoStoryScreenEvents.cpp | 52 ++ .../PokemonFRLG_AutoStoryScreenEvents.h | 49 ++ ...okemonFRLG_AutoStoryScreenEvents_Tests.cpp | 98 +++ .../PokemonFRLG_AutoStoryScreenEvents_Tests.h | 25 + SerialPrograms/cmake/SourceFiles.cmake | 13 + 16 files changed, 2041 insertions(+) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index fdc17bd01a..3967ee9e91 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -23,7 +23,9 @@ #include "Pokemon_Interrupts_Tests.h" #include "Pokemon_SceneJudges_Tests.h" #include "Pokemon_ScreenEvents_Tests.h" +#include "Pokemon_StoryActions_Tests.h" #include "Pokemon_StoryEvents_Tests.h" +#include "Pokemon_StoryInterrupts_Tests.h" #include "Pokemon_StoryLog_Tests.h" #include "Pokemon_StorySavePolicy_Tests.h" #include "Pokemon_StorySegments_Tests.h" @@ -55,6 +57,8 @@ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_SceneJudges(database); add_tests_Interrupts(database); add_tests_Transitions(database); + add_tests_StoryActions(database); + add_tests_StoryInterrupts(database); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h new file mode 100644 index 0000000000..c574b2503f --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h @@ -0,0 +1,95 @@ +/* Interrupt Handlers + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_StoryInterrupts.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_InterruptHandlers_H +#define PokemonAutomation_Pokemon_InterruptHandlers_H + +#include +#include +#include +#include +#include +#include +#include "Pokemon_Interrupts.h" +#include "Pokemon_ScreenEvents.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_StoryStepExecutor.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What a game saw of the screen between two steps: its timed events, and +// the span of them the classifier judges. +struct ScreenLook{ + ScreenEventLog log{}; + InterruptWindow window = {}; +}; + +// Looks at the screen. `fresh` starts a new look; otherwise the look goes +// on from the last one, to see how an unsettled screen ends. +using ScreenLookFunction = std::function; + +// Clears an interrupt a look found: flees or fights the battle, closes +// the dialog, waits out the warp. +using InterruptAction = std::function; + +// A row of an InterruptHandlerTable. +struct InterruptHandler{ + InterruptAction handle = {}; + // What clearing it did to where the player is. + InterruptPose pose = InterruptPose::UNCHANGED; +}; + + +// A game's handlers by kind of interrupt, and the steps that start on one. +class InterruptHandlerTable{ +public: + // The handler for `kind`: one of WILD_ENCOUNTER, TRAINER_SIGHT, + // DIALOG or WARP. Another kind, or a second handler for one, throws + // InternalProgramError. + void add(InterruptKind kind, InterruptHandler handler); + // The handler for `kind`; nullptr if there is none. + const InterruptHandler* find(InterruptKind kind) const; + + // Steps of `step` start on `kind` showing: before one, it is the + // step's to clear, not an interrupt. A step that starts on + // WILD_ENCOUNTER or TRAINER_SIGHT starts on UNSETTLED too. + void starts_on(StoryStepKind step, InterruptKind kind); + bool step_starts_on(StoryStepKind step, InterruptKind kind) const; + +private: + std::map m_handlers; + std::set> m_starts_on; +}; + + +// A game's interrupts between steps: how it looks, how it judges what it +// saw, and what it does about each kind. +struct StoryInterrupts{ + ScreenLookFunction look = {}; + InterruptKnobs knobs = {}; + InterruptHandlerTable handlers = {}; + // Looks at a screen that stays UNSETTLED (a fade with no battle yet) + // before it fails the step as "interrupt_unsettled". A step that + // starts on it gets it on the first look. + size_t max_looks = 3; + // The same, for a screen that may be a battle's opening: enough looks + // for its battle to show. BDSP's 300 ms looks cover 12 s, past its + // battle_after_fade (8 s), after which a fade with no battle settles. + size_t max_opening_looks = 40; + // Interrupts cleared for one step before it fails as + // "too_many_interrupts". + size_t max_per_step = 3; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp new file mode 100644 index 0000000000..5ecbd69f35 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp @@ -0,0 +1,166 @@ +/* Story Actions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_StoryActions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +const StoryAction* find_in(const std::map>& actions, std::string_view name){ + const auto iter = actions.find(name); + return iter == actions.end() ? nullptr : &iter->second; +} + +} // namespace + + +void StoryActionTable::add(StoryStepKind kind, std::string name, StoryAction action){ + const std::string key = std::format("{} '{}'", story_step_kind_name(kind), name); + if (!m_by_kind[kind].emplace(std::move(name), std::move(action)).second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("A second story action for {}", key)); + } +} + +void StoryActionTable::add_any_kind(std::string name, StoryAction action){ + if (name.empty()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "A story action for any kind needs a name."); + } + const std::string key = name; + if (!m_any_kind.emplace(std::move(name), std::move(action)).second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("A second story action for any kind named {}", key)); + } +} + +const StoryAction* StoryActionTable::find(StoryStepKind kind, std::string_view name) const{ + const auto kind_iter = m_by_kind.find(kind); + if (kind_iter != m_by_kind.end()){ + if (const StoryAction* exact = find_in(kind_iter->second, name)){ + return exact; + } + } + if (const StoryAction* any_kind = find_in(m_any_kind, name)){ + return any_kind; + } + if (kind_iter != m_by_kind.end()){ + return find_in(kind_iter->second, ""); + } + return nullptr; +} + +const StoryAction* StoryActionTable::find(const StoryStep& step) const{ + return find(step.kind, step.action); +} + + +std::vector lint_story_checkpoint(const StoryCheckpoint& data, const StoryActionTable& table){ + std::vector problems; + for (size_t c = 0; c < data.steps.size(); c++){ + const StoryStep& step = data.steps[c]; + const StoryAction* action = table.find(step); + const std::vector errors = action == nullptr + ? std::vector{"no action"} + : story_args_errors(StoryActionSpec{.kind = step.kind, .name = step.action, .args = action->args}, step.args); + for (const std::string& error : errors){ + problems.emplace_back(std::format( + "{} step {} {}: {} for {} '{}'", + data.id, c + 1, step.name, error, story_step_kind_name(step.kind), step.action + )); + } + } + return problems; +} + + +void StepGuard::before_step(const StoryStep&){} + +bool StepGuard::stops_on_failure(const StoryStep&) const{ + return false; +} + +void StepGuard::on_failure(const StoryStep&, const OperationFailedException&){} + +void StepGuard::on_interrupt(const StoryStep&, const InterruptCheck&){} + +void StepGuard::on_screen(const StoryStep&, const ScreenSettle&){} + + +TableExecutor::TableExecutor(const StoryActionTable& table, StepGuard& guard) + : m_table(table) + , m_guard(guard) +{} + +Outcome TableExecutor::run(const StoryStep& step, RunState& state){ + m_guard.before_step(step); + size_t cleared = 0; + while (true){ + if (std::optional failed = clear_interrupts(step, state, cleared)){ + return *failed; + } + try{ + Outcome outcome = run_action(step, state); + if (outcome.succeeded() || !cleared_after_failure(step, state, cleared)){ + return outcome; + } + }catch (OperationFailedException& e){ + if (cleared_after_failure(step, state, cleared)){ + continue; + } + if (m_guard.stops_on_failure(step)){ + throw; + } + m_guard.on_failure(step, e); + return outcome_failed("operation_failed", e.message()); + } + } +} + +Outcome TableExecutor::run_action(const StoryStep& step, RunState& state){ + if (const StoryAction* action = m_table.find(step)){ + return action->act(step, state); + } + return unsupported_step(step); +} + +// Clears what interrupted the player before `step`, counting it in +// `cleared`. Nothing when there was nothing or it is cleared; else the +// step's failure. +std::optional TableExecutor::clear_interrupts(const StoryStep& step, RunState& state, size_t& cleared){ + if (m_interrupts == nullptr){ + return std::nullopt; + } + InterruptCheck check = clear_story_interrupt(*m_interrupts, step, state); + m_guard.on_screen(step, check.screen); + if (check.verdict.kind == InterruptKind::NONE){ + // Nothing interrupted; failed only when the game is not running. + return check.outcome.succeeded() ? std::nullopt : std::optional(check.outcome); + } + if (check.outcome.succeeded() && ++cleared > m_interrupts->max_per_step){ + check.outcome = outcome_failed("too_many_interrupts", step.name); + } + m_guard.on_interrupt(step, check); + if (!check.outcome.succeeded()){ + return check.outcome; + } + 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){ + const size_t before = cleared; + return !clear_interrupts(step, state, cleared) && cleared > before; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h new file mode 100644 index 0000000000..3e2792a695 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h @@ -0,0 +1,152 @@ +/* Story Actions + * + * From: https://github.com/PokemonAutomation/ + * + * A game's story steps as a table of actions instead of one virtual per + * kind. An action is keyed by the step's kind and its action's name + * (StoryStep::action), so one table holds a game's + * usual way of doing a kind, its other ways, and the steps only it has. + * The console and a simulation bind the same rows to different actions. + * + * TableExecutor runs a step through the table, inside the game's + * StepGuard: the log line, and a failed console step turned into a failed + * Outcome. Today each game writes that guard itself (BDSP's + * StoryExecutor::run(), FRLG's guarded(), PLZA's Executor::run()). + * With the game's interrupts set, it also clears what stopped the player + * between steps (Pokemon_StoryInterrupts.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryActions_H +#define PokemonAutomation_Pokemon_StoryActions_H + +#include +#include +#include +#include +#include +#include +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_StoryInterrupts.h" +#include "Pokemon_StoryStepExecutor.h" +#include "Types/Pokemon_StoryActionSpec.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Does `step`, from the run so far. +using StoryActionFunction = std::function; + +// A row of a StoryActionTable: what does a step, and what it needs. +struct StoryAction{ + StoryActionFunction act = {}; + // Moves or reads the console. A binding without one (a simulation) + // can't run it. + bool needs_console = false; + // The screen event the action ends on ("fade", "dialog"). Declared for + // the event-driven waits to come; nothing reads it yet. + std::string waits_for = {}; + // The args its steps may carry (StoryStep::args); a step with any + // other, or without a required one, fails lint_story_checkpoint(). + std::vector args = {}; +}; + + +// A game's actions by step kind and action name. +class StoryActionTable{ +public: + // The action for steps of `kind` whose action is named `name`. An + // empty `name` is the kind's default. A second action for the same + // key throws InternalProgramError. + void add(StoryStepKind kind, std::string name, StoryAction action); + // The action for steps of any kind whose action is named `name`, + // which must not be empty. + void add_any_kind(std::string name, StoryAction action); + + // The action for a step of `kind` with an action named `name`: the + // one added for both, else the one for `name` of any kind, else the + // kind's default. nullptr if there is none. + const StoryAction* find(StoryStepKind kind, std::string_view name) const; + // find() for the step's kind and its action's name. + const StoryAction* find(const StoryStep& step) const; + +private: + using ByName = std::map>; + std::map m_by_kind; + ByName m_any_kind; +}; + +// The steps of `data` that `table` has no action for, as +// " step : no action for GAME 'bill'", or whose args +// don't fit their action's, as "... missing argument \"budget\" for GAME 'mart'". +std::vector lint_story_checkpoint(const StoryCheckpoint& data, const StoryActionTable& table); + + +// What a game does around every step a TableExecutor runs. Does nothing +// by default, and a failed step fails the step. +class StepGuard{ +public: + virtual ~StepGuard() = default; + + // Before the step runs: e.g. the step's log line. + virtual void before_step(const StoryStep& step); + // Whether a failed step stops the program, leaving the console on the + // failure, instead of failing the step for the segment to reload: the + // rows a developer is fixing. + virtual bool stops_on_failure(const StoryStep& step) const; + // The step threw `error` and fails: e.g. log it and save a screenshot. + virtual void on_failure(const StoryStep& step, const OperationFailedException& error); + // A look before the step, or after it failed, found an interrupt and + // cleared it or failed to (`check`): e.g. log it. + virtual void on_interrupt(const StoryStep& step, const InterruptCheck& check); + // How the screen looked when the look before the step (or after it + // failed) ended, interrupt or not: e.g. log it, so a run log shows + // whether the scene before had ended before the step's first input. + virtual void on_screen(const StoryStep& step, const ScreenSettle& screen); +}; + + +// Runs each step with the table's action for it, inside `guard`. +class TableExecutor : public StoryStepExecutor{ +public: + // `table` and `guard` must outlive the executor. + TableExecutor(const StoryActionTable& table, StepGuard& guard); + + // The table's action for the step (run_action()); with none, the + // step is unsupported (unsupported_step()). An OperationFailedException + // from the action is the failed Outcome "operation_failed", unless the + // guard stops on it. + // With interrupts set, each step first clears what stopped the player + // since the step before, and a failed step that an interrupt explains + // runs again once it is cleared. + virtual Outcome run(const StoryStep& step, RunState& state) override; + + // The game's interrupts between steps, which must outlive the + // executor; none (the default) looks for none. + void set_interrupts(const StoryInterrupts* interrupts){ + m_interrupts = interrupts; + } + +protected: + // The table's action for the step, or unsupported_step() with none: + // what run() runs once the screen is clear. A binding may wrap it, or + // do the kinds its table does not have yet. + virtual Outcome run_action(const StoryStep& step, RunState& state); + +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); + + const StoryActionTable& m_table; + StepGuard& m_guard; + const StoryInterrupts* m_interrupts = nullptr; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp new file mode 100644 index 0000000000..4e3b98983a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp @@ -0,0 +1,323 @@ +/* Story Actions Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryActions.h" +#include "Pokemon_StoryActions_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +StoryStep make(StoryStepKind kind, std::string name, std::string action = ""){ + StoryStep step; + step.kind = kind; + step.name = std::move(name); + step.action = std::move(action); + return step; +} + +// An action that fails with `name`, so a test sees which one ran. +StoryAction named(std::string name){ + return StoryAction{ + .act = [name](const StoryStep&, RunState&){ + return outcome_failed(name); + }, + }; +} + +// The name of the action the table finds for `kind` and `action`; "none" +// without one. +std::string found(const StoryActionTable& table, StoryStepKind kind, std::string name){ + const StoryAction* action = table.find(make(kind, "step", std::move(name))); + if (action == nullptr){ + return "none"; + } + RunState state; + return action->act(make(kind, "step"), state).failure; +} + + +UnitTestResult test_lookup_order(){ + StoryActionTable table; + table.add(StoryStepKind::TALK, "", named("talk default")); + table.add(StoryStepKind::TALK, "bill", named("talk bill")); + table.add_any_kind("bill", named("any bill")); + table.add_any_kind("nurse", named("any nurse")); + const std::pair checks[] = { + {found(table, StoryStepKind::TALK, "bill"), "talk bill"}, + {found(table, StoryStepKind::MASH, "bill"), "any bill"}, + {found(table, StoryStepKind::TALK, "nurse"), "any nurse"}, + {found(table, StoryStepKind::TALK, "oak"), "talk default"}, + {found(table, StoryStepKind::TALK, ""), "talk default"}, + {found(table, StoryStepKind::MASH, "oak"), "none"}, + {found(table, StoryStepKind::MASH, ""), "none"}, + }; + for (const auto& [actual, expected] : checks){ + if (actual != expected){ + return std::format("Expected {}, got {}", expected, actual); + } + } + return true; +} + +UnitTestResult test_duplicate_actions_throw(){ + StoryActionTable table; + table.add(StoryStepKind::TALK, "bill", named("first")); + table.add_any_kind("bill", named("any")); + const auto throws = [](auto add){ + try{ + add(); + }catch (InternalProgramError&){ + return true; + } + return false; + }; + if (!throws([&]{ table.add(StoryStepKind::TALK, "bill", named("second")); })){ + return "Expected a second TALK 'bill' to throw."; + } + if (!throws([&]{ table.add_any_kind("bill", named("second")); })){ + return "Expected a second any-kind 'bill' to throw."; + } + if (!throws([&]{ table.add_any_kind("", named("nameless")); })){ + return "Expected an any-kind action without a name to throw."; + } + return found(table, StoryStepKind::TALK, "bill") == "first" ? UnitTestResult(true) : UnitTestResult("Expected the first action kept."); +} + +// The args a test Mart takes. +const std::vector MART_ARGS = { + {.key = "map", .type = StoryArgType::WORD, .required = true, .fallback = std::nullopt, .why = ""}, + {.key = "budget", .type = StoryArgType::INTEGER, .required = true, .fallback = std::nullopt, .why = ""}, +}; + +// `step` with `args`. +StoryStep with_args(StoryStep step, StoryActionArgs args){ + step.args = std::move(args); + return step; +} + +UnitTestResult test_lint_names_steps_without_actions(){ + StoryActionTable table; + table.add(StoryStepKind::ROUTE, "", named("route")); + table.add_any_kind("bill", named("bill")); + StoryAction mart = named("mart"); + mart.args = MART_ARGS; + table.add(StoryStepKind::GAME, "mart", std::move(mart)); + const StoryCheckpoint data{ + .id = "00.05", + .title = "", + .start = std::nullopt, + .steps = { + make(StoryStepKind::ROUTE, "to the cape", "route"), + make(StoryStepKind::GAME, "meet Bill", "bill"), + make(StoryStepKind::GAME, "teleporter", "cell_separator"), + make(StoryStepKind::TALK, "talk"), + with_args(make(StoryStepKind::GAME, "buy", "mart"), {{"map", std::string("M")}, {"budget", int64_t(1500)}}), + with_args(make(StoryStepKind::GAME, "buy more", "mart"), {{"map", std::string("M")}}), + with_args(make(StoryStepKind::GAME, "meet Bill again", "bill"), {{"slot", int64_t(1)}}), + }, + }; + const std::vector problems = lint_story_checkpoint(data, table); + const std::vector expected = { + "00.05 step 3 teleporter: no action for GAME 'cell_separator'", + "00.05 step 4 talk: no action for TALK ''", + "00.05 step 6 buy more: missing argument \"budget\" for GAME 'mart'", + "00.05 step 7 meet Bill again: unknown argument \"slot\" for GAME 'bill'", + }; + if (problems != expected){ + std::string got; + for (const std::string& problem : problems){ + got += std::format("\n{}", problem); + } + return std::format("Expected two steps without actions and two with bad args, got:{}", got); + } + return true; +} + + +// A binding that does TALK itself when its table has no action for it. +class FakeTableExecutor : public TableExecutor{ +public: + using TableExecutor::TableExecutor; + +protected: + virtual Outcome run_action(const StoryStep& step, RunState& state) override{ + const Outcome outcome = TableExecutor::run_action(step, state); + if (step.kind == StoryStepKind::TALK && outcome.failure == "unsupported_step"){ + return outcome_failed("talk binding"); + } + return outcome; + } +}; + +// Writes down what the executor asked of it. +class FakeGuard : public StepGuard{ +public: + std::vector trace; + bool stops = false; + + virtual void before_step(const StoryStep& step) override{ + trace.push_back(std::format("before {}", step.name)); + } + virtual bool stops_on_failure(const StoryStep&) const override{ + return stops; + } + virtual void on_failure(const StoryStep& step, const OperationFailedException& error) override{ + trace.push_back(std::format("failed {}: {}", step.name, error.message())); + } +}; + +StoryAction throwing(){ + return StoryAction{ + .act = [](const StoryStep&, RunState&) -> Outcome{ + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, "no dialog"); + }, + .needs_console = true, + }; +} + +UnitTestResult test_executor_uses_table_then_binding(){ + StoryActionTable table; + table.add(StoryStepKind::GAME, "bill", named("bill action")); + FakeGuard guard; + FakeTableExecutor executor(table, guard); + RunState state; + const std::string bill = executor.run(make(StoryStepKind::GAME, "bill", "bill"), state).failure; + const std::string talk = executor.run(make(StoryStepKind::TALK, "talk"), state).failure; + const std::string mash = executor.run(make(StoryStepKind::MASH, "mash"), state).failure; + if (bill != "bill action" || talk != "talk binding" || mash != "unsupported_step"){ + return std::format("Expected table, binding, unsupported; got {}, {}, {}", bill, talk, mash); + } + if (guard.trace != std::vector{"before bill", "before talk", "before mash"}){ + return "Expected the guard before every step."; + } + return true; +} + +UnitTestResult test_guard_turns_failures_into_outcomes(){ + StoryActionTable table; + table.add(StoryStepKind::TALK, "", throwing()); + FakeGuard guard; + TableExecutor executor(table, guard); + RunState state; + const Outcome outcome = executor.run(make(StoryStepKind::TALK, "oak"), state); + if (outcome.failure != "operation_failed" || outcome.detail != "no dialog"){ + return std::format("Expected operation_failed: no dialog, got {}", to_string(outcome)); + } + if (guard.trace != std::vector{"before oak", "failed oak: no dialog"}){ + return "Expected the guard told of the failure."; + } + return true; +} + +UnitTestResult test_guard_stop_rethrows(){ + StoryActionTable table; + table.add(StoryStepKind::TALK, "", throwing()); + table.add(StoryStepKind::MASH, "", StoryAction{ + .act = [](const StoryStep&, RunState&) -> Outcome{ + throw std::runtime_error("not a console failure"); + }, + }); + FakeGuard guard; + guard.stops = true; + TableExecutor executor(table, guard); + RunState state; + try{ + executor.run(make(StoryStepKind::TALK, "oak"), state); + return "Expected a stop row's failure rethrown."; + }catch (OperationFailedException&){} + guard.stops = false; + try{ + executor.run(make(StoryStepKind::MASH, "scene"), state); + return "Expected other exceptions passed through."; + }catch (std::runtime_error&){} + if (guard.trace != std::vector{"before oak", "before scene"}){ + return "Expected no failure reported for a stop or another exception."; + } + return true; +} + + +struct StoryActionsInput{ + std::string_view name; + UnitTestResult (*test)(); +}; + +struct StoryActionsExpectation{ + std::string_view description; +}; + +struct StoryActionsCase{ + StoryActionsInput input; + StoryActionsExpectation expectation; +}; + +class Test_StoryActions : public UnitTest{ +public: + explicit Test_StoryActions(StoryActionsCase scenario) + : UnitTest(std::format("Pokemon::StoryActions - {}", scenario.input.name)) + , m_scenario(scenario) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_scenario.input.test(); + } + +private: + StoryActionsCase m_scenario; +}; + +const StoryActionsCase STORY_ACTIONS_CASES[] = { + { + .input = {.name = "table: exact, then any kind, then the kind's default", .test = test_lookup_order}, + .expectation = {.description = "finds the most specific action, or none"}, + }, + { + .input = {.name = "table: a second action for a key throws", .test = test_duplicate_actions_throw}, + .expectation = {.description = "keeps the first action and rejects nameless any-kind actions"}, + }, + { + .input = {.name = "lint: steps without an action", .test = test_lint_names_steps_without_actions}, + .expectation = {.description = "names each step the table has no action for"}, + }, + { + .input = {.name = "executor: the table, then the binding", .test = test_executor_uses_table_then_binding}, + .expectation = {.description = "a step without a table action is the binding's or unsupported, guarded before every step"}, + }, + { + .input = {.name = "executor: a console failure fails the step", .test = test_guard_turns_failures_into_outcomes}, + .expectation = {.description = "turns OperationFailedException into operation_failed and tells the guard"}, + }, + { + .input = {.name = "executor: a stop row rethrows", .test = test_guard_stop_rethrows}, + .expectation = {.description = "rethrows on a stop row and passes other exceptions through"}, + }, +}; + +} // namespace + + +void add_tests_StoryActions(UnitTestDatabase& database){ + for (const StoryActionsCase& scenario : STORY_ACTIONS_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h new file mode 100644 index 0000000000..d3593d58f6 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h @@ -0,0 +1,23 @@ +/* Story Actions Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryActions_Tests_H +#define PokemonAutomation_Pokemon_StoryActions_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for story action tables, the variant parser and the table executor. +void add_tests_StoryActions(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp new file mode 100644 index 0000000000..0012c5d2eb --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp @@ -0,0 +1,186 @@ +/* Story Interrupts + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_StoryInterrupts.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +void InterruptHandlerTable::add(InterruptKind kind, InterruptHandler handler){ + if (kind == InterruptKind::NONE || kind == InterruptKind::UNSETTLED){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + std::format("No handler can clear {}.", interrupt_kind_name(kind)) + ); + } + if (!m_handlers.emplace(kind, std::move(handler)).second){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + std::format("A second interrupt handler for {}", interrupt_kind_name(kind)) + ); + } +} + +const InterruptHandler* InterruptHandlerTable::find(InterruptKind kind) const{ + const auto iter = m_handlers.find(kind); + return iter == m_handlers.end() ? nullptr : &iter->second; +} + +void InterruptHandlerTable::starts_on(StoryStepKind step, InterruptKind kind){ + m_starts_on.emplace(step, kind); +} + +bool InterruptHandlerTable::step_starts_on(StoryStepKind step, InterruptKind kind) const{ + if (m_starts_on.contains({step, kind})){ + return true; + } + return kind == InterruptKind::UNSETTLED && ( + m_starts_on.contains({step, InterruptKind::WILD_ENCOUNTER}) || + m_starts_on.contains({step, InterruptKind::TRAINER_SIGHT}) + ); +} + + +namespace{ + +// Whether an UNSETTLED verdict on `look` may be a battle's opening: its +// fade is white (an encounter's flash), still down (a battle's fade ends +// on the battle), or came after a dialog box (a trainer's lines). +bool may_open_a_battle(const ScreenLook& look, const InterruptVerdict& verdict){ + const auto fade = std::find_if(verdict.evidence.begin(), verdict.evidence.end(), [](const ScreenEventChange& change){ + return change.edge == ScreenEventEdge::ROSE && + (change.event == ScreenEvent::FADE_WHITE || change.event == ScreenEvent::FADE_BLACK); + }); + if (fade == verdict.evidence.end()){ + return false; + } + const bool still_down = std::none_of(verdict.evidence.begin(), verdict.evidence.end(), [](const ScreenEventChange& change){ + return change.edge == ScreenEventEdge::FELL; + }); + if (fade->event == ScreenEvent::FADE_WHITE || still_down){ + return true; + } + return std::any_of(look.log.changes().begin(), look.log.changes().end(), [&](const ScreenEventChange& change){ + return change.event == ScreenEvent::DIALOG_BOX && change.edge == ScreenEventEdge::ROSE && + look.window.start <= change.time && change.time < fade->time; + }); +} + +// The look's verdict, looked at again while it is unsettled, up to +// max_looks looks in all, or max_opening_looks while it may be a battle's +// opening; not again before a step that starts on it. `screen` is how the +// last look ended. +InterruptVerdict settled_verdict(const StoryInterrupts& interrupts, StoryStepKind step, ScreenSettle& screen){ + ScreenLook look = interrupts.look(true); + InterruptVerdict verdict = classify_interrupt(look.log, look.window, interrupts.knobs); + const bool home = look.log.showing().has(ScreenEvent::SWITCH_HOME_MENU); + if (!home && !interrupts.handlers.step_starts_on(step, InterruptKind::UNSETTLED)){ + for (size_t looks = 1; verdict.kind == InterruptKind::UNSETTLED; looks++){ + const size_t limit = may_open_a_battle(look, verdict) ? interrupts.max_opening_looks : interrupts.max_looks; + if (looks >= limit){ + break; + } + look = interrupts.look(false); + verdict = classify_interrupt(look.log, look.window, interrupts.knobs); + } + } + screen = judge_settle(look); + return verdict; +} + +} // namespace + + +ScreenSettle judge_settle(const ScreenLook& look){ + ScreenSettle out; + const std::optional last = look.log.last_frame(); + if (!last || *last < look.window.start){ + return out; + } + out.seen = true; + out.showing = look.log.showing(); + WallClock since = look.window.start; + for (const ScreenEventChange& change : look.log.changes()){ + if (change.time <= look.window.end){ + since = std::max(since, change.time); + } + } + const WallClock end = std::max(look.window.end, since); + out.quiet = std::chrono::duration_cast(end - since); + return out; +} + +bool on_home_menu(const ScreenSettle& settle){ + return settle.seen && settle.showing.has(ScreenEvent::SWITCH_HOME_MENU); +} + +bool is_settled(const ScreenSettle& settle){ + return settle.seen && !on_home_menu(settle) && + settle.showing.has(ScreenEvent::PLAYER_CAN_MOVE) && + !settle.showing.any_of({ScreenEvent::DIALOG_BOX, ScreenEvent::BATTLE_STARTED}) && + fade_in(settle.showing) == WarpFade::NONE; +} + +std::string describe(const ScreenSettle& settle){ + if (!settle.seen){ + return "no frame seen"; + } + const std::string quiet = std::format("quiet {:.1f} s", settle.quiet.count() / 1000.0); + if (on_home_menu(settle)){ + return std::format("Switch HOME menu ({})", quiet); + } + if (is_settled(settle)){ + return std::format("settled overworld ({})", quiet); + } + return std::format("{} showing ({})", describe(settle.showing), quiet); +} + + +InterruptCheck clear_story_interrupt(const StoryInterrupts& interrupts, const StoryStep& step, RunState& state){ + InterruptCheck out; + out.verdict = settled_verdict(interrupts, step.kind, out.screen); + if (on_home_menu(out.screen)){ + out.verdict = {}; + out.outcome = outcome_game_not_running(); + return out; + } + const InterruptKind kind = out.verdict.kind; + if (kind == InterruptKind::NONE){ + return out; + } + if (interrupts.handlers.step_starts_on(step.kind, kind)){ + out.verdict = {}; + return out; + } + if (kind == InterruptKind::UNSETTLED){ + out.outcome = outcome_failed("interrupt_unsettled", step.name); + return out; + } + const InterruptHandler* handler = interrupts.handlers.find(kind); + if (handler == nullptr || !handler->handle){ + 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); + if (!handled.succeeded()){ + out.outcome = outcome_failed("interrupt_failed", std::format("{}: {}", interrupt_kind_name(kind), to_string(handled))); + return out; + } + apply_interrupt_pose(handler->pose, state.pose); + return out; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h new file mode 100644 index 0000000000..2bceba34c6 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h @@ -0,0 +1,96 @@ +/* Story Interrupts + * + * From: https://github.com/PokemonAutomation/ + * + * What stops the story between two of its steps: someone walks up and + * talks, a trainer sees us as a step ends, a wild battle starts on the + * last tile of a walk, a door takes us somewhere. A walk's own walker + * clears what happens part-way through it (Pokemon_LegWalker.h, BDSP's + * walks); this is what is left once a step has settled. + * + * Before each step, and after a step fails, the TableExecutor looks at + * the screen through the game's eyes (ScreenLookFunction), judges the + * look with the shared classifier (classify_interrupt()) and clears what + * it found with the game's handler for that kind of interrupt. The + * handlers are a table, like the story's actions: data a game binds to + * its console or its simulation, not a type per game. + * + * A step that starts on what the look found (a MASH on its scene's box, + * a BATTLE on its trainer's lines) is not interrupted by it: the table + * says which (InterruptHandlerTable::starts_on()). A step that starts on + * a battle also starts on an UNSETTLED screen, a fade with no battle yet: + * that is its battle's opening, still playing (BDSP's Starly battle right + * after the starter is picked), and the step waits for it itself. + * + * Before another step, an unsettled screen that may be a battle's opening + * (a white flash, a fade still down, a fade after a dialog box) is looked + * at until its battle shows, up to max_opening_looks looks: the walk + * before the step ended in grass or in a trainer's sight. The battle is + * then cleared as any other. A fade that came back up with no box before + * it (a door's) is looked at max_looks times only. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryInterrupts_H +#define PokemonAutomation_Pokemon_StoryInterrupts_H + +#include +#include +#include +#include +#include +#include +#include "Pokemon_Interrupts.h" +#include "Pokemon_ScreenEvents.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_StoryStepExecutor.h" +#include "Pokemon_InterruptHandlers.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How the screen looked at the end of a look: the line a run log needs to +// answer "had the scene ended before the step's first input?". +struct ScreenSettle{ + // Whether the look saw a frame at all. + bool seen = false; + // The events its last frame showed. + ScreenEvents showing = {}; + // How long the screen had shown them unchanged when the look ended. + Milliseconds quiet = Milliseconds(0); +}; +// The end of `look`: its last frame's events, and how long they held. +ScreenSettle judge_settle(const ScreenLook& look); +// Whether it ended on the HOME menu: the game is not running. +bool on_home_menu(const ScreenSettle& settle); +// Whether it ended on the overworld with no box, no fade and no battle. +bool is_settled(const ScreenSettle& settle); +// "settled overworld (quiet 0.3 s)", "black fade showing (quiet 0.1 s)", +// "Switch HOME menu (quiet 0.3 s)", "no frame seen". +std::string describe(const ScreenSettle& settle); + + +// What a look between steps found, and what clearing it came to. +struct InterruptCheck{ + // How the screen looked when the look ended, judged or not. + ScreenSettle screen = {}; + // NONE when nothing interrupted, or when the step starts on it. + InterruptVerdict verdict = {}; + // Failed when the look stayed unsettled, the kind had no handler, or + // the handler failed; GAME_NOT_RUNNING, with no verdict, when the + // look ended on the Switch's HOME menu. + Outcome outcome = {}; +}; + +// Looks at the screen before `step` (or after it failed) and clears what +// interrupted the player, if anything, writing the handler's effect on +// the pose into `state`. On the HOME menu it fails as GAME_NOT_RUNNING +// and clears nothing, whatever the step starts on. +InterruptCheck clear_story_interrupt(const StoryInterrupts& interrupts, const StoryStep& step, RunState& state); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp new file mode 100644 index 0000000000..234e0d926b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp @@ -0,0 +1,734 @@ +/* Story Interrupts Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The table executor's looks between steps, against a fake game: a + * scripted screen and handlers that note what they cleared. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryActions.h" +#include "Pokemon_StoryInterrupts.h" +#include "Pokemon_StoryInterrupts_Tests.h" +#include "Pokemon_StorySegments.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +const WallClock T0 = WallClock() + std::chrono::hours(1); + +// One frame of a scripted screen: its events, at `ms` after T0. +struct Frame{ + int ms; + ScreenEvents events; +}; + +const ScreenEvents WALK{ScreenEvent::PLAYER_CAN_MOVE}; +const ScreenEvents BOX{ScreenEvent::DIALOG_BOX, ScreenEvent::PLAYER_CAN_MOVE}; +const ScreenEvents WHITE{ScreenEvent::FADE_WHITE}; +const ScreenEvents BLACK{ScreenEvent::FADE_BLACK}; +const ScreenEvents BATTLE{ScreenEvent::BATTLE_STARTED}; +const ScreenEvents BANNER{ScreenEvent::LOCATION_BANNER, ScreenEvent::PLAYER_CAN_MOVE}; +// The Switch's HOME menu: the game is not running. +const ScreenEvents HOME{ScreenEvent::SWITCH_HOME_MENU}; + +// A look at `frames`, judged up to `until_ms`. +ScreenLook look_of(const std::vector& frames, int until_ms){ + ScreenLook look; + for (const Frame& frame : frames){ + look.log.record(frame.events, T0 + Milliseconds(frame.ms)); + } + look.window = {T0, T0 + Milliseconds(until_ms)}; + return look; +} + +ScreenLook quiet(){ + return look_of({{0, WALK}, {300, WALK}}, 300); +} +ScreenLook dialog(){ + return look_of({{0, WALK}, {100, BOX}}, 300); +} +ScreenLook wild(){ + return look_of({{0, WALK}, {100, WHITE}, {400, WALK}, {1500, BATTLE}}, 2000); +} +ScreenLook trainer(){ + return look_of({{0, WALK}, {100, BOX}, {2000, BLACK}, {2500, BATTLE}}, 3000); +} +ScreenLook warp(){ + return look_of({{0, WALK}, {100, BLACK}, {600, WALK}, {900, BANNER}}, 1200); +} +// A white fade with no battle yet: an encounter's flash or a cave exit. +ScreenLook white_unsettled(){ + return look_of({{0, WALK}, {100, WHITE}, {700, WALK}}, 1000); +} +// A trainer's lines, then the battle's black, still down: no battle yet. +ScreenLook trainer_opening(){ + return look_of({{0, WALK}, {100, BOX}, {2000, BLACK}}, 2100); +} +// A door's black, back up with no box before it: a warp, not yet settled. +ScreenLook black_unsettled(){ + return look_of({{0, WALK}, {100, BLACK}, {700, WALK}}, 1000); +} +// The same white, looked at for long enough after it: a cave exit. +ScreenLook white_settled(){ + return look_of({{0, WALK}, {100, WHITE}, {700, WALK}, {10000, WALK}}, 10000); +} +// The HOME menu, still: the program started with the game closed. +ScreenLook home_menu(){ + return look_of({{0, HOME}, {300, HOME}}, 300); +} +// The same, with a game's detectors reading it as the overworld too. +ScreenLook home_read_as_overworld(){ + ScreenEvents both = HOME; + both.set(ScreenEvent::PLAYER_CAN_MOVE, true); + return look_of({{0, both}}, 300); +} + + +// The fake game: the screen its looks show, one per look and then the +// last again, and a trace of what was looked at, cleared and run. +struct FakeGame{ + std::vector screens; + size_t looks = 0; + std::vector trace; + + ScreenLook look(bool fresh){ + trace.push_back(fresh ? "look" : "look again"); + const ScreenLook& out = screens.empty() ? quiet() : screens[std::min(looks, screens.size() - 1)]; + looks++; + return out; + } +}; + +// A handler that notes its kind; fails with `failure` if set. +InterruptHandler noting(std::string name, InterruptPose pose, std::string failure, FakeGame& game){ + return InterruptHandler{ + .handle = [&game, name, failure](const InterruptVerdict&, RunState&){ + game.trace.push_back(std::format("clear {}", name)); + return failure.empty() ? outcome_ok() : outcome_failed(failure); + }, + .pose = pose, + }; +} + +// All four handlers, a warp losing the pose; MASH starts on a dialog. +StoryInterrupts fake_interrupts(FakeGame& game){ + StoryInterrupts interrupts; + interrupts.look = [&game](bool fresh){ + return game.look(fresh); + }; + interrupts.handlers.add(InterruptKind::WILD_ENCOUNTER, noting("wild", InterruptPose::UNCHANGED, "", game)); + interrupts.handlers.add(InterruptKind::TRAINER_SIGHT, noting("trainer", InterruptPose::UNCHANGED, "", game)); + interrupts.handlers.add(InterruptKind::DIALOG, noting("dialog", InterruptPose::UNCHANGED, "", game)); + interrupts.handlers.add(InterruptKind::WARP, noting("warp", InterruptPose::LOST, "", game)); + interrupts.handlers.starts_on(StoryStepKind::MASH, InterruptKind::DIALOG); + return interrupts; +} + +StoryStep make(StoryStepKind kind, std::string name){ + StoryStep step; + step.kind = kind; + step.name = std::move(name); + return step; +} + +// The step's action: notes it ran, and fails its first `failures` runs, +// returning a failed Outcome or, with `throws`, throwing. +struct FakeAction{ + size_t failures = 0; + bool throws = false; +}; +StoryActionTable table_of(FakeAction action, FakeGame& game){ + StoryActionTable table; + auto runs = std::make_shared(0); + table.add_any_kind("act", StoryAction{ + .act = [&game, action, runs](const StoryStep& step, RunState&) -> Outcome{ + game.trace.push_back(std::format("run {}", step.name)); + if ((*runs)++ >= action.failures){ + return outcome_ok(); + } + if (action.throws){ + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, "stopped by a dialog"); + } + return outcome_failed("dialog", "stopped by a dialog"); + }, + }); + return table; +} + +// A guard that notes the interrupts it was told of. +class NotingGuard : public StepGuard{ +public: + explicit NotingGuard(FakeGame& game) + : m_game(game) + {} + virtual void on_interrupt(const StoryStep&, const InterruptCheck& check) override{ + m_game.trace.push_back(std::format("told {} {}", interrupt_kind_name(check.verdict.kind), to_string(check.outcome))); + } + +private: + FakeGame& m_game; +}; + +// `step` (action "act") run once by a TableExecutor with the fake +// game's interrupts, from a known pose. +struct FakeRun{ + Outcome outcome; + RunState state; +}; +FakeRun run_step(FakeGame& game, StoryInterrupts& interrupts, StoryStep step, FakeAction action = {}){ + const StoryActionTable table = table_of(action, game); + NotingGuard guard(game); + TableExecutor executor(table, guard); + executor.set_interrupts(&interrupts); + FakeRun out; + out.state.pose.map = "Town"; + out.state.pose.certainty = PoseCertainty::TILE; + step.action = "act"; + out.outcome = executor.run(step, out.state); + return out; +} + +UnitTestResult expect_trace(const FakeGame& game, const std::vector& expected){ + if (game.trace == expected){ + return true; + } + std::string out = "Expected the trace:"; + for (const std::string& line : expected){ + out += std::format("\n {}", line); + } + out += "\ngot:"; + for (const std::string& line : game.trace){ + out += std::format("\n {}", line); + } + return out; +} + + +UnitTestResult test_no_interrupts_set(){ + FakeGame game; + const StoryActionTable table = table_of({}, game); + StepGuard guard; + TableExecutor executor(table, guard); + RunState state; + StoryStep step = make(StoryStepKind::ROUTE, "walk"); + step.action = "act"; + const Outcome outcome = executor.run(step, state); + if (!outcome.succeeded()){ + return std::format("Expected the step to succeed, got {}", to_string(outcome)); + } + return expect_trace(game, {"run walk"}); +} + +UnitTestResult test_quiet_screen(){ + FakeGame game; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (!run.outcome.succeeded() || run.state.pose.certainty != PoseCertainty::TILE){ + return std::format("Expected the step to succeed where it stood, got {}", to_string(run.outcome)); + } + return expect_trace(game, {"look", "run walk"}); +} + +// A look showing `screen` before a ROUTE step: cleared by `handler`, then +// the step runs. +UnitTestResult test_cleared(ScreenLook screen, const std::string& kind, const std::string& handler, PoseCertainty pose){ + FakeGame game; + game.screens = {std::move(screen), quiet()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (!run.outcome.succeeded()){ + return std::format("Expected the step to succeed, got {}", to_string(run.outcome)); + } + if (run.state.pose.certainty != pose){ + return std::format("Expected the pose {}, got {}", certainty_name(pose), certainty_name(run.state.pose.certainty)); + } + return expect_trace(game, {"look", std::format("clear {}", handler), std::format("told {} ", kind), "run walk"}); +} + +UnitTestResult test_wild_encounter(){ + return test_cleared(wild(), "wild encounter", "wild", PoseCertainty::TILE); +} +UnitTestResult test_trainer_sight(){ + return test_cleared(trainer(), "trainer sight", "trainer", PoseCertainty::TILE); +} +UnitTestResult test_dialog(){ + return test_cleared(dialog(), "dialog", "dialog", PoseCertainty::TILE); +} +UnitTestResult test_warp(){ + return test_cleared(warp(), "warp", "warp", PoseCertainty::UNKNOWN); +} + +UnitTestResult test_step_starts_on_it(){ + FakeGame game; + game.screens = {dialog()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::MASH, "scene")); + if (!run.outcome.succeeded()){ + return std::format("Expected the step to succeed, got {}", to_string(run.outcome)); + } + return expect_trace(game, {"look", "run scene"}); +} + +UnitTestResult test_handler_fails_the_step(){ + FakeGame game; + game.screens = {dialog()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers = InterruptHandlerTable(); + interrupts.handlers.add(InterruptKind::DIALOG, noting("dialog", InterruptPose::UNCHANGED, "still_up", game)); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (run.outcome.failure != "interrupt_failed" || run.outcome.detail != "dialog: still_up"){ + return std::format("Expected interrupt_failed: dialog: still_up, got {}", to_string(run.outcome)); + } + return expect_trace(game, {"look", "clear dialog", "told dialog interrupt_failed: dialog: still_up"}); +} + +UnitTestResult test_unhandled_kind(){ + FakeGame game; + game.screens = {trainer()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers = InterruptHandlerTable(); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (run.outcome.failure != "unhandled_interrupt"){ + return std::format("Expected unhandled_interrupt, got {}", to_string(run.outcome)); + } + return expect_trace(game, {"look", "told trainer sight unhandled_interrupt: trainer sight before walk"}); +} + +UnitTestResult test_unsettled_looks_again(){ + FakeGame game; + game.screens = {white_unsettled(), white_settled(), quiet()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (!run.outcome.succeeded()){ + return std::format("Expected the step to succeed, got {}", to_string(run.outcome)); + } + return expect_trace(game, {"look", "look again", "clear warp", "told warp ", "run walk"}); +} + +// A door's fade is no battle's opening: three looks, as before. +UnitTestResult test_unsettled_is_bounded(){ + FakeGame game; + game.screens = {black_unsettled()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (run.outcome.failure != "interrupt_unsettled"){ + return std::format("Expected interrupt_unsettled, got {}", to_string(run.outcome)); + } + return expect_trace(game, {"look", "look again", "look again", "told unsettled interrupt_unsettled: walk"}); +} + +// A battle's opening still playing when a step that starts on a battle +// begins (BDSP's Starly battle, right after the starter is picked): the +// step's, on the first look, not interrupt_unsettled. +UnitTestResult test_unsettled_before_a_battle(){ + FakeGame game; + game.screens = {white_unsettled()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers.starts_on(StoryStepKind::BATTLE, InterruptKind::WILD_ENCOUNTER); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::BATTLE, "starly")); + if (!run.outcome.succeeded()){ + return std::format("Expected the battle step to run, got {}", to_string(run.outcome)); + } + return expect_trace(game, {"look", "run starly"}); +} + +// 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, +// 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; + game.screens = {opening, opening, opening, opening, std::move(battle), quiet()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (!run.outcome.succeeded()){ + return std::format("Expected the walk to run after the battle, got {}", to_string(run.outcome)); + } + return expect_trace(game, { + "look", "look again", "look again", "look again", "look again", + std::format("clear {}", handler), std::format("told {} ", kind), "run walk", + }); +} +UnitTestResult test_wild_opening_before_a_walk(){ + return test_opening_before_a_walk(white_unsettled(), wild(), "wild encounter", "wild"); +} +UnitTestResult test_trainer_opening_before_a_walk(){ + return test_opening_before_a_walk(trainer_opening(), trainer(), "trainer sight", "trainer"); +} + +// A white that shows no battle and does not settle: max_opening_looks. +UnitTestResult test_opening_is_bounded(){ + FakeGame game; + game.screens = {white_unsettled()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.max_opening_looks = 5; + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (run.outcome.failure != "interrupt_unsettled"){ + return std::format("Expected interrupt_unsettled, got {}", to_string(run.outcome)); + } + return expect_trace(game, { + "look", "look again", "look again", "look again", "look again", + "told unsettled interrupt_unsettled: walk", + }); +} + +UnitTestResult test_failure_explained(bool throws){ + FakeGame game; + // Before the step, after its failure, before its second run. + game.screens = {quiet(), dialog(), quiet()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk"), {.failures = 1, .throws = throws}); + if (!run.outcome.succeeded()){ + return std::format("Expected the step run again and succeed, got {}", to_string(run.outcome)); + } + return expect_trace(game, {"look", "run walk", "look", "clear dialog", "told dialog ", "look", "run walk"}); +} +UnitTestResult test_failed_outcome_explained(){ + return test_failure_explained(false); +} +UnitTestResult test_thrown_failure_explained(){ + return test_failure_explained(true); +} + +UnitTestResult test_failure_not_explained(){ + FakeGame game; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk"), {.failures = 1}); + if (run.outcome.failure != "dialog"){ + return std::format("Expected the step's own failure, got {}", to_string(run.outcome)); + } + return expect_trace(game, {"look", "run walk", "look"}); +} + +// A step that keeps failing with a dialog that keeps coming back: run +// again while the dialogs are cleared, until there have been too many. +UnitTestResult test_too_many_interrupts(){ + FakeGame game; + game.screens = {dialog()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk"), {.failures = 10}); + if (run.outcome.failure != "dialog" || game.looks != interrupts.max_per_step + 1){ + return std::format("Expected the step's own failure after {} looks, got {} after {}", + interrupts.max_per_step + 1, to_string(run.outcome), game.looks); + } + if (game.trace.back() != "told dialog too_many_interrupts: walk"){ + return std::format("Expected the guard told of too many interrupts, got {}", game.trace.back()); + } + return true; +} + +UnitTestResult test_table_rejects(){ + InterruptHandlerTable table; + table.add(InterruptKind::DIALOG, {}); + for (InterruptKind kind : {InterruptKind::NONE, InterruptKind::UNSETTLED, InterruptKind::DIALOG}){ + try{ + table.add(kind, {}); + return std::format("Expected a handler for {} rejected.", interrupt_kind_name(kind)); + }catch (InternalProgramError&){} + } + if (table.find(InterruptKind::DIALOG) == nullptr || table.find(InterruptKind::WARP) != nullptr){ + return "Expected the dialog's handler found and no warp's."; + } + return true; +} + +// A guard that notes how the screen looked before each step. +class ScreenGuard : public StepGuard{ +public: + explicit ScreenGuard(FakeGame& game) + : m_game(game) + {} + virtual void on_screen(const StoryStep& step, const ScreenSettle& screen) override{ + m_game.trace.push_back(std::format("before {}: {}", step.name, describe(screen))); + } + +private: + FakeGame& m_game; +}; + +// The guard hears how the screen looked before every step, interrupt or +// not: the run log's answer to "had the scene ended before the input?". +UnitTestResult test_screen_before_each_step(){ + FakeGame game; + // A scene's closing fade still down: no battle comes, so the step + // fails unsettled, and the guard hears the fade was showing. + game.screens = {look_of({{0, WALK}, {100, BLACK}}, 300)}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.max_opening_looks = 2; + const StoryActionTable table = table_of({}, game); + ScreenGuard guard(game); + TableExecutor executor(table, guard); + executor.set_interrupts(&interrupts); + RunState state; + StoryStep step = make(StoryStepKind::ROUTE, "by_the_counter"); + step.action = "act"; + const Outcome faded = executor.run(step, state); + if (faded.succeeded()){ + return std::format("Expected a step in a fade to fail unsettled, got {}", to_string(faded)); + } + game.screens = {quiet()}; + game.looks = 0; + const Outcome settled = executor.run(step, state); + if (!settled.succeeded()){ + return std::format("Expected the step on a quiet screen to run, got {}", to_string(settled)); + } + return expect_trace(game, { + "look", "look again", "before by_the_counter: black fade showing (quiet 0.2 s)", + "look", "before by_the_counter: settled overworld (quiet 0.3 s)", "run by_the_counter", + }); +} + +// 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 +// 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(){ + for (StoryStepKind kind : {StoryStepKind::SAVE, StoryStepKind::ROUTE, StoryStepKind::BATTLE}){ + FakeGame game; + game.screens = {home_menu()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers.starts_on(StoryStepKind::BATTLE, InterruptKind::TRAINER_SIGHT); + const StoryActionTable table = table_of({}, game); + ScreenGuard guard(game); + TableExecutor executor(table, guard); + executor.set_interrupts(&interrupts); + RunState state; + StoryStep step = make(kind, "save"); + step.action = "act"; + const Outcome outcome = executor.run(step, state); + if (to_string(outcome) != "game_not_running: the game is not running: the Switch HOME menu is showing"){ + return std::format("Expected the step on HOME to fail as game_not_running, got {}", to_string(outcome)); + } + if (UnitTestResult trace = expect_trace(game, {"look", "before save: Switch HOME menu (quiet 0.3 s)"}); trace.result != UnitTestResult::PASSED){ + return trace; + } + } + return true; +} + +// A checkpoint that fails on the HOME menu is neither recovered in place +// nor reloaded: every press would go to the console's menus. +UnitTestResult test_home_menu_stops_the_segment(){ + std::vector trace; + CheckpointSpec spec; + spec.id = "00.03"; + spec.build = [&trace]{ + Checkpoint checkpoint; + checkpoint.id = "00.03"; + Event save; + save.name = "save"; + save.act = [&trace](RunState&){ + trace.push_back("save"); + return outcome_failed("game_not_running", "the game is not running: the Switch HOME menu is showing"); + }; + Recovery wait; + wait.kind = RecoveryKind::WAIT; + wait.prepare = [&trace](RunState&){ + trace.push_back("recover"); + return outcome_ok(); + }; + save.recoveries.push_back(std::move(wait)); + checkpoint.events.push_back(std::move(save)); + return checkpoint; + }; + Segment segment; + segment.id = "00"; + segment.checkpoints.push_back(std::move(spec)); + SegmentHooks hooks; + hooks.reload = [&trace](RunState&){ + trace.push_back("reload"); + return outcome_ok(); + }; + RunState state; + const SegmentReport report = run_segment(SegmentRange{}, SegmentPolicy{}, segment, hooks, state); + if (report.completed || report.failure.failure != "game_not_running" || report.reloads != 0){ + return std::format("Expected the segment to stop on game_not_running with no reload, got {}", to_string(report.failure)); + } + if (trace != std::vector{"save"}){ + std::string got; + for (const std::string& line : trace){ + got += std::format(" {}", line); + } + return std::format("Expected the save tried once and nothing else, got:{}", got); + } + return true; +} + +UnitTestResult test_settle_of_a_look(){ + struct Row{ + std::string name; + ScreenLook look; + std::string expected; + }; + const std::vector rows = { + {"no frame", ScreenLook{}, "no frame seen"}, + {"a quiet overworld", quiet(), "settled overworld (quiet 0.3 s)"}, + {"a box", dialog(), "dialog box, player can move showing (quiet 0.2 s)"}, + {"a door's fade back up", black_unsettled(), "settled overworld (quiet 0.3 s)"}, + {"the HOME menu", home_menu(), "Switch HOME menu (quiet 0.3 s)"}, + {"HOME read as a quiet overworld too", home_read_as_overworld(), "Switch HOME menu (quiet 0.3 s)"}, + }; + for (const Row& row : rows){ + const std::string got = describe(judge_settle(row.look)); + if (got != row.expected){ + return std::format("{}: expected \"{}\", got \"{}\"", row.name, row.expected, got); + } + } + return true; +} + + +struct StoryInterruptsInput{ + std::string_view name; + UnitTestResult (*test)(); +}; + +struct StoryInterruptsExpectation{ + std::string_view description; +}; + +struct StoryInterruptsCase{ + StoryInterruptsInput input; + StoryInterruptsExpectation expectation; +}; + +class Test_StoryInterrupts : public UnitTest{ +public: + explicit Test_StoryInterrupts(StoryInterruptsCase scenario) + : UnitTest(std::format("Pokemon::StoryInterrupts - {}", scenario.input.name)) + , m_scenario(scenario) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_scenario.input.test(); + } + +private: + StoryInterruptsCase m_scenario; +}; + +const StoryInterruptsCase STORY_INTERRUPTS_CASES[] = { + { + .input = {.name = "no interrupts set: no look", .test = test_no_interrupts_set}, + .expectation = {.description = "the executor runs the step as before"}, + }, + { + .input = {.name = "a quiet screen: one look, then the step", .test = test_quiet_screen}, + .expectation = {.description = "nothing cleared, the pose kept"}, + }, + { + .input = {.name = "a wild encounter before a step", .test = test_wild_encounter}, + .expectation = {.description = "the wild handler, then the step"}, + }, + { + .input = {.name = "a trainer's sight before a step", .test = test_trainer_sight}, + .expectation = {.description = "the trainer handler, then the step"}, + }, + { + .input = {.name = "a dialog before a step", .test = test_dialog}, + .expectation = {.description = "the dialog handler, then the step"}, + }, + { + .input = {.name = "a warp before a step", .test = test_warp}, + .expectation = {.description = "the warp handler, the pose lost, then the step"}, + }, + { + .input = {.name = "a step that starts on it", .test = test_step_starts_on_it}, + .expectation = {.description = "a MASH's box is the step's, not an interrupt"}, + }, + { + .input = {.name = "a handler that fails fails the step", .test = test_handler_fails_the_step}, + .expectation = {.description = "interrupt_failed, the step not run"}, + }, + { + .input = {.name = "a kind with no handler fails the step", .test = test_unhandled_kind}, + .expectation = {.description = "unhandled_interrupt, the step not run"}, + }, + { + .input = {.name = "unsettled: look again until it settles", .test = test_unsettled_looks_again}, + .expectation = {.description = "a white with no battle after it is a warp"}, + }, + { + .input = {.name = "unsettled: at most max_looks looks", .test = test_unsettled_is_bounded}, + .expectation = {.description = "a door's fade: interrupt_unsettled after three looks"}, + }, + { + .input = {.name = "unsettled: a battle's opening before a battle step", .test = test_unsettled_before_a_battle}, + .expectation = {.description = "the step's, after one look"}, + }, + { + .input = {.name = "unsettled: a wild battle's opening before a walk", .test = test_wild_opening_before_a_walk}, + .expectation = {.description = "waits for the battle, clears it, then the walk"}, + }, + { + .input = {.name = "unsettled: a trainer battle's opening before a walk", .test = test_trainer_opening_before_a_walk}, + .expectation = {.description = "waits for the battle, fights it, then the walk"}, + }, + { + .input = {.name = "unsettled: at most max_opening_looks for an opening", .test = test_opening_is_bounded}, + .expectation = {.description = "a white with no battle: interrupt_unsettled"}, + }, + { + .input = {.name = "a failed step an interrupt explains runs again", .test = test_failed_outcome_explained}, + .expectation = {.description = "cleared after the failure, then the step again"}, + }, + { + .input = {.name = "a thrown step an interrupt explains runs again", .test = test_thrown_failure_explained}, + .expectation = {.description = "the console's failure too"}, + }, + { + .input = {.name = "a failed step with nothing on screen fails", .test = test_failure_not_explained}, + .expectation = {.description = "the step's own failure, run once"}, + }, + { + .input = {.name = "too many interrupts fail the step", .test = test_too_many_interrupts}, + .expectation = {.description = "the step's failure once max_per_step are cleared"}, + }, + { + .input = {.name = "table: one handler a kind that can be cleared", .test = test_table_rejects}, + .expectation = {.description = "rejects NONE, UNSETTLED and a second handler"}, + }, + { + .input = {.name = "the screen before each step, for the log", .test = test_screen_before_each_step}, + .expectation = {.description = "a fade still down is told, and fails unsettled; a quiet overworld is settled"}, + }, + { + .input = {.name = "how a look ended", .test = test_settle_of_a_look}, + .expectation = {.description = "the last frame's events and how long they held"}, + }, + { + .input = {.name = "the HOME menu before a step", .test = test_home_menu_before_a_step}, + .expectation = {.description = "told as HOME; game_not_running before any input"}, + }, + { + .input = {.name = "the HOME menu stops the segment", .test = test_home_menu_stops_the_segment}, + .expectation = {.description = "no recovery in place, no reload"}, + }, +}; + +} // namespace + + +void add_tests_StoryInterrupts(UnitTestDatabase& database){ + for (const StoryInterruptsCase& scenario : STORY_INTERRUPTS_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.h new file mode 100644 index 0000000000..4ba110b077 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.h @@ -0,0 +1,23 @@ +/* Story Interrupts Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryInterrupts_Tests_H +#define PokemonAutomation_Pokemon_StoryInterrupts_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the table executor's looks for interrupts between steps. +void add_tests_StoryInterrupts(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index d734e275f7..993334966c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -8,6 +8,7 @@ #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" @@ -288,6 +289,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_BattleMoveSelectionArrow(database); add_tests_BagDetector(database); add_tests_ExitWildBattle(database); + add_tests_AutoStoryScreenEvents(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.cpp new file mode 100644 index 0000000000..85edb74b36 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.cpp @@ -0,0 +1,52 @@ +/* FRLG AutoStory - Screen Events + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonFRLG_AutoStoryScreenEvents.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using Pokemon::ScreenEvent; +using Pokemon::ScreenEvents; + + +FrlgScreenObserver::FrlgScreenObserver() + : m_dialog(COLOR_RED) + , m_choice(COLOR_RED) + , m_battle_menu(COLOR_RED) + , m_battle_dialog(COLOR_RED) +{} + +ScreenEvents FrlgScreenObserver::observe(const VideoSnapshot& frame, WallClock){ + if (!frame){ + return {}; + } + const ImageViewRGB32& screen = *frame.frame; + ScreenEvents out = Pokemon::fade_events(Pokemon::fade_of_screen(screen)); + if (Pokemon::fade_in(out) != Pokemon::WarpFade::NONE){ + // A uniform screen has no box or menu to read. + return out; + } + const bool battle = m_battle_menu.detect(screen) || m_battle_dialog.detect(screen); + out.set(ScreenEvent::BATTLE_STARTED, battle); + out.set(ScreenEvent::DIALOG_BOX, !battle && m_dialog.detect(screen)); + out.set(ScreenEvent::CHOICE_BOX, !battle && m_choice.detect(screen)); + return out; +} + +void FrlgScreenObserver::make_overlays(VideoOverlaySet& items) const{ + m_dialog.make_overlays(items); + m_choice.make_overlays(items); + m_battle_menu.make_overlays(items); + m_battle_dialog.make_overlays(items); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h new file mode 100644 index 0000000000..8de3ed926a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h @@ -0,0 +1,49 @@ +/* FRLG AutoStory - Screen Events + * + * From: https://github.com/PokemonAutomation/ + * + * FRLG's detectors as the shared screen events (Pokemon_ScreenEvents.h), + * so the shared judgements (Pokemon_SceneJudges.h) read FRLG frames too. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryScreenEvents_H +#define PokemonAutomation_PokemonFRLG_AutoStoryScreenEvents_H + +#include "Pokemon/AutoStory/Pokemon_ScreenEvents.h" +#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_BattleDialogs.h" +#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_DialogDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The shared events from FRLG's detectors: +// - DIALOG_BOX: the overworld's white text box (WhiteDialogDetector); +// - CHOICE_BOX: a Yes/No or answer box beside it (SelectionDialogDetector); +// - BATTLE_STARTED: the battle menu or a battle's text box; +// - FADE_BLACK / FADE_WHITE: fade_of_screen(). +// Not reported yet, as FRLG has no detector for them here: the map-name +// popup (LOCATION_BANNER), PLAYER_CAN_MOVE, SCREEN_STILL, the interact +// prompt (FRLG has none) and a battle's end. +class FrlgScreenObserver : public Pokemon::ScreenEventObserver{ +public: + FrlgScreenObserver(); + + virtual Pokemon::ScreenEvents observe(const VideoSnapshot& frame, WallClock now) override; + virtual void make_overlays(VideoOverlaySet& items) const override; + +private: + WhiteDialogDetector m_dialog; + SelectionDialogDetector m_choice; + BattleMenuDetector m_battle_menu; + BattleDialogDetector m_battle_dialog; +}; + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp new file mode 100644 index 0000000000..8bd21ac0f9 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp @@ -0,0 +1,98 @@ +/* FRLG AutoStory - Screen Events Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The adapter on synthetic frames: a uniform screen is a fade and nothing + * else, and no frame shows nothing. Frames of real boxes and battles are + * the detectors' own image tests (CommandLineTests); a flat grey frame is + * not one of those (the battle text box reads it as a box). + * + */ + +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "PokemonFRLG_AutoStoryScreenEvents.h" +#include "PokemonFRLG_AutoStoryScreenEvents_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using Pokemon::ScreenEvent; +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; +}; + +class Test_AutoStoryScreenEvents : public UnitTest{ +public: + explicit Test_AutoStoryScreenEvents(ScreenEventsCase test_case) + : UnitTest(std::format("PokemonFRLG::AutoStoryScreenEvents - {}", test_case.input.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + VideoSnapshot frame; + if (m_case.input.color != 0){ + ImageRGB32 image(1920, 1080); + image.fill(m_case.input.color); + frame = VideoSnapshot(std::move(image), WallClock()); + } + FrlgScreenObserver observer; + const ScreenEvents got = observer.observe(frame, WallClock()); + if (got != m_case.expectation.events){ + return std::format("expected {}, got {}", describe(m_case.expectation.events), describe(got)); + } + return true; + } + +private: + ScreenEventsCase m_case; +}; + +} // namespace + + +const ScreenEventsCase SCREEN_EVENTS_CASES[] = { + { + .input = {"no frame shows nothing", 0}, + .expectation = {{}}, + }, + { + .input = {"a black screen is a black fade only", 0xff000000}, + .expectation = {{ScreenEvent::FADE_BLACK}}, + }, + { + .input = {"a white screen is a white fade only", 0xffffffff}, + .expectation = {{ScreenEvent::FADE_WHITE}}, + }, +}; + +void add_tests_AutoStoryScreenEvents(UnitTestDatabase& database){ + for (const auto& item : SCREEN_EVENTS_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.h new file mode 100644 index 0000000000..39b267b4d7 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.h @@ -0,0 +1,25 @@ +/* FRLG AutoStory - Screen Events Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryScreenEvents_Tests_H +#define PokemonAutomation_PokemonFRLG_AutoStoryScreenEvents_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Registers the screen-event adapter's unit tests (synthetic frames). +void add_tests_AutoStoryScreenEvents(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index fc68ce0b5f..a0fdfd3863 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1554,6 +1554,7 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.cpp Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h Source/Pokemon/AutoStory/Pokemon_FadeProfiles.h + Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp Source/Pokemon/AutoStory/Pokemon_Interrupts.h Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp @@ -1570,12 +1571,20 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.h Source/Pokemon/AutoStory/Pokemon_ScreenFades.h + Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp + Source/Pokemon/AutoStory/Pokemon_StoryActions.h + Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h Source/Pokemon/AutoStory/Pokemon_StoryCheckpointTypes.h Source/Pokemon/AutoStory/Pokemon_StoryEvent.h Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp Source/Pokemon/AutoStory/Pokemon_StoryEvents.h Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.h + Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp + Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h + Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.h Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp Source/Pokemon/AutoStory/Pokemon_StoryLog.h Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp @@ -1936,6 +1945,10 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/Farming/PokemonFRLG_NuggetBridgeFarmer.h Source/VideoGames/PokemonFRLG/Programs/Farming/PokemonFRLG_PickupFarmer.cpp Source/VideoGames/PokemonFRLG/Programs/Farming/PokemonFRLG_PickupFarmer.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.h Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_BattleMenuNavigation.cpp Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_BattleMenuNavigation.h Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_SafariOptimalAction.cpp From aa0597b02b866ebf8b1dfa9e4931b4eda42728f6 Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 11:38:14 -0800 Subject: [PATCH 02/20] AutoStory: shared program shell for BDSP and FRLG Start preparation, the runner's reload, and the finish of a run or a verify run, written once for both games. A start at a checkpoint with a save always loads that save first; a failure leaves the game where it failed, with the same log lines in both games. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_AutoStoryShell.cpp | 130 ++++++++++ .../AutoStory/Pokemon_AutoStoryShell.h | 92 +++++++ .../Pokemon_AutoStoryShell_Tests.cpp | 236 ++++++++++++++++++ .../AutoStory/Pokemon_AutoStoryShell_Tests.h | 23 ++ .../AutoStory/Pokemon_AutoStory_Tests.h | 2 + SerialPrograms/cmake/SourceFiles.cmake | 4 + 6 files changed, 487 insertions(+) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell.cpp new file mode 100644 index 0000000000..f8771c8532 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell.cpp @@ -0,0 +1,130 @@ +/* AutoStory Program Shell + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_AutoStoryShell.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +void log_line(const std::string& line, StoryGameHooks& game){ + if (game.log){ + game.log(line); + } +} + +std::string story_stop_message(const SegmentReport& report){ + if (report.completed){ + return ""; + } + return std::format( + "AutoStory stopped at {} {}: {}", + report.failed_checkpoint, report.failed_event, to_string(report.failure) + ); +} + +std::string story_verify_summary(std::string_view checkpoint, const VerifyPolicy& policy, const VerifyReport& report){ + return std::format( + "AutoStory verify: {} {}/{} passed, {} needed.", checkpoint, report.passes, policy.runs, policy.passes_needed + ); +} + +Outcome load_story_save(std::string_view reason, StoryGameHooks& game, RunState& state){ + log_line(std::format("[Story] {}: loading the save", reason), game); + Outcome outcome = game.load_save(state); + if (outcome.succeeded() && game.check_save_place){ + const std::string error = game.check_save_place(); + if (!error.empty()){ + outcome = outcome_failed("wrong_save", error); + } + } + if (outcome.succeeded() && game.after_load){ + outcome = game.after_load(state); + } + if (!outcome.succeeded()){ + log_line(std::format("[Story] {}", to_string(outcome)), game); + } + return outcome; +} + +} // namespace + +Outcome prepare_story_start(std::string_view checkpoint, StoryStart start, StoryGameHooks& game, RunState& state){ + switch (start){ + case StoryStart::NEW_GAME: + log_line(std::format("[Story] {}: starts a new game, no save to load", checkpoint), game); + return outcome_ok(); + case StoryStart::LIVE: + log_line(std::format("[Story] {}: starts from the game as it is, no save to load", checkpoint), game); + return outcome_ok(); + case StoryStart::FROM_SAVE: + break; + } + Outcome outcome = load_story_save(checkpoint, game, state); + if (outcome.succeeded()){ + state.flags.insert("save_loaded"); + } + return outcome; +} + +SegmentHooks story_segment_hooks(StoryGameHooks& game){ + SegmentHooks hooks; + hooks.reload = [&game](RunState& state){ + return load_story_save("retry", game, state); + }; + hooks.save = [&game](RunState& state){ + if (!game.save){ + return outcome_failed("no_save_hook", "this game's rows save at their start"); + } + return game.save(state); + }; + hooks.log = [&game](const std::string& line){ + log_line(line, game); + }; + hooks.status = [&game](const std::string& line){ + if (game.status){ + game.status(line); + } + }; + return hooks; +} + +void log_story_failure(StoryGameHooks& game){ + log_line(std::string(STORY_LEFT_WHERE_FAILED), game); +} + +std::string finish_story_run(const SegmentReport& report, std::string_view last, AutoStoryStats& stats, StoryGameHooks& game){ + record_story_counts(report.story_counts(), stats); + if (!report.completed){ + log_story_failure(game); + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, story_stop_message(report)); + } + std::string done = std::format("AutoStory: done through {}.", last); + log_line(done, game); + return done; +} + +std::string finish_story_verify( + std::string_view checkpoint, const VerifyPolicy& policy, const VerifyReport& report, StoryGameHooks& game +){ + std::string summary = story_verify_summary(checkpoint, policy, report); + if (!report.verified){ + log_story_failure(game); + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, summary); + } + log_line(summary, game); + return summary; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell.h new file mode 100644 index 0000000000..56524b5f4a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell.h @@ -0,0 +1,92 @@ +/* AutoStory Program Shell + * + * From: https://github.com/PokemonAutomation/ + * + * What every game's AutoStory program does around its story rows: get the + * game to the start checkpoint, lend the segment runner its reload, and + * finish a run or a verify run with the same log lines, stats and errors. + * A game lends only what really differs: how it loads its save (BDSP + * resets from HOME, FRLG soft-resets) and how it checks where the save is. + * + * Two rules hold for every game: + * - A run that starts at a checkpoint with a save loads that save first, + * so it never walks from wherever the game was left. + * - 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. + * + */ + +#ifndef PokemonAutomation_Pokemon_AutoStoryShell_H +#define PokemonAutomation_Pokemon_AutoStoryShell_H + +#include +#include +#include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon_AutoStoryStats.h" +#include "Pokemon_StoryCheckpointTypes.h" +#include "Pokemon_StoryOutcome.h" +#include "Pokemon_StorySegments.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How the game reaches the start checkpoint. +enum class StoryStart{ + // A new game from the title screen: there is no save. + NEW_GAME, + // The game as another program left it: nothing is loaded. + LIVE, + // The checkpoint's save, loaded first. + FROM_SAVE, +}; + +// What a game lends the shell. +struct StoryGameHooks{ + // Loads the last save: the game reset (from HOME or soft) and back in + // the overworld. A failed Outcome says why. + Act load_save; + // Optional: after a load, "" when the save is where the checkpoint + // about to run starts, else why not. + MoveOnlyFunction check_save_place; + // Optional: after a load and its place check, rereads what the save + // holds (FRLG: the bag's supplies). + Act after_load; + // Optional: saves the game (rows that save at their end). + Act save; + EventLogger log; + // Optional: the step under way, for the video overlay. + EventLogger status; +}; + +// The line logged after any failure. +inline constexpr std::string_view STORY_LEFT_WHERE_FAILED = "AutoStory failed: the game stays where it failed."; + +// Gets the game to where checkpoint `checkpoint` starts, as `start` says. +// FROM_SAVE always loads the save (logging "[Story] 00.04b: loading the +// save"), checks its place and rereads it, and sets the "save_loaded" flag. +Outcome prepare_story_start(std::string_view checkpoint, StoryStart start, StoryGameHooks& game, RunState& state); + +// The runner's hooks: reload is load_story_save(); save, log and status +// are the game's. `game` must outlive them. +SegmentHooks story_segment_hooks(StoryGameHooks& game); + +// Ends a run: its counts into `stats`, then the failure line and an +// OperationFailedException if it stopped short, else "AutoStory: done +// through ." Returns that line, for the finish notification. +std::string finish_story_run(const SegmentReport& report, std::string_view last, AutoStoryStats& stats, StoryGameHooks& game); + +// Ends a verify run: the summary, and the failure line and an +// OperationFailedException unless verified. Returns the summary. +std::string finish_story_verify( + std::string_view checkpoint, const VerifyPolicy& policy, const VerifyReport& report, StoryGameHooks& game +); + +// The failure line, for a game whose run threw before the shell saw it. +void log_story_failure(StoryGameHooks& game); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.cpp new file mode 100644 index 0000000000..16722ad2be --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.cpp @@ -0,0 +1,236 @@ +/* AutoStory Program Shell Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_AutoStoryShell.h" +#include "Pokemon_AutoStoryShell_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +// A game that records what the shell asked of it. +struct FakeGame{ + std::string place_error; + size_t loads = 0; + size_t rereads = 0; + size_t saves = 0; + std::vector lines; + + StoryGameHooks hooks(){ + StoryGameHooks game; + game.load_save = [this](RunState&){ + loads++; + return outcome_ok(); + }; + game.check_save_place = [this]{ + return place_error; + }; + game.after_load = [this](RunState&){ + rereads++; + return outcome_ok(); + }; + game.save = [this](RunState&){ + saves++; + return outcome_ok(); + }; + game.log = [this](const std::string& line){ + lines.push_back(line); + }; + return game; + } + bool logged(std::string_view line) const{ + for (const std::string& logged_line : lines){ + if (logged_line == line){ + return true; + } + } + return false; + } +}; + +// A start as the program asks for it, and what the game must have done. +struct StartCase{ + std::string name; + StoryStart start; + std::string place_error; + bool succeeds; + size_t loads; + size_t rereads; + bool save_loaded; +}; + +class Test_StoryStart : public UnitTest{ +public: + Test_StoryStart(StartCase test_case) + : UnitTest(std::format("Pokemon::AutoStoryShell - start: {}", test_case.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + FakeGame fake; + fake.place_error = m_case.place_error; + StoryGameHooks game = fake.hooks(); + RunState state; + const Outcome outcome = prepare_story_start("00.04b", m_case.start, game, state); + const bool save_loaded = state.flags.contains("save_loaded"); + if (outcome.succeeded() != m_case.succeeds || fake.loads != m_case.loads + || fake.rereads != m_case.rereads || save_loaded != m_case.save_loaded + ){ + return std::format( + "Expected ok={} loads={} rereads={} save_loaded={}, got {} {} {} {} ({})", + m_case.succeeds, m_case.loads, m_case.rereads, m_case.save_loaded, + outcome.succeeded(), fake.loads, fake.rereads, save_loaded, to_string(outcome) + ); + } + return true; + } + +private: + const StartCase m_case; +}; + +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 checkpoint with a save loads it first", StoryStart::FROM_SAVE, "", true, 1, 1, true}, + {"a save in the wrong place fails before rereading it", StoryStart::FROM_SAVE, "The save is in Pewter City.", false, 1, 0, false}, + {"a new game loads nothing", StoryStart::NEW_GAME, "", true, 0, 0, false}, + {"a live start loads nothing", StoryStart::LIVE, "", true, 0, 0, false}, +}; + + +// A failed attempt's reload loads the save through the game. +class Test_StoryReload : public UnitTest{ +public: + Test_StoryReload() + : UnitTest("Pokemon::AutoStoryShell - a retry reloads the save") + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + FakeGame fake; + StoryGameHooks game = fake.hooks(); + 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)); + } + return true; + } +}; + + +// A run that stopped short throws, logs the failure line and touches +// nothing in the game: no reload, no save, no reset to HOME. +class Test_StoryFailureLeavesGame : public UnitTest{ +public: + Test_StoryFailureLeavesGame() + : UnitTest("Pokemon::AutoStoryShell - a failed run leaves the game where it failed") + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + FakeGame fake; + StoryGameHooks game = fake.hooks(); + SegmentReport report; + report.completed = false; + report.failed_checkpoint = "00.04b"; + report.failed_event = "talk_mom"; + report.failure = outcome_failed("expect_failed", "dialogue opened"); + AutoStoryStats stats; + std::string message; + try{ + finish_story_run(report, "00.05", 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"){ + return std::format("Unexpected message: {}", message); + } + if (!fake.logged(STORY_LEFT_WHERE_FAILED)){ + return "Expected the failure line"; + } + if (fake.loads != 0 || fake.saves != 0){ + return std::format("Expected the game untouched, got {} loads and {} saves", fake.loads, fake.saves); + } + return true; + } +}; + + +// A completed run logs and returns the line the finish notification sends. +class Test_StoryFinished : public UnitTest{ +public: + Test_StoryFinished() + : UnitTest("Pokemon::AutoStoryShell - a completed run is done through its last checkpoint") + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + FakeGame fake; + StoryGameHooks game = fake.hooks(); + 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)){ + return std::format("Unexpected finish line: {}", done); + } + return true; + } +}; + + +// A verify run short of its passes throws with the summary. +class Test_StoryVerifyFailed : public UnitTest{ +public: + Test_StoryVerifyFailed() + : UnitTest("Pokemon::AutoStoryShell - an unverified checkpoint fails with its summary") + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + FakeGame fake; + StoryGameHooks game = fake.hooks(); + VerifyPolicy policy; + VerifyReport report; + report.passes = 1; + report.verified = false; + std::string message; + try{ + finish_story_verify("00.15b", 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)){ + return std::format("Unexpected message: {}", message); + } + return true; + } +}; + +} // namespace + + +void add_tests_AutoStoryShell(UnitTestDatabase& database){ + for (const StartCase& test_case : START_CASES){ + database.add(test_case); + } + database.add(); + database.add(); + database.add(); + database.add(); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.h new file mode 100644 index 0000000000..84ae8d3eea --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.h @@ -0,0 +1,23 @@ +/* AutoStory Program Shell Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_AutoStoryShell_Tests_H +#define PokemonAutomation_Pokemon_AutoStoryShell_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the AutoStory program shell's start, reload and finish. +void add_tests_AutoStoryShell(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 3967ee9e91..4d84cf41ce 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -19,6 +19,7 @@ #include "Engine/Pokemon_StoryEngine_Tests.h" #include "Pokemon/Options/Pokemon_StoryRangeOptions_Tests.h" #include "Pokemon_AutoStorySelect_Tests.h" +#include "Pokemon_AutoStoryShell_Tests.h" #include "Pokemon_AutoStoryStats_Tests.h" #include "Pokemon_Interrupts_Tests.h" #include "Pokemon_SceneJudges_Tests.h" @@ -40,6 +41,7 @@ namespace Pokemon{ // Registers every shared AutoStory suite, for the unit test runner. inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_AutoStorySelect(database); + add_tests_AutoStoryShell(database); add_tests_AutoStoryStats(database); add_tests_StoryLog(database); add_tests_StoryRangeOptions(database); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index a0fdfd3863..76fcac9782 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1546,6 +1546,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_AutoStoryShell.cpp + Source/Pokemon/AutoStory/Pokemon_AutoStoryShell.h + Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.cpp Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp From b43ebed0cb3ef36404b9376eb59995f0925d7153 Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 12:24:56 -0800 Subject: [PATCH 03/20] AutoStory: rename the program shell to StoryRun Pokemon_AutoStoryShell{,_Tests} -> Pokemon_StoryRun{,_Tests}; include guards, header titles, test suite name and registration follow. No behaviour change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_AutoStoryShell_Tests.h | 23 ------------------- .../AutoStory/Pokemon_AutoStory_Tests.h | 4 ++-- ...utoStoryShell.cpp => Pokemon_StoryRun.cpp} | 4 ++-- ...on_AutoStoryShell.h => Pokemon_StoryRun.h} | 12 +++++----- ...l_Tests.cpp => Pokemon_StoryRun_Tests.cpp} | 20 ++++++++-------- .../AutoStory/Pokemon_StoryRun_Tests.h | 23 +++++++++++++++++++ SerialPrograms/cmake/SourceFiles.cmake | 8 +++---- 7 files changed, 47 insertions(+), 47 deletions(-) delete mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.h rename SerialPrograms/Source/Pokemon/AutoStory/{Pokemon_AutoStoryShell.cpp => Pokemon_StoryRun.cpp} (95%) rename SerialPrograms/Source/Pokemon/AutoStory/{Pokemon_AutoStoryShell.h => Pokemon_StoryRun.h} (89%) rename SerialPrograms/Source/Pokemon/AutoStory/{Pokemon_AutoStoryShell_Tests.cpp => Pokemon_StoryRun_Tests.cpp} (88%) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.h deleted file mode 100644 index 84ae8d3eea..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.h +++ /dev/null @@ -1,23 +0,0 @@ -/* AutoStory Program Shell Tests - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_AutoStoryShell_Tests_H -#define PokemonAutomation_Pokemon_AutoStoryShell_Tests_H - -#include "Common/Cpp/TestRunners/UnitTestDatabase.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -// Registers unit tests for the AutoStory program shell's start, reload and finish. -void add_tests_AutoStoryShell(UnitTestDatabase& database); - - - -} // namespace Pokemon -} // namespace PokemonAutomation -#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 4d84cf41ce..906540637b 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -19,7 +19,7 @@ #include "Engine/Pokemon_StoryEngine_Tests.h" #include "Pokemon/Options/Pokemon_StoryRangeOptions_Tests.h" #include "Pokemon_AutoStorySelect_Tests.h" -#include "Pokemon_AutoStoryShell_Tests.h" +#include "Pokemon_StoryRun_Tests.h" #include "Pokemon_AutoStoryStats_Tests.h" #include "Pokemon_Interrupts_Tests.h" #include "Pokemon_SceneJudges_Tests.h" @@ -41,7 +41,7 @@ namespace Pokemon{ // Registers every shared AutoStory suite, for the unit test runner. inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_AutoStorySelect(database); - add_tests_AutoStoryShell(database); + add_tests_StoryRun(database); add_tests_AutoStoryStats(database); add_tests_StoryLog(database); add_tests_StoryRangeOptions(database); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp similarity index 95% rename from SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell.cpp rename to SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp index f8771c8532..7e7ff7c736 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp @@ -1,4 +1,4 @@ -/* AutoStory Program Shell +/* AutoStory Story Run * * From: https://github.com/PokemonAutomation/ * @@ -7,7 +7,7 @@ #include #include #include "CommonFramework/Exceptions/OperationFailedException.h" -#include "Pokemon_AutoStoryShell.h" +#include "Pokemon_StoryRun.h" namespace PokemonAutomation{ namespace Pokemon{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h similarity index 89% rename from SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell.h rename to SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h index 56524b5f4a..cfbeca7696 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h @@ -1,8 +1,8 @@ -/* AutoStory Program Shell +/* AutoStory Story Run * * From: https://github.com/PokemonAutomation/ * - * What every game's AutoStory program does around its story rows: get the + * The start and finish of a story run: get the * game to the start checkpoint, lend the segment runner its reload, and * finish a run or a verify run with the same log lines, stats and errors. * A game lends only what really differs: how it loads its save (BDSP @@ -16,8 +16,8 @@ * */ -#ifndef PokemonAutomation_Pokemon_AutoStoryShell_H -#define PokemonAutomation_Pokemon_AutoStoryShell_H +#ifndef PokemonAutomation_Pokemon_StoryRun_H +#define PokemonAutomation_Pokemon_StoryRun_H #include #include @@ -41,7 +41,7 @@ enum class StoryStart{ FROM_SAVE, }; -// What a game lends the shell. +// What a game lends the story run. struct StoryGameHooks{ // Loads the last save: the game reset (from HOME or soft) and back in // the overworld. A failed Outcome says why. @@ -82,7 +82,7 @@ std::string finish_story_verify( std::string_view checkpoint, const VerifyPolicy& policy, const VerifyReport& report, StoryGameHooks& game ); -// The failure line, for a game whose run threw before the shell saw it. +// The failure line, for a game whose run threw before the story run saw it. void log_story_failure(StoryGameHooks& game); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp similarity index 88% rename from SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.cpp rename to SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp index 16722ad2be..dd5ecc7a33 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp @@ -1,4 +1,4 @@ -/* AutoStory Program Shell Tests +/* AutoStory Story Run Tests * * From: https://github.com/PokemonAutomation/ * @@ -9,15 +9,15 @@ #include #include "Common/Cpp/TestRunners/UnitTest.h" #include "CommonFramework/Exceptions/OperationFailedException.h" -#include "Pokemon_AutoStoryShell.h" -#include "Pokemon_AutoStoryShell_Tests.h" +#include "Pokemon_StoryRun.h" +#include "Pokemon_StoryRun_Tests.h" namespace PokemonAutomation{ namespace Pokemon{ namespace{ -// A game that records what the shell asked of it. +// A game that records what the story run asked of it. struct FakeGame{ std::string place_error; size_t loads = 0; @@ -71,7 +71,7 @@ struct StartCase{ class Test_StoryStart : public UnitTest{ public: Test_StoryStart(StartCase test_case) - : UnitTest(std::format("Pokemon::AutoStoryShell - start: {}", test_case.name)) + : UnitTest(std::format("Pokemon::StoryRun - start: {}", test_case.name)) , m_case(std::move(test_case)) {} @@ -112,7 +112,7 @@ const StartCase START_CASES[] = { class Test_StoryReload : public UnitTest{ public: Test_StoryReload() - : UnitTest("Pokemon::AutoStoryShell - a retry reloads the save") + : UnitTest("Pokemon::StoryRun - a retry reloads the save") {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -134,7 +134,7 @@ class Test_StoryReload : public UnitTest{ class Test_StoryFailureLeavesGame : public UnitTest{ public: Test_StoryFailureLeavesGame() - : UnitTest("Pokemon::AutoStoryShell - a failed run leaves the game where it failed") + : UnitTest("Pokemon::StoryRun - a failed run leaves the game where it failed") {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -171,7 +171,7 @@ class Test_StoryFailureLeavesGame : public UnitTest{ class Test_StoryFinished : public UnitTest{ public: Test_StoryFinished() - : UnitTest("Pokemon::AutoStoryShell - a completed run is done through its last checkpoint") + : UnitTest("Pokemon::StoryRun - a completed run is done through its last checkpoint") {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -193,7 +193,7 @@ class Test_StoryFinished : public UnitTest{ class Test_StoryVerifyFailed : public UnitTest{ public: Test_StoryVerifyFailed() - : UnitTest("Pokemon::AutoStoryShell - an unverified checkpoint fails with its summary") + : UnitTest("Pokemon::StoryRun - an unverified checkpoint fails with its summary") {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -220,7 +220,7 @@ class Test_StoryVerifyFailed : public UnitTest{ } // namespace -void add_tests_AutoStoryShell(UnitTestDatabase& database){ +void add_tests_StoryRun(UnitTestDatabase& database){ for (const StartCase& test_case : START_CASES){ database.add(test_case); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.h new file mode 100644 index 0000000000..d1ac79aa1a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.h @@ -0,0 +1,23 @@ +/* AutoStory Story Run Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRun_Tests_H +#define PokemonAutomation_Pokemon_StoryRun_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the AutoStory story run's start, reload and finish. +void add_tests_StoryRun(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 76fcac9782..9c4fe82434 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1546,10 +1546,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_AutoStoryShell.cpp - Source/Pokemon/AutoStory/Pokemon_AutoStoryShell.h - Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.cpp - Source/Pokemon/AutoStory/Pokemon_AutoStoryShell_Tests.h + Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp + Source/Pokemon/AutoStory/Pokemon_StoryRun.h + Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.cpp Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp From 87a9d32a921ccb995ddb0fd9778136a4a13b4502 Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 13:49:18 -0800 Subject: [PATCH 04/20] AutoStory: start gate before a story run presses anything prepare_story_start() now logs the checkpoint that starts, then runs the game's preflight (video alive, controller ready, game not on HOME); one that fails returns precondition_failed with nothing pressed. A shared console reader lends the same preflight to BDSP and FRLG. story_first_save_allowed(): only a new game saves at its first checkpoint's start; after a load the save is there, and from the game as it is the place is unconfirmed (console B, 2026-11-11 13:32). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon_StoryConsolePreflight.cpp | 80 ++++++++ .../AutoStory/Pokemon_StoryConsolePreflight.h | 34 ++++ .../Pokemon/AutoStory/Pokemon_StoryRun.cpp | 17 ++ .../Pokemon/AutoStory/Pokemon_StoryRun.h | 35 ++-- .../AutoStory/Pokemon_StoryRun_Tests.cpp | 179 ++++++++++++++++-- .../AutoStory/Pokemon_StoryStartGate.cpp | 53 ++++++ .../AutoStory/Pokemon_StoryStartGate.h | 59 ++++++ SerialPrograms/cmake/SourceFiles.cmake | 4 + 8 files changed, 436 insertions(+), 25 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryConsolePreflight.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryConsolePreflight.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStartGate.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStartGate.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryConsolePreflight.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryConsolePreflight.cpp new file mode 100644 index 0000000000..e8f5d3004e --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryConsolePreflight.cpp @@ -0,0 +1,80 @@ +/* AutoStory Console Preflight + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTools/FloatPixel.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" +#include "Pokemon_StoryConsolePreflight.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +using namespace std::chrono_literals; + + +namespace{ + +// Color bars are seven flat vertical stripes of different colors. +constexpr size_t BAR_COUNT = 7; +// 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. +constexpr double BAR_MIN_DISTANCE = 60; +// A frame older than this is a stalled feed. +constexpr auto FRAME_MAX_AGE = 2000ms; + +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 ImageStats stats = image_stats(extract_box_reference(frame, stripe)); + if (stats.stddev.sum() > BAR_MAX_STDDEV){ + return false; + } + bars[c] = stats.average; + } + for (size_t c = 1; c < BAR_COUNT; c++){ + if (euclidean_distance(bars[c - 1], bars[c]) < BAR_MIN_DISTANCE){ + return false; + } + } + return true; +} + +} // namespace + +bool story_frame_shows_picture(const ImageViewRGB32& frame){ + if (!frame){ + return false; + } + if (is_black(frame)){ + return false; + } + return !shows_color_bars(frame); +} + +StoryPreflight read_story_preflight(NintendoSwitch::ConsoleHandle& console, NintendoSwitch::ProControllerContext& context){ + StoryPreflight preflight; + preflight.controller_ready = context.controller().is_ready(); + const VideoSnapshot snapshot = console.video().snapshot(); + const bool fresh = snapshot && current_time() - snapshot.timestamp < FRAME_MAX_AGE; + preflight.video_alive = fresh && story_frame_shows_picture(snapshot); + preflight.game_running = preflight.video_alive + && !NintendoSwitch::HomeMenuDetector(console, COLOR_RED).detect(snapshot); + return preflight; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryConsolePreflight.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryConsolePreflight.h new file mode 100644 index 0000000000..3fc9e87404 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryConsolePreflight.h @@ -0,0 +1,34 @@ +/* AutoStory Console Preflight + * + * From: https://github.com/PokemonAutomation/ + * + * The story run's preflight (StoryPreflight) read off a Switch console: + * the same for every game, so BDSP and FRLG lend the same reader. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryConsolePreflight_H +#define PokemonAutomation_Pokemon_StoryConsolePreflight_H + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "Pokemon_StoryRun.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Whether `frame` shows a picture: not empty, not all black, and not the +// capture card's color bars (no signal from the Switch). +bool story_frame_shows_picture(const ImageViewRGB32& frame); + +// Reads the console: a frame newer than two seconds that shows a picture, +// the controller ready, and that frame not the HOME menu. Presses nothing. +StoryPreflight read_story_preflight(NintendoSwitch::ConsoleHandle& console, NintendoSwitch::ProControllerContext& context); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp index 7e7ff7c736..aa9434bec7 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp @@ -37,6 +37,18 @@ std::string story_verify_summary(std::string_view checkpoint, const VerifyPolicy ); } +Outcome run_story_preflight(StoryGameHooks& game){ + if (!game.preflight){ + log_line("[Story] preflight: not checked: the game has no preflight", game); + return outcome_ok(); + } + const Outcome outcome = check_story_preflight(game.preflight()); + if (!outcome.succeeded()){ + log_line(std::format("[Story] preflight failed, nothing pressed: {}", outcome.detail), game); + } + return outcome; +} + Outcome load_story_save(std::string_view reason, StoryGameHooks& game, RunState& state){ log_line(std::format("[Story] {}: loading the save", reason), game); Outcome outcome = game.load_save(state); @@ -58,6 +70,11 @@ Outcome load_story_save(std::string_view reason, StoryGameHooks& game, RunState& } // namespace Outcome prepare_story_start(std::string_view checkpoint, StoryStart start, StoryGameHooks& game, RunState& state){ + log_line(std::format("[Story] start: checkpoint {}, from {}", checkpoint, story_start_name(start)), game); + const Outcome preflight = run_story_preflight(game); + if (!preflight.succeeded()){ + return preflight; + } switch (start){ case StoryStart::NEW_GAME: log_line(std::format("[Story] {}: starts a new game, no save to load", checkpoint), game); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h index cfbeca7696..630ab97165 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h @@ -8,9 +8,19 @@ * A game lends only what really differs: how it loads its save (BDSP * resets from HOME, FRLG soft-resets) and how it checks where the save is. * - * Two rules hold for every game: + * These rules hold for every game: + * - Before anything is pressed, the game's preflight must see the video + * alive, the controller ready and the game running (not HOME). One + * that fails is the setup's failure, not the story's: nothing is + * touched. * - A run that starts at a checkpoint with a save loads that save first, - * so it never walks from wherever the game was left. + * so it never walks from wherever the game was left. There is no + * "just loaded" shortcut: a load or place check that fails stops the + * 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). * - 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. * @@ -26,23 +36,17 @@ #include "Pokemon_StoryCheckpointTypes.h" #include "Pokemon_StoryOutcome.h" #include "Pokemon_StorySegments.h" +#include "Pokemon_StoryStartGate.h" namespace PokemonAutomation{ namespace Pokemon{ -// How the game reaches the start checkpoint. -enum class StoryStart{ - // A new game from the title screen: there is no save. - NEW_GAME, - // The game as another program left it: nothing is loaded. - LIVE, - // The checkpoint's save, loaded first. - FROM_SAVE, -}; - // What a game lends the story run. struct StoryGameHooks{ + // Reads the console before anything else (see StoryPreflight). Without + // it the run logs that nothing was checked. + MoveOnlyFunction preflight; // Loads the last save: the game reset (from HOME or soft) and back in // the overworld. A failed Outcome says why. Act load_save; @@ -63,8 +67,11 @@ struct StoryGameHooks{ inline constexpr std::string_view STORY_LEFT_WHERE_FAILED = "AutoStory failed: the game stays where it failed."; // Gets the game to where checkpoint `checkpoint` starts, as `start` says. -// FROM_SAVE always loads the save (logging "[Story] 00.04b: loading the -// save"), checks its place and rereads it, and sets the "save_loaded" flag. +// First logs the checkpoint starting ("[Story] start: checkpoint 00.04b, +// from its save") and runs the game's preflight; one that fails returns +// STORY_PRECONDITION_FAILED with nothing pressed. FROM_SAVE then always +// loads the save (logging "[Story] 00.04b: loading the save"), checks its +// place and rereads it, and sets the "save_loaded" flag. Outcome prepare_story_start(std::string_view checkpoint, StoryStart start, StoryGameHooks& game, RunState& state); // The runner's hooks: reload is load_story_save(); save, log and status diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp index dd5ecc7a33..36288a0154 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp @@ -19,6 +19,7 @@ namespace{ // A game that records what the story run asked of it. struct FakeGame{ + StoryPreflight preflight{.video_alive = true, .controller_ready = true, .game_running = true}; std::string place_error; size_t loads = 0; size_t rereads = 0; @@ -27,6 +28,9 @@ struct FakeGame{ StoryGameHooks hooks(){ StoryGameHooks game; + game.preflight = [this]{ + return preflight; + }; game.load_save = [this](RunState&){ loads++; return outcome_ok(); @@ -58,39 +62,70 @@ struct FakeGame{ }; // A start as the program asks for it, and what the game must have done. -struct StartCase{ +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; +}; + +constexpr StoryPreflight READY{.video_alive = true, .controller_ready = true, .game_running = true}; +constexpr StoryPreflight ON_HOME{.video_alive = true, .controller_ready = true, .game_running = false}; +constexpr StoryPreflight NO_VIDEO{.video_alive = false, .controller_ready = true, .game_running = true}; +constexpr StoryPreflight NO_CONTROLLER{.video_alive = true, .controller_ready = false, .game_running = true}; + +std::string_view start_name(StoryStart start){ + switch (start){ + case StoryStart::NEW_GAME: + return "a new game"; + case StoryStart::LIVE: + return "the game as it is"; + case StoryStart::FROM_SAVE: + return "its save"; + } + return "?"; +} class Test_StoryStart : public UnitTest{ public: Test_StoryStart(StartCase test_case) - : UnitTest(std::format("Pokemon::StoryRun - start: {}", test_case.name)) + : UnitTest(std::format("Pokemon::StoryRun - start: {}", test_case.input.name)) , m_case(std::move(test_case)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ FakeGame fake; - fake.place_error = m_case.place_error; + fake.place_error = m_case.input.place_error; + fake.preflight = m_case.input.preflight; StoryGameHooks game = fake.hooks(); RunState state; - const Outcome outcome = prepare_story_start("00.04b", m_case.start, game, state); + const Outcome outcome = prepare_story_start("00.04b", m_case.input.start, game, state); const bool save_loaded = state.flags.contains("save_loaded"); - if (outcome.succeeded() != m_case.succeeds || fake.loads != m_case.loads - || fake.rereads != m_case.rereads || save_loaded != m_case.save_loaded + if (outcome.succeeded() != m_case.expectation.succeeds || fake.loads != m_case.expectation.loads + || fake.rereads != m_case.expectation.rereads || save_loaded != m_case.expectation.save_loaded ){ return std::format( "Expected ok={} loads={} rereads={} save_loaded={}, got {} {} {} {} ({})", - m_case.succeeds, m_case.loads, m_case.rereads, m_case.save_loaded, + m_case.expectation.succeeds, m_case.expectation.loads, m_case.expectation.rereads, m_case.expectation.save_loaded, outcome.succeeded(), fake.loads, fake.rereads, save_loaded, to_string(outcome) ); } + if (!fake.logged(std::format("[Story] start: checkpoint 00.04b, from {}", start_name(m_case.input.start)))){ + return "Expected the line naming the checkpoint that starts"; + } + if (!m_case.input.preflight.game_running && outcome.failure != STORY_PRECONDITION_FAILED){ + return std::format("Expected {}, got {}", STORY_PRECONDITION_FAILED, to_string(outcome)); + } return true; } @@ -101,10 +136,126 @@ 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 checkpoint with a save loads it first", StoryStart::FROM_SAVE, "", true, 1, 1, true}, - {"a save in the wrong place fails before rereading it", StoryStart::FROM_SAVE, "The save is in Pewter City.", false, 1, 0, false}, - {"a new game loads nothing", StoryStart::NEW_GAME, "", true, 0, 0, false}, - {"a live start loads nothing", StoryStart::LIVE, "", true, 0, 0, false}, + { + .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}, + }, + { + .input = {.name = "a save in the wrong place fails before rereading it", .start = StoryStart::FROM_SAVE, .place_error = "The save is in Pewter City.", .preflight = READY}, + .expectation = {.succeeds = false, .loads = 1, .rereads = 0, .save_loaded = false}, + }, + { + .input = {.name = "a new game loads nothing", .start = StoryStart::NEW_GAME, .place_error = "", .preflight = READY}, + .expectation = {.succeeds = true, .loads = 0, .rereads = 0, .save_loaded = false}, + }, + { + .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. + { + .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}, + }, + { + .input = {.name = "the HOME menu stops a live start", .start = StoryStart::LIVE, .place_error = "", .preflight = ON_HOME}, + .expectation = {.succeeds = false, .loads = 0, .rereads = 0, .save_loaded = false}, + }, + { + .input = {.name = "dead video stops the run before the load", .start = StoryStart::FROM_SAVE, .place_error = "", .preflight = NO_VIDEO}, + .expectation = {.succeeds = false, .loads = 0, .rereads = 0, .save_loaded = false}, + }, + { + .input = {.name = "a controller not ready stops the run before the load", .start = StoryStart::FROM_SAVE, .place_error = "", .preflight = NO_CONTROLLER}, + .expectation = {.succeeds = false, .loads = 0, .rereads = 0, .save_loaded = false}, + }, +}; + + +// 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; +}; + +class Test_StoryPreflight : public UnitTest{ +public: + Test_StoryPreflight(PreflightCase test_case) + : UnitTest(std::format("Pokemon::StoryRun - preflight: {}", test_case.input.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string got = to_string(check_story_preflight(m_case.input.preflight)); + if (got != m_case.expectation.outcome){ + return std::format("Expected \"{}\", got \"{}\"", m_case.expectation.outcome, got); + } + return true; + } + +private: + const PreflightCase m_case; +}; + +const PreflightCase PREFLIGHT_CASES[] = { + {.input = {.name = "a ready console passes", .preflight = READY}, .expectation = {.outcome = ""}}, + { + .input = {.name = "the HOME menu", .preflight = ON_HOME}, + .expectation = {.outcome = "precondition_failed: the game is not running"}, + }, + { + .input = {.name = "every check failed", .preflight = StoryPreflight{}}, + .expectation = {.outcome = "precondition_failed: no live video; the controller is not ready; the game is not running"}, + }, +}; + + +// 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; +}; + +class Test_StoryFirstSave : public UnitTest{ +public: + Test_StoryFirstSave(FirstSaveCase test_case) + : UnitTest(std::format("Pokemon::StoryRun - first save: {}", start_name(test_case.input.start))) + , m_case(test_case) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + if (story_first_save_allowed(m_case.input.start) != m_case.expectation.saves){ + return std::format("Expected saves={} from {}", m_case.expectation.saves, start_name(m_case.input.start)); + } + return true; + } + +private: + const FirstSaveCase m_case; +}; + +const FirstSaveCase FIRST_SAVE_CASES[] = { + {.input = {.start = StoryStart::NEW_GAME}, .expectation = {.saves = true}}, + {.input = {.start = StoryStart::FROM_SAVE}, .expectation = {.saves = false}}, + {.input = {.start = StoryStart::LIVE}, .expectation = {.saves = false}}, }; @@ -224,6 +375,12 @@ void add_tests_StoryRun(UnitTestDatabase& database){ for (const StartCase& test_case : START_CASES){ database.add(test_case); } + for (const PreflightCase& test_case : PREFLIGHT_CASES){ + database.add(test_case); + } + for (const FirstSaveCase& test_case : FIRST_SAVE_CASES){ + database.add(test_case); + } database.add(); database.add(); database.add(); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStartGate.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStartGate.cpp new file mode 100644 index 0000000000..f45cc85264 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStartGate.cpp @@ -0,0 +1,53 @@ +/* AutoStory Story Start Gate + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryStartGate.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +Outcome check_story_preflight(const StoryPreflight& preflight){ + std::string failed; + auto add = [&failed](bool ok, std::string_view what){ + if (ok){ + return; + } + if (!failed.empty()){ + failed += "; "; + } + failed += what; + }; + add(preflight.video_alive, "no live video"); + add(preflight.controller_ready, "the controller is not ready"); + add(preflight.game_running, "the game is not running"); + if (failed.empty()){ + return outcome_ok(); + } + return outcome_failed(std::string(STORY_PRECONDITION_FAILED), failed); +} + +bool story_first_save_allowed(StoryStart start){ + return start == StoryStart::NEW_GAME; +} + +std::string_view story_start_name(StoryStart start){ + switch (start){ + case StoryStart::NEW_GAME: + return "a new game"; + case StoryStart::LIVE: + return "the game as it is"; + case StoryStart::FROM_SAVE: + return "its save"; + } + return "?"; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStartGate.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStartGate.h new file mode 100644 index 0000000000..37304e346d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStartGate.h @@ -0,0 +1,59 @@ +/* AutoStory Story Start Gate + * + * From: https://github.com/PokemonAutomation/ + * + * How a story run may start: the ways to reach the start checkpoint, the + * console checks before anything is pressed, and whether the first + * checkpoint may save at its start. The rules are in Pokemon_StoryRun.h. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStartGate_H +#define PokemonAutomation_Pokemon_StoryStartGate_H + +#include +#include "Pokemon_StoryOutcome.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How the game reaches the start checkpoint. +enum class StoryStart{ + // A new game from the title screen: there is no save. + NEW_GAME, + // The game as another program left it: nothing is loaded. + LIVE, + // The checkpoint's save, loaded first. + FROM_SAVE, +}; + +// What a game reads off the console before a run presses anything. +struct StoryPreflight{ + // Frames are arriving and show a picture (not black, not color bars). + bool video_alive = false; + bool controller_ready = false; + // The game is on screen, not the Switch's HOME menu. + bool game_running = false; +}; + +// The failure of a preflight that failed: the console or its setup, not +// the story. Nothing answers it with a reload or a recovery. +inline constexpr std::string_view STORY_PRECONDITION_FAILED = "precondition_failed"; + +// outcome_ok() when `preflight` passed, else STORY_PRECONDITION_FAILED +// naming each check that failed. +Outcome check_story_preflight(const StoryPreflight& preflight); + +// Whether the first checkpoint's own save at its start may run, for a run +// that starts as `start` says: only a new game's (see Pokemon_StoryRun.h). +bool story_first_save_allowed(StoryStart start); + +// "its save", "a new game", "the game as it is": for the start line. +std::string_view story_start_name(StoryStart start); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 9c4fe82434..4d2b48719b 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1546,10 +1546,14 @@ 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_StoryConsolePreflight.cpp + Source/Pokemon/AutoStory/Pokemon_StoryConsolePreflight.h Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp Source/Pokemon/AutoStory/Pokemon_StoryRun.h Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.h + Source/Pokemon/AutoStory/Pokemon_StoryStartGate.cpp + Source/Pokemon/AutoStory/Pokemon_StoryStartGate.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.cpp Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp From a3b1c8e3c91006bf6635a24e7ce79488418a1167 Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 14:48:38 -0800 Subject: [PATCH 05/20] AutoStory: Fold the start gate into the preflight hook StoryStartGate.h mixed the start enum, the preflight reading, its failure code and two start rules. StoryPreflight is now the one concept in its own header: the preflight hook's reading, its check() and its FAILURE code. StoryStart and story_first_save_allowed() go back to Pokemon_StoryRun.h with the start sequence; story_start_name() is internal to it. Behavior is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StoryPreflight.cpp | 37 ++++++++++++ .../AutoStory/Pokemon_StoryPreflight.h | 42 +++++++++++++ .../Pokemon/AutoStory/Pokemon_StoryRun.cpp | 19 +++++- .../Pokemon/AutoStory/Pokemon_StoryRun.h | 18 +++++- .../AutoStory/Pokemon_StoryRun_Tests.cpp | 6 +- .../AutoStory/Pokemon_StoryStartGate.cpp | 53 ----------------- .../AutoStory/Pokemon_StoryStartGate.h | 59 ------------------- SerialPrograms/cmake/SourceFiles.cmake | 4 +- 8 files changed, 118 insertions(+), 120 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.h delete mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStartGate.cpp delete mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStartGate.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp new file mode 100644 index 0000000000..e579d4888d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp @@ -0,0 +1,37 @@ +/* AutoStory Story Preflight + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryPreflight.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +Outcome StoryPreflight::check() const{ + std::string failed; + auto add = [&failed](bool ok, std::string_view what){ + if (ok){ + return; + } + if (!failed.empty()){ + failed += "; "; + } + failed += what; + }; + add(video_alive, "no live video"); + add(controller_ready, "the controller is not ready"); + add(game_running, "the game is not running"); + if (failed.empty()){ + return outcome_ok(); + } + return outcome_failed(std::string(FAILURE), failed); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.h new file mode 100644 index 0000000000..0c8a16431a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.h @@ -0,0 +1,42 @@ +/* AutoStory Story Preflight + * + * From: https://github.com/PokemonAutomation/ + * + * What the story run's preflight hook (StoryGameHooks::preflight) reads + * off the console before anything is pressed, and its verdict. The start + * sequence that runs it is in Pokemon_StoryRun.h. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryPreflight_H +#define PokemonAutomation_Pokemon_StoryPreflight_H + +#include +#include "Pokemon_StoryOutcome.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What a game reads off the console before a run presses anything. +struct StoryPreflight{ + // The failure of a preflight that failed: the console or its setup, + // not the story. Nothing answers it with a reload or a recovery. + static constexpr std::string_view FAILURE = "precondition_failed"; + + // Frames are arriving and show a picture (not black, not color bars). + bool video_alive = false; + bool controller_ready = false; + // The game is on screen, not the Switch's HOME menu. + bool game_running = false; + + // outcome_ok() when every check passed, else FAILURE naming each + // check that failed. + Outcome check() const; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp index aa9434bec7..261ee2915b 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp @@ -15,6 +15,19 @@ namespace Pokemon{ namespace{ +// "its save", "a new game", "the game as it is": for the start line. +std::string_view story_start_name(StoryStart start){ + switch (start){ + case StoryStart::NEW_GAME: + return "a new game"; + case StoryStart::LIVE: + return "the game as it is"; + case StoryStart::FROM_SAVE: + return "its save"; + } + return "?"; +} + void log_line(const std::string& line, StoryGameHooks& game){ if (game.log){ game.log(line); @@ -42,7 +55,7 @@ Outcome run_story_preflight(StoryGameHooks& game){ log_line("[Story] preflight: not checked: the game has no preflight", game); return outcome_ok(); } - const Outcome outcome = check_story_preflight(game.preflight()); + const Outcome outcome = game.preflight().check(); if (!outcome.succeeded()){ log_line(std::format("[Story] preflight failed, nothing pressed: {}", outcome.detail), game); } @@ -69,6 +82,10 @@ Outcome load_story_save(std::string_view reason, StoryGameHooks& game, RunState& } // namespace +bool story_first_save_allowed(StoryStart start){ + return start == StoryStart::NEW_GAME; +} + Outcome prepare_story_start(std::string_view checkpoint, StoryStart start, StoryGameHooks& game, RunState& state){ log_line(std::format("[Story] start: checkpoint {}, from {}", checkpoint, story_start_name(start)), game); const Outcome preflight = run_story_preflight(game); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h index 630ab97165..8b62c4da79 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h @@ -36,12 +36,22 @@ #include "Pokemon_StoryCheckpointTypes.h" #include "Pokemon_StoryOutcome.h" #include "Pokemon_StorySegments.h" -#include "Pokemon_StoryStartGate.h" +#include "Pokemon_StoryPreflight.h" namespace PokemonAutomation{ namespace Pokemon{ +// How the game reaches the start checkpoint. +enum class StoryStart{ + // A new game from the title screen: there is no save. + NEW_GAME, + // The game as another program left it: nothing is loaded. + LIVE, + // The checkpoint's save, loaded first. + FROM_SAVE, +}; + // What a game lends the story run. struct StoryGameHooks{ // Reads the console before anything else (see StoryPreflight). Without @@ -69,11 +79,15 @@ inline constexpr std::string_view STORY_LEFT_WHERE_FAILED = "AutoStory failed: t // Gets the game to where checkpoint `checkpoint` starts, as `start` says. // First logs the checkpoint starting ("[Story] start: checkpoint 00.04b, // from its save") and runs the game's preflight; one that fails returns -// STORY_PRECONDITION_FAILED with nothing pressed. FROM_SAVE then always +// StoryPreflight::FAILURE with nothing pressed. FROM_SAVE then always // loads the save (logging "[Story] 00.04b: loading the save"), checks its // place and rereads it, and sets the "save_loaded" flag. Outcome prepare_story_start(std::string_view checkpoint, StoryStart start, StoryGameHooks& game, RunState& state); +// Whether the first checkpoint's own save at its start may run, for a run +// that starts as `start` says: only a new game's (see the rules above). +bool story_first_save_allowed(StoryStart start); + // The runner's hooks: reload is load_story_save(); save, log and status // are the game's. `game` must outlive them. SegmentHooks story_segment_hooks(StoryGameHooks& game); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp index 36288a0154..a45f39b5a4 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp @@ -123,8 +123,8 @@ class Test_StoryStart : public UnitTest{ if (!fake.logged(std::format("[Story] start: checkpoint 00.04b, from {}", start_name(m_case.input.start)))){ return "Expected the line naming the checkpoint that starts"; } - if (!m_case.input.preflight.game_running && outcome.failure != STORY_PRECONDITION_FAILED){ - return std::format("Expected {}, got {}", STORY_PRECONDITION_FAILED, to_string(outcome)); + if (!m_case.input.preflight.game_running && outcome.failure != StoryPreflight::FAILURE){ + return std::format("Expected {}, got {}", StoryPreflight::FAILURE, to_string(outcome)); } return true; } @@ -196,7 +196,7 @@ class Test_StoryPreflight : public UnitTest{ {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const std::string got = to_string(check_story_preflight(m_case.input.preflight)); + const std::string got = to_string(m_case.input.preflight.check()); if (got != m_case.expectation.outcome){ return std::format("Expected \"{}\", got \"{}\"", m_case.expectation.outcome, got); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStartGate.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStartGate.cpp deleted file mode 100644 index f45cc85264..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStartGate.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* AutoStory Story Start Gate - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Pokemon_StoryStartGate.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -Outcome check_story_preflight(const StoryPreflight& preflight){ - std::string failed; - auto add = [&failed](bool ok, std::string_view what){ - if (ok){ - return; - } - if (!failed.empty()){ - failed += "; "; - } - failed += what; - }; - add(preflight.video_alive, "no live video"); - add(preflight.controller_ready, "the controller is not ready"); - add(preflight.game_running, "the game is not running"); - if (failed.empty()){ - return outcome_ok(); - } - return outcome_failed(std::string(STORY_PRECONDITION_FAILED), failed); -} - -bool story_first_save_allowed(StoryStart start){ - return start == StoryStart::NEW_GAME; -} - -std::string_view story_start_name(StoryStart start){ - switch (start){ - case StoryStart::NEW_GAME: - return "a new game"; - case StoryStart::LIVE: - return "the game as it is"; - case StoryStart::FROM_SAVE: - return "its save"; - } - return "?"; -} - - - -} // namespace Pokemon -} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStartGate.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStartGate.h deleted file mode 100644 index 37304e346d..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStartGate.h +++ /dev/null @@ -1,59 +0,0 @@ -/* AutoStory Story Start Gate - * - * From: https://github.com/PokemonAutomation/ - * - * How a story run may start: the ways to reach the start checkpoint, the - * console checks before anything is pressed, and whether the first - * checkpoint may save at its start. The rules are in Pokemon_StoryRun.h. - * - */ - -#ifndef PokemonAutomation_Pokemon_StoryStartGate_H -#define PokemonAutomation_Pokemon_StoryStartGate_H - -#include -#include "Pokemon_StoryOutcome.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -// How the game reaches the start checkpoint. -enum class StoryStart{ - // A new game from the title screen: there is no save. - NEW_GAME, - // The game as another program left it: nothing is loaded. - LIVE, - // The checkpoint's save, loaded first. - FROM_SAVE, -}; - -// What a game reads off the console before a run presses anything. -struct StoryPreflight{ - // Frames are arriving and show a picture (not black, not color bars). - bool video_alive = false; - bool controller_ready = false; - // The game is on screen, not the Switch's HOME menu. - bool game_running = false; -}; - -// The failure of a preflight that failed: the console or its setup, not -// the story. Nothing answers it with a reload or a recovery. -inline constexpr std::string_view STORY_PRECONDITION_FAILED = "precondition_failed"; - -// outcome_ok() when `preflight` passed, else STORY_PRECONDITION_FAILED -// naming each check that failed. -Outcome check_story_preflight(const StoryPreflight& preflight); - -// Whether the first checkpoint's own save at its start may run, for a run -// that starts as `start` says: only a new game's (see Pokemon_StoryRun.h). -bool story_first_save_allowed(StoryStart start); - -// "its save", "a new game", "the game as it is": for the start line. -std::string_view story_start_name(StoryStart start); - - - -} // namespace Pokemon -} // namespace PokemonAutomation -#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 4d2b48719b..f82cf07c03 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1552,8 +1552,8 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_StoryRun.h Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.h - Source/Pokemon/AutoStory/Pokemon_StoryStartGate.cpp - Source/Pokemon/AutoStory/Pokemon_StoryStartGate.h + Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp + Source/Pokemon/AutoStory/Pokemon_StoryPreflight.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.cpp Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp From 20e625bb1d8a58f63415a8988c4434ce1fda4c3f Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 14:50:07 -0800 Subject: [PATCH 06/20] AutoStory: StoryStart and its save rule in their own header Keeps Pokemon_StoryRun.h at its symbol limit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon/AutoStory/Pokemon_StoryRun.cpp | 4 -- .../Pokemon/AutoStory/Pokemon_StoryRun.h | 15 +------- .../Pokemon/AutoStory/Pokemon_StoryStart.h | 38 +++++++++++++++++++ SerialPrograms/cmake/SourceFiles.cmake | 1 + 4 files changed, 40 insertions(+), 18 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStart.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp index 261ee2915b..01f939df17 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp @@ -82,10 +82,6 @@ Outcome load_story_save(std::string_view reason, StoryGameHooks& game, RunState& } // namespace -bool story_first_save_allowed(StoryStart start){ - return start == StoryStart::NEW_GAME; -} - Outcome prepare_story_start(std::string_view checkpoint, StoryStart start, StoryGameHooks& game, RunState& state){ log_line(std::format("[Story] start: checkpoint {}, from {}", checkpoint, story_start_name(start)), game); const Outcome preflight = run_story_preflight(game); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h index 8b62c4da79..8a8a749bf8 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h @@ -37,21 +37,12 @@ #include "Pokemon_StoryOutcome.h" #include "Pokemon_StorySegments.h" #include "Pokemon_StoryPreflight.h" +#include "Pokemon_StoryStart.h" namespace PokemonAutomation{ namespace Pokemon{ -// How the game reaches the start checkpoint. -enum class StoryStart{ - // A new game from the title screen: there is no save. - NEW_GAME, - // The game as another program left it: nothing is loaded. - LIVE, - // The checkpoint's save, loaded first. - FROM_SAVE, -}; - // What a game lends the story run. struct StoryGameHooks{ // Reads the console before anything else (see StoryPreflight). Without @@ -84,10 +75,6 @@ inline constexpr std::string_view STORY_LEFT_WHERE_FAILED = "AutoStory failed: t // place and rereads it, and sets the "save_loaded" flag. Outcome prepare_story_start(std::string_view checkpoint, StoryStart start, StoryGameHooks& game, RunState& state); -// Whether the first checkpoint's own save at its start may run, for a run -// that starts as `start` says: only a new game's (see the rules above). -bool story_first_save_allowed(StoryStart start); - // The runner's hooks: reload is load_story_save(); save, log and status // are the game's. `game` must outlive them. SegmentHooks story_segment_hooks(StoryGameHooks& game); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStart.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStart.h new file mode 100644 index 0000000000..33ba6d9489 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStart.h @@ -0,0 +1,38 @@ +/* AutoStory Story Start + * + * From: https://github.com/PokemonAutomation/ + * + * How a story run reaches its start checkpoint, and what that allows. + * The start sequence itself is prepare_story_start() in Pokemon_StoryRun.h. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStart_H +#define PokemonAutomation_Pokemon_StoryStart_H + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How the game reaches the start checkpoint. +enum class StoryStart{ + // A new game from the title screen: there is no save. + NEW_GAME, + // The game as another program left it: nothing is loaded. + LIVE, + // The checkpoint's save, loaded first. + FROM_SAVE, +}; + +// Whether the first checkpoint's own save at its start may run: only a +// new game's. After a load the save is already there, and from the game +// as it is the place is unconfirmed. +inline bool story_first_save_allowed(StoryStart start){ + return start == StoryStart::NEW_GAME; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index f82cf07c03..4f96ea129b 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1607,6 +1607,7 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_StorySegments.h Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.h + Source/Pokemon/AutoStory/Pokemon_StoryStart.h Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp From fb95f02d4a43336b4e010506111e553302b7646a Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 14:56:35 -0800 Subject: [PATCH 07/20] AutoStory: StoryStart under Types; one StoryPreflight with read() StoryStart moves to Types/Pokemon_StoryStart.h. The console reader joins StoryPreflight as StoryPreflight::read(); the picture check is internal. Behavior unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon_StoryConsolePreflight.cpp | 80 ------------------- .../AutoStory/Pokemon_StoryConsolePreflight.h | 34 -------- .../AutoStory/Pokemon_StoryPreflight.cpp | 65 +++++++++++++++ .../AutoStory/Pokemon_StoryPreflight.h | 10 ++- .../Pokemon/AutoStory/Pokemon_StoryRun.h | 2 +- .../{ => Types}/Pokemon_StoryStart.h | 0 SerialPrograms/cmake/SourceFiles.cmake | 4 +- 7 files changed, 76 insertions(+), 119 deletions(-) delete mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryConsolePreflight.cpp delete mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryConsolePreflight.h rename SerialPrograms/Source/Pokemon/AutoStory/{ => Types}/Pokemon_StoryStart.h (100%) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryConsolePreflight.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryConsolePreflight.cpp deleted file mode 100644 index e8f5d3004e..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryConsolePreflight.cpp +++ /dev/null @@ -1,80 +0,0 @@ -/* AutoStory Console Preflight - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Time.h" -#include "CommonFramework/ImageTools/FloatPixel.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" -#include "Pokemon_StoryConsolePreflight.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - -using namespace std::chrono_literals; - - -namespace{ - -// Color bars are seven flat vertical stripes of different colors. -constexpr size_t BAR_COUNT = 7; -// 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. -constexpr double BAR_MIN_DISTANCE = 60; -// A frame older than this is a stalled feed. -constexpr auto FRAME_MAX_AGE = 2000ms; - -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 ImageStats stats = image_stats(extract_box_reference(frame, stripe)); - if (stats.stddev.sum() > BAR_MAX_STDDEV){ - return false; - } - bars[c] = stats.average; - } - for (size_t c = 1; c < BAR_COUNT; c++){ - if (euclidean_distance(bars[c - 1], bars[c]) < BAR_MIN_DISTANCE){ - return false; - } - } - return true; -} - -} // namespace - -bool story_frame_shows_picture(const ImageViewRGB32& frame){ - if (!frame){ - return false; - } - if (is_black(frame)){ - return false; - } - return !shows_color_bars(frame); -} - -StoryPreflight read_story_preflight(NintendoSwitch::ConsoleHandle& console, NintendoSwitch::ProControllerContext& context){ - StoryPreflight preflight; - preflight.controller_ready = context.controller().is_ready(); - const VideoSnapshot snapshot = console.video().snapshot(); - const bool fresh = snapshot && current_time() - snapshot.timestamp < FRAME_MAX_AGE; - preflight.video_alive = fresh && story_frame_shows_picture(snapshot); - preflight.game_running = preflight.video_alive - && !NintendoSwitch::HomeMenuDetector(console, COLOR_RED).detect(snapshot); - return preflight; -} - - - -} // namespace Pokemon -} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryConsolePreflight.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryConsolePreflight.h deleted file mode 100644 index 3fc9e87404..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryConsolePreflight.h +++ /dev/null @@ -1,34 +0,0 @@ -/* AutoStory Console Preflight - * - * From: https://github.com/PokemonAutomation/ - * - * The story run's preflight (StoryPreflight) read off a Switch console: - * the same for every game, so BDSP and FRLG lend the same reader. - * - */ - -#ifndef PokemonAutomation_Pokemon_StoryConsolePreflight_H -#define PokemonAutomation_Pokemon_StoryConsolePreflight_H - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" -#include "Pokemon_StoryRun.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -// Whether `frame` shows a picture: not empty, not all black, and not the -// capture card's color bars (no signal from the Switch). -bool story_frame_shows_picture(const ImageViewRGB32& frame); - -// Reads the console: a frame newer than two seconds that shows a picture, -// the controller ready, and that frame not the HOME menu. Presses nothing. -StoryPreflight read_story_preflight(NintendoSwitch::ConsoleHandle& console, NintendoSwitch::ProControllerContext& context); - - - -} // namespace Pokemon -} // namespace PokemonAutomation -#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp index e579d4888d..2b56c6b435 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp @@ -4,12 +4,77 @@ * */ +#include +#include #include +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTools/FloatPixel.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" #include "Pokemon_StoryPreflight.h" namespace PokemonAutomation{ namespace Pokemon{ +using namespace std::chrono_literals; + + +namespace{ + +// Color bars are seven flat vertical stripes of different colors. +constexpr size_t BAR_COUNT = 7; +// 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. +constexpr double BAR_MIN_DISTANCE = 60; +// A frame older than this is a stalled feed. +constexpr auto FRAME_MAX_AGE = 2000ms; + +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 ImageStats stats = image_stats(extract_box_reference(frame, stripe)); + if (stats.stddev.sum() > BAR_MAX_STDDEV){ + return false; + } + bars[c] = stats.average; + } + for (size_t c = 1; c < BAR_COUNT; c++){ + if (euclidean_distance(bars[c - 1], bars[c]) < BAR_MIN_DISTANCE){ + return false; + } + } + return true; +} + +bool frame_shows_picture(const ImageViewRGB32& frame){ + if (!frame){ + return false; + } + if (is_black(frame)){ + return false; + } + return !shows_color_bars(frame); +} + +} // namespace + +StoryPreflight StoryPreflight::read(NintendoSwitch::ConsoleHandle& console, NintendoSwitch::ProControllerContext& context){ + StoryPreflight preflight; + preflight.controller_ready = context.controller().is_ready(); + const VideoSnapshot snapshot = console.video().snapshot(); + const bool fresh = snapshot && current_time() - snapshot.timestamp < FRAME_MAX_AGE; + preflight.video_alive = fresh && frame_shows_picture(snapshot); + preflight.game_running = preflight.video_alive + && !NintendoSwitch::HomeMenuDetector(console, COLOR_RED).detect(snapshot); + return preflight; +} + Outcome StoryPreflight::check() const{ std::string failed; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.h index 0c8a16431a..d9aa65f158 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.h @@ -3,7 +3,8 @@ * From: https://github.com/PokemonAutomation/ * * What the story run's preflight hook (StoryGameHooks::preflight) reads - * off the console before anything is pressed, and its verdict. The start + * off the console before anything is pressed, and its verdict. The same + * for every game, so BDSP and FRLG lend the same reader. The start * sequence that runs it is in Pokemon_StoryRun.h. * */ @@ -12,6 +13,8 @@ #define PokemonAutomation_Pokemon_StoryPreflight_H #include +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" #include "Pokemon_StoryOutcome.h" namespace PokemonAutomation{ @@ -33,6 +36,11 @@ struct StoryPreflight{ // outcome_ok() when every check passed, else FAILURE naming each // check that failed. Outcome check() const; + + // Reads the console: a frame newer than two seconds that shows a + // picture (not black, not the capture card's color bars), the + // controller ready, and that frame not the HOME menu. Presses nothing. + static StoryPreflight read(NintendoSwitch::ConsoleHandle& console, NintendoSwitch::ProControllerContext& context); }; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h index 8a8a749bf8..9215d63a1c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h @@ -37,7 +37,7 @@ #include "Pokemon_StoryOutcome.h" #include "Pokemon_StorySegments.h" #include "Pokemon_StoryPreflight.h" -#include "Pokemon_StoryStart.h" +#include "Types/Pokemon_StoryStart.h" namespace PokemonAutomation{ namespace Pokemon{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStart.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStart.h similarity index 100% rename from SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStart.h rename to SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStart.h diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 4f96ea129b..cd4fc4c225 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1546,8 +1546,6 @@ 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_StoryConsolePreflight.cpp - Source/Pokemon/AutoStory/Pokemon_StoryConsolePreflight.h Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp Source/Pokemon/AutoStory/Pokemon_StoryRun.h Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp @@ -1607,7 +1605,6 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_StorySegments.h Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.h - Source/Pokemon/AutoStory/Pokemon_StoryStart.h Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp @@ -1637,6 +1634,7 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.h Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.cpp Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryStart.h Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h From 1345efc2512b11175c92625d386444023f1ddfec Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 19:37:42 -0800 Subject: [PATCH 08/20] Pokemon Navigation: one movement mechanics table per game Tap lengths, tile times per gait and axis, start delay and how open legs are pressed (BDSP taps, FRLG timed holds on foot), with an entry for BDSP and one for FRLG and a check of each. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../ComputerPrograms_UnitTestRunner.cpp | 2 + .../Navigation/Pokemon_MoveMechanics.h | 92 +++++++++++++++++++ .../Pokemon_MoveMechanics_Tests.cpp | 76 +++++++++++++++ .../Navigation/Pokemon_MoveMechanics_Tests.h | 22 +++++ SerialPrograms/cmake/SourceFiles.cmake | 3 + 5 files changed, 195 insertions(+) create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.h diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 5eec7c80d7..4920e76717 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -35,6 +35,7 @@ #include "Pokemon/Navigation/Pokemon_LegPlanner_Tests.h" #include "Pokemon/Navigation/Pokemon_LegWalker_Tests.h" #include "Pokemon/Navigation/Pokemon_MapData_Tests.h" +#include "Pokemon/Navigation/Pokemon_MoveMechanics_Tests.h" #include "Pokemon/Navigation/Pokemon_RouteLog_Tests.h" #include "Pokemon/Navigation/Pokemon_RuntimeMap_Tests.h" #include "Pokemon/Navigation/Pokemon_WallRecovery_Tests.h" @@ -78,6 +79,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_LegWalker(ret); Pokemon::add_tests_WallRecovery(ret); Pokemon::add_tests_MapData(ret); + Pokemon::add_tests_MoveMechanics(ret); Pokemon::add_tests_RuntimeMap(ret); Pokemon::add_tests_RouteLog(ret); Pokemon::add_tests_AutoStory(ret); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics.h new file mode 100644 index 0000000000..4aab5f79eb --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics.h @@ -0,0 +1,92 @@ +/* Move Mechanics + * + * From: https://github.com/PokemonAutomation/ + * + * How each game moves the player for a press, as measured on the console: + * one entry per game, read by that game's walker and by its sim. + * + */ + +#ifndef PokemonAutomation_Pokemon_MoveMechanics_H +#define PokemonAutomation_Pokemon_MoveMechanics_H + +#include +#include "Common/Cpp/Time.h" +#include "Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How the walker presses an open leg, one that ends short of a wall. +enum class OpenLegPress{ + STEP_TAPS, // a step tap a tile: the count is exact + TIMED_HOLD, // one hold, timed by the tile time +}; + +// Time per tile along each axis of the screen. +struct TileTime{ + Milliseconds across; // east or west + Milliseconds up_down; // north or south + + constexpr Milliseconds along(Direction direction) const{ + return direction == Direction::EAST || direction == Direction::WEST ? across : up_down; + } +}; + +// One way of moving: walking, running or riding. +struct Gait{ + TileTime tile; + OpenLegPress open_legs; +}; + +struct MoveMechanics{ + // A tap that turns a player facing another way, without a step. + Milliseconds turn_tap; + // A tap that takes one step, and the release before the next press. + Milliseconds step_tap; + Milliseconds step_tap_release; + // From pressing, standing still, to the first step under way. + Milliseconds start_delay; + Gait walk; + // B held, once the player has the Running Shoes. + Gait run; + // None where the walker does not ride yet. + std::optional bike; +}; + + +// Brilliant Diamond and Shining Pearl, measured on console B. The camera +// tilts, so a row takes longer than a column. D-pad taps move exactly a +// tile each, while a held run overshoots about 3 tiles in 10 (2026-11-09, +// Jubilife), so open legs are tapped. Taps: PokemonBDSP_AutoStory_RouteInput.h; +// tile times: PokemonBDSP_AutoStory_RouteTiming.h. +inline constexpr MoveMechanics BDSP_MOVE_MECHANICS{ + .turn_tap = Milliseconds(50), + .step_tap = Milliseconds(160), + .step_tap_release = Milliseconds(640), + .start_delay = Milliseconds(250), + .walk = {.tile = {.across = Milliseconds(160), .up_down = Milliseconds(240)}, .open_legs = OpenLegPress::STEP_TAPS}, + .run = {.tile = {.across = Milliseconds(100), .up_down = Milliseconds(150)}, .open_legs = OpenLegPress::STEP_TAPS}, + .bike = std::nullopt, +}; + +// FireRed and LeafGreen, measured on console B: a walking tile is 16 +// frames, running 8, and a held leg stops where its time says, so open +// legs on foot are timed holds; on the Bicycle they are counted in taps. +// The walker's holds count no start delay. Measurements: +// PokemonFRLG_MovementMechanics.h and PokemonFRLG_BikeSpinMechanics.h. +inline constexpr MoveMechanics FRLG_MOVE_MECHANICS{ + .turn_tap = Milliseconds(40), + .step_tap = Milliseconds(66), + .step_tap_release = Milliseconds(700), + .start_delay = Milliseconds(0), + .walk = {.tile = {.across = Milliseconds(267), .up_down = Milliseconds(267)}, .open_legs = OpenLegPress::TIMED_HOLD}, + .run = {.tile = {.across = Milliseconds(133), .up_down = Milliseconds(133)}, .open_legs = OpenLegPress::TIMED_HOLD}, + .bike = Gait{.tile = {.across = Milliseconds(100), .up_down = Milliseconds(100)}, .open_legs = OpenLegPress::STEP_TAPS}, +}; + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp new file mode 100644 index 0000000000..d9ab5bcdb4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp @@ -0,0 +1,76 @@ +/* Move Mechanics Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_MoveMechanics.h" +#include "Pokemon_MoveMechanics_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ +namespace{ + + +struct MoveMechanicsCase{ + std::string game; + MoveMechanics mechanics; + // 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; +}; + +// Why `faster` is not faster than `slower` on both axes, if it is not. +std::optional not_faster(const char* faster_name, const Gait& faster, const char* slower_name, const Gait& slower){ + if (faster.tile.across >= slower.tile.across || faster.tile.up_down >= slower.tile.up_down){ + return std::format("{} ({}/{} ms) is not faster than {} ({}/{} ms).", + faster_name, faster.tile.across.count(), faster.tile.up_down.count(), + slower_name, slower.tile.across.count(), slower.tile.up_down.count()); + } + return std::nullopt; +} + +class Test_MoveMechanics : public UnitTest{ +public: + explicit Test_MoveMechanics(MoveMechanicsCase scenario) + : UnitTest("Pokemon::MoveMechanics - " + scenario.game), m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const MoveMechanics& game = m_scenario.mechanics; + if (game.turn_tap >= game.step_tap){ + return std::format("The turn tap ({} ms) is not shorter than the step tap ({} ms).", + game.turn_tap.count(), game.step_tap.count()); + } + if (std::optional slower = not_faster("running", game.run, "walking", game.walk)){ + return *slower; + } + if (game.bike){ + if (std::optional slower = not_faster("the bike", *game.bike, "running", game.run)){ + return *slower; + } + } + if (game.walk.open_legs != m_scenario.open_legs_on_foot || game.run.open_legs != m_scenario.open_legs_on_foot){ + return "Open legs on foot are not pressed the way the game's walker presses them."; + } + return true; + } +private: + MoveMechanicsCase m_scenario; +}; + + +} // namespace + +void add_tests_MoveMechanics(UnitTestDatabase& database){ + database.add(MoveMechanicsCase{"BDSP", BDSP_MOVE_MECHANICS, OpenLegPress::STEP_TAPS}); + database.add(MoveMechanicsCase{"FRLG", FRLG_MOVE_MECHANICS, OpenLegPress::TIMED_HOLD}); +} + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.h new file mode 100644 index 0000000000..a545eae699 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.h @@ -0,0 +1,22 @@ +/* Move Mechanics Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_MoveMechanics_Tests_H +#define PokemonAutomation_Pokemon_MoveMechanics_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers the checks on each game's movement table. +void add_tests_MoveMechanics(UnitTestDatabase& database); + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index cd4fc4c225..bd96a5cd27 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1480,6 +1480,9 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_MapData.h Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp Source/Pokemon/Navigation/Pokemon_MapData_Tests.h + Source/Pokemon/Navigation/Pokemon_MoveMechanics.h + Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp + Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.h Source/Pokemon/Navigation/Pokemon_RuntimeMap.cpp Source/Pokemon/Navigation/Pokemon_RuntimeMap.h Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp From d1359c743442a8aa8db9271dc3328f795c511533 Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 19:40:38 -0800 Subject: [PATCH 09/20] Pokemon Navigation: MoveMechanics tests from a table of cases Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Navigation/Pokemon_MoveMechanics.h | 1 + .../Pokemon_MoveMechanics_Tests.cpp | 36 ++++++++++++++----- 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics.h index 4aab5f79eb..c96e424cd1 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics.h @@ -40,6 +40,7 @@ struct Gait{ OpenLegPress open_legs; }; +// How one game moves the player: its taps, and a tile time per gait. struct MoveMechanics{ // A tap that turns a player facing another way, without a step. Milliseconds turn_tap; diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp index d9ab5bcdb4..bdb39073ab 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include "Common/Cpp/TestRunners/UnitTest.h" #include "Pokemon_MoveMechanics.h" @@ -17,16 +18,22 @@ namespace Pokemon{ namespace{ -struct MoveMechanicsCase{ - std::string game; +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; +}; // Why `faster` is not faster than `slower` on both axes, if it is not. -std::optional not_faster(const char* faster_name, const Gait& faster, const char* slower_name, const Gait& slower){ +std::optional not_faster(std::string_view faster_name, const Gait& faster, std::string_view slower_name, const Gait& slower){ if (faster.tile.across >= slower.tile.across || faster.tile.up_down >= slower.tile.up_down){ return std::format("{} ({}/{} ms) is not faster than {} ({}/{} ms).", faster_name, faster.tile.across.count(), faster.tile.up_down.count(), @@ -38,10 +45,10 @@ std::optional not_faster(const char* faster_name, const Gait& faste class Test_MoveMechanics : public UnitTest{ public: explicit Test_MoveMechanics(MoveMechanicsCase scenario) - : UnitTest("Pokemon::MoveMechanics - " + scenario.game), m_scenario(std::move(scenario)) + : UnitTest(std::format("Pokemon::MoveMechanics - {}", scenario.input.game)), m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const MoveMechanics& game = m_scenario.mechanics; + const MoveMechanics& game = m_scenario.input.mechanics; if (game.turn_tap >= game.step_tap){ return std::format("The turn tap ({} ms) is not shorter than the step tap ({} ms).", game.turn_tap.count(), game.step_tap.count()); @@ -54,7 +61,8 @@ class Test_MoveMechanics : public UnitTest{ return *slower; } } - if (game.walk.open_legs != m_scenario.open_legs_on_foot || game.run.open_legs != m_scenario.open_legs_on_foot){ + const OpenLegPress expected = m_scenario.expectation.open_legs_on_foot; + if (game.walk.open_legs != expected || game.run.open_legs != expected){ return "Open legs on foot are not pressed the way the game's walker presses them."; } return true; @@ -63,12 +71,24 @@ class Test_MoveMechanics : public UnitTest{ MoveMechanicsCase m_scenario; }; +const MoveMechanicsCase MOVE_MECHANICS_CASES[] = { + { + .input = {.game = "BDSP", .mechanics = BDSP_MOVE_MECHANICS}, + .expectation = {.open_legs_on_foot = OpenLegPress::STEP_TAPS}, + }, + { + .input = {.game = "FRLG", .mechanics = FRLG_MOVE_MECHANICS}, + .expectation = {.open_legs_on_foot = OpenLegPress::TIMED_HOLD}, + }, +}; + } // namespace void add_tests_MoveMechanics(UnitTestDatabase& database){ - database.add(MoveMechanicsCase{"BDSP", BDSP_MOVE_MECHANICS, OpenLegPress::STEP_TAPS}); - database.add(MoveMechanicsCase{"FRLG", FRLG_MOVE_MECHANICS, OpenLegPress::TIMED_HOLD}); + for (const MoveMechanicsCase& scenario : MOVE_MECHANICS_CASES){ + database.add(scenario); + } } From dbe09a798a95f87bed7eb89d6cd1bccc12341af2 Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 20:31:06 -0800 Subject: [PATCH 10/20] Pokemon Navigation: connected maps, one world type for BDSP and FRLG Maps joined by their warps and edges, with the player's place as a map and a tile of it. Where a warp or an edge leads is computed once here; whether a step is allowed stays per game. connect_by_world() joins maps placed on one world grid, for BDSP's maps, which have no connections. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../ComputerPrograms_UnitTestRunner.cpp | 2 + .../Navigation/Pokemon_ConnectedMaps.cpp | 134 ++++++++++++ .../Navigation/Pokemon_ConnectedMaps.h | 90 ++++++++ .../Pokemon_ConnectedMaps_Tests.cpp | 205 ++++++++++++++++++ .../Navigation/Pokemon_ConnectedMaps_Tests.h | 22 ++ SerialPrograms/cmake/SourceFiles.cmake | 4 + 6 files changed, 457 insertions(+) create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 5eec7c80d7..8e3eb9c1ec 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -32,6 +32,7 @@ #include "NintendoSwitch/Programs/Typewriter/NintendoSwitch_Typewriter_Tests.h" #include "NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.h" +#include "Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h" #include "Pokemon/Navigation/Pokemon_LegPlanner_Tests.h" #include "Pokemon/Navigation/Pokemon_LegWalker_Tests.h" #include "Pokemon/Navigation/Pokemon_MapData_Tests.h" @@ -78,6 +79,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_LegWalker(ret); Pokemon::add_tests_WallRecovery(ret); Pokemon::add_tests_MapData(ret); + Pokemon::add_tests_ConnectedMaps(ret); Pokemon::add_tests_RuntimeMap(ret); Pokemon::add_tests_RouteLog(ret); Pokemon::add_tests_AutoStory(ret); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp new file mode 100644 index 0000000000..7f802aac2d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp @@ -0,0 +1,134 @@ +/* Connected Maps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_ConnectedMaps.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::optional ConnectedMaps::find(std::string_view name) const{ + for (size_t index = 0; index < m_maps->size(); index++){ + if ((*m_maps)[index].name == name){ + return index; + } + } + return std::nullopt; +} + +std::optional ConnectedMaps::warp_arrival(const MapWarp& warp) const{ + if (!warp.to){ + return std::nullopt; + } + const std::optional destination = find(warp.to->map); + if (!destination){ + return std::nullopt; + } + const MapData& to = map(*destination); + const auto arrival = to.points.find(warp.to->point); + if (arrival == to.points.end()){ + return std::nullopt; + } + return MapPlace{*destination, arrival->second}; +} + +std::optional ConnectedMaps::across_edge(const MapPlace& from, Direction side) const{ + const TilePos here = from.tile; + for (const MapConnection& connection : map(from.map).connections){ + if (connection.side != side){ + continue; + } + const std::optional destination = find(connection.to_map); + if (!destination){ + continue; + } + const Grid& to = map(*destination).tiles; + TilePos point{here.x - connection.offset, here.y - connection.offset}; + switch (side){ + case Direction::NORTH: + point.y = to.height - 1; + break; + case Direction::SOUTH: + point.y = 0; + break; + case Direction::WEST: + point.x = to.width - 1; + break; + case Direction::EAST: + point.x = 0; + break; + } + if (to.contains(point)){ + return MapPlace{*destination, point}; + } + } + return std::nullopt; +} + +std::optional ConnectedMaps::neighbour(const MapPlace& from, Direction direction) const{ + const TilePos ahead = from.tile.next(direction); + if (map(from.map).tiles.contains(ahead)){ + return MapPlace{from.map, ahead}; + } + return across_edge(from, direction); +} + + +namespace{ + +// The side of `a` that `b` touches, and the offset of `b`'s tiles along it, +// if their rectangles on the world grid meet along a side. +std::optional touching(const MapData& a, const MapData& b){ + const TilePos pa = a.world->offset; + const TilePos pb = b.world->offset; + const int aw = a.tiles.width; + const int ah = a.tiles.height; + const int bw = b.tiles.width; + const int bh = b.tiles.height; + const bool columns_overlap = pa.x < pb.x + bw && pb.x < pa.x + aw; + const bool rows_overlap = pa.y < pb.y + bh && pb.y < pa.y + ah; + if (columns_overlap && pb.y + bh == pa.y){ + return MapConnection{Direction::NORTH, b.name, pb.x - pa.x}; + } + if (columns_overlap && pb.y == pa.y + ah){ + return MapConnection{Direction::SOUTH, b.name, pb.x - pa.x}; + } + if (rows_overlap && pb.x + bw == pa.x){ + return MapConnection{Direction::WEST, b.name, pb.y - pa.y}; + } + if (rows_overlap && pb.x == pa.x + aw){ + return MapConnection{Direction::EAST, b.name, pb.y - pa.y}; + } + return std::nullopt; +} + +} // namespace + +void connect_by_world(std::vector& maps){ + for (MapData& a : maps){ + for (const MapData& b : maps){ + if (&a == &b || !a.world || !b.world || a.world->name != b.world->name){ + continue; + } + const std::optional connection = touching(a, b); + if (!connection){ + continue; + } + const bool joined = std::ranges::any_of(a.connections, [&](const MapConnection& existing){ + return existing.to_map == b.name; + }); + if (!joined){ + a.connections.push_back(*connection); + } + } + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h new file mode 100644 index 0000000000..f23e25d06a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h @@ -0,0 +1,90 @@ +/* Connected Maps + * + * From: https://github.com/PokemonAutomation/ + * + * The one world the tile games (BDSP, FRLG) plan and walk on: maps joined by + * their warps and their edges (MapData::connections). The player's place in + * it is a map and a tile of that map, in the map's own coordinates. Where a + * warp or an edge leads is the same in both games; whether a step is + * allowed, and what the game does on arrival (FRLG walks the player out of + * a door), is each game's. + * + */ + +#ifndef PokemonAutomation_Pokemon_ConnectedMaps_H +#define PokemonAutomation_Pokemon_ConnectedMaps_H + +#include +#include +#include +#include +#include "Pokemon_Grid.h" +#include "Pokemon_MapData.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A tile of one of the connected maps: the map's index and the tile in that +// map's own coordinates. +struct MapPlace{ + size_t map = 0; + TilePos tile; + + bool operator==(const MapPlace& other) const = default; +}; + + +// A view of loaded maps as one connected world. It does not own the maps, +// which must outlive it and keep their order: MapPlace::map indexes them. +class ConnectedMaps{ +public: + explicit ConnectedMaps(const std::vector& maps) + : m_maps(&maps) + {} + + const MapData& map(size_t index) const{ + return (*m_maps)[index]; + } + // The loaded map named `name`, or nothing. + std::optional find(std::string_view name) const; + + // Where taking `warp` puts the player: its destination point. Nothing + // if it leads to a map that isn't loaded or names a point that map + // doesn't have. + std::optional warp_arrival(const MapWarp& warp) const; + + // The tile past `side` of `from`'s map that carries on `from`'s row or + // column: on the first loaded map connected on that side that has it. + // Nothing if no loaded map there has it. + std::optional across_edge(const MapPlace& from, Direction side) const; + + // The tile next to `from` in `direction`: on the same map, or across + // its edge. Nothing past an edge that leads nowhere loaded. + std::optional neighbour(const MapPlace& from, Direction direction) const; + +private: + const std::vector* m_maps; +}; + + +// Joins the maps that lie on the same world grid (MapData::world) where +// they meet: each map gets a connection on each side to every map whose +// rectangle touches that side, unless it has one to that map already. +// Maps without a world are left alone. +void connect_by_world(std::vector& maps); + + + +} // namespace Pokemon +} // namespace PokemonAutomation + + +template <> +struct std::hash{ + size_t operator()(const PokemonAutomation::Pokemon::MapPlace& place) const{ + return std::hash()(place.tile) * 31 + place.map; + } +}; + +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp new file mode 100644 index 0000000000..69ad4cbf65 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp @@ -0,0 +1,205 @@ +/* Connected Maps Tests + * + * From: https://github.com/PokemonAutomation/ + * + * A town with a route north of it and a lake east of it, joined by their + * places on one world grid (connect_by_world()), and a house the town's + * door warps into: + * + * world x: -1 0 1 2 3 4 5 + * y 0..2: [ Route (6 wide) ] + * y 3..5: [ Town (4) ][Lake] + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_ConnectedMaps.h" +#include "Pokemon_ConnectedMaps_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ +namespace{ + + +MapData open_map(std::string name, int width, int height){ + MapData map; + map.name = std::move(name); + map.tiles = Grid{width, height, std::vector((size_t)width * height, TileKind::OPEN)}; + return map; +} + +MapData on_world(MapData map, const TilePos& offset){ + map.world = MapWorld{"Test", offset}; + return map; +} + +const std::vector& test_maps(){ + static const std::vector maps = []{ + std::vector ret{ + on_world(open_map("Town", 4, 3), {0, 3}), + on_world(open_map("Route", 6, 3), {-1, 0}), + on_world(open_map("Lake", 2, 3), {4, 3}), + open_map("House", 2, 2), + }; + ret[3].points["door"] = {0, 1}; + connect_by_world(ret); + return ret; + }(); + return maps; +} + +// A tile named by its map. +struct NamedPlace{ + std::string_view map; + TilePos tile; +}; + +std::string describe(const ConnectedMaps& world, const std::optional& place){ + if (!place){ + return "nowhere"; + } + return world.map(place->map).name + " " + to_string(place->tile); +} + +// Why `actual` is not `expected`, if it is not. +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}; + } + if (actual == wanted){ + return std::nullopt; + } + return std::format("Got {}, expected {}.", describe(world, actual), describe(world, wanted)); +} + + +struct StepInput{ + std::string_view name; + NamedPlace from; + Direction direction; +}; +struct StepCase{ + StepInput input; + std::optional expectation; +}; + +class Test_ConnectedMaps_Step : public UnitTest{ +public: + explicit Test_ConnectedMaps_Step(StepCase scenario) + : UnitTest(std::format("Pokemon::ConnectedMaps - {}", scenario.input.name)), m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const ConnectedMaps world(test_maps()); + const StepInput& 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)){ + return *error; + } + return true; + } +private: + StepCase m_scenario; +}; + +const StepCase STEP_CASES[] = { + { + .input = {.name = "a step on the same map", .from = {"Town", {1, 1}}, .direction = Direction::EAST}, + .expectation = NamedPlace{"Town", {2, 1}}, + }, + { + .input = {.name = "north onto the route, shifted by its offset", .from = {"Town", {0, 0}}, .direction = Direction::NORTH}, + .expectation = NamedPlace{"Route", {1, 2}}, + }, + { + .input = {.name = "south off the route into the town", .from = {"Route", {1, 2}}, .direction = Direction::SOUTH}, + .expectation = NamedPlace{"Town", {0, 0}}, + }, + { + .input = {.name = "east into the lake", .from = {"Town", {3, 2}}, .direction = Direction::EAST}, + .expectation = NamedPlace{"Lake", {0, 2}}, + }, + { + .input = {.name = "west into the town", .from = {"Lake", {0, 1}}, .direction = Direction::WEST}, + .expectation = NamedPlace{"Town", {3, 1}}, + }, + { + .input = {.name = "an edge no map joins", .from = {"Town", {0, 1}}, .direction = Direction::WEST}, + .expectation = std::nullopt, + }, + { + .input = {.name = "past the joined map's span", .from = {"Route", {0, 2}}, .direction = Direction::SOUTH}, + .expectation = std::nullopt, + }, + { + .input = {.name = "a map off the world grid joins nothing", .from = {"House", {1, 0}}, .direction = Direction::NORTH}, + .expectation = std::nullopt, + }, +}; + + +struct WarpInput{ + std::string_view name; + MapWarp warp; +}; +struct WarpCase{ + WarpInput input; + std::optional expectation; +}; + +class Test_ConnectedMaps_Warp : public UnitTest{ +public: + explicit Test_ConnectedMaps_Warp(WarpCase scenario) + : UnitTest(std::format("Pokemon::ConnectedMaps - {}", scenario.input.name)), m_scenario(std::move(scenario)) + {} + 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)){ + return *error; + } + return true; + } +private: + WarpCase m_scenario; +}; + +const WarpCase WARP_CASES[] = { + { + .input = {.name = "a warp to a loaded map's point", .warp = {.to = WarpDestination{"House", "door"}}}, + .expectation = NamedPlace{"House", {0, 1}}, + }, + { + .input = {.name = "a warp to a map that isn't loaded", .warp = {.to = WarpDestination{"Cave", "door"}}}, + .expectation = std::nullopt, + }, + { + .input = {.name = "a warp to a point the map lacks", .warp = {.to = WarpDestination{"House", "stairs"}}}, + .expectation = std::nullopt, + }, + { + .input = {.name = "a warp that leads nowhere", .warp = {}}, + .expectation = std::nullopt, + }, +}; + + +} // namespace + +void add_tests_ConnectedMaps(UnitTestDatabase& database){ + for (const StepCase& scenario : STEP_CASES){ + database.add(scenario); + } + for (const WarpCase& scenario : WARP_CASES){ + database.add(scenario); + } +} + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h new file mode 100644 index 0000000000..a3d6a6c26b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h @@ -0,0 +1,22 @@ +/* Connected Maps Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_ConnectedMaps_Tests_H +#define PokemonAutomation_Pokemon_ConnectedMaps_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers the checks on stepping and warping between connected maps. +void add_tests_ConnectedMaps(UnitTestDatabase& database); + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index cd4fc4c225..a5f48d3bcb 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1459,6 +1459,10 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Inference/Pokemon_TrainPokemonOCR.h Source/Pokemon/Inference/Pokemon_TypeReader.cpp Source/Pokemon/Inference/Pokemon_TypeReader.h + Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp + Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h + Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp + Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h Source/Pokemon/Navigation/Pokemon_Grid.cpp Source/Pokemon/Navigation/Pokemon_Grid.h Source/Pokemon/Navigation/Pokemon_LegTypes.h From b64cd70dc406a9931b2afdeb2041db2746dd541e Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 20:33:17 -0800 Subject: [PATCH 11/20] Pokemon Navigation: connected maps tests take an expectation struct; edge entry split out Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Navigation/Pokemon_ConnectedMaps.cpp | 41 +++++++++++-------- .../Navigation/Pokemon_ConnectedMaps.h | 1 + .../Pokemon_ConnectedMaps_Tests.cpp | 38 +++++++++-------- 3 files changed, 48 insertions(+), 32 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp index 7f802aac2d..73b0495f30 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp @@ -9,6 +9,30 @@ namespace PokemonAutomation{ namespace Pokemon{ +namespace{ + +// The tile of `to` that `connection` on `side` leads onto from `here`: +// the edge row or column, shifted by the connection's offset. +TilePos edge_entry(const TilePos& here, Direction side, const MapConnection& connection, const Grid& to){ + TilePos point{here.x - connection.offset, here.y - connection.offset}; + switch (side){ + case Direction::NORTH: + point.y = to.height - 1; + break; + case Direction::SOUTH: + point.y = 0; + break; + case Direction::WEST: + point.x = to.width - 1; + break; + case Direction::EAST: + point.x = 0; + break; + } + return point; +} + +} // namespace std::optional ConnectedMaps::find(std::string_view name) const{ @@ -37,7 +61,6 @@ std::optional ConnectedMaps::warp_arrival(const MapWarp& warp) const{ } std::optional ConnectedMaps::across_edge(const MapPlace& from, Direction side) const{ - const TilePos here = from.tile; for (const MapConnection& connection : map(from.map).connections){ if (connection.side != side){ continue; @@ -47,21 +70,7 @@ std::optional ConnectedMaps::across_edge(const MapPlace& from, Directi continue; } const Grid& to = map(*destination).tiles; - TilePos point{here.x - connection.offset, here.y - connection.offset}; - switch (side){ - case Direction::NORTH: - point.y = to.height - 1; - break; - case Direction::SOUTH: - point.y = 0; - break; - case Direction::WEST: - point.x = to.width - 1; - break; - case Direction::EAST: - point.x = 0; - break; - } + const TilePos point = edge_entry(from.tile, side, connection, to); if (to.contains(point)){ return MapPlace{*destination, point}; } diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h index f23e25d06a..905685db72 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h @@ -80,6 +80,7 @@ void connect_by_world(std::vector& maps); } // namespace PokemonAutomation +// A hash of MapPlace, for planners that keep places in unordered sets. template <> struct std::hash{ size_t operator()(const PokemonAutomation::Pokemon::MapPlace& place) const{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp index 69ad4cbf65..d39c6d2a3e 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp @@ -64,11 +64,17 @@ std::string describe(const ConnectedMaps& world, const std::optional& if (!place){ return "nowhere"; } - return world.map(place->map).name + " " + to_string(place->tile); + return std::format("{} {}", world.map(place->map).name, to_string(place->tile)); } // Why `actual` is not `expected`, if it is not. -std::optional mismatch(const ConnectedMaps& world, const std::optional& actual, const std::optional& expected){ +// Where a step or a warp should put the player, or nothing for nowhere. +struct PlaceExpectation{ + std::optional place; +}; + +std::optional mismatch(const ConnectedMaps& world, const std::optional& actual, const PlaceExpectation& expectation){ + const std::optional& expected = expectation.place; std::optional wanted; if (expected){ wanted = MapPlace{*world.find(expected->map), expected->tile}; @@ -87,7 +93,7 @@ struct StepInput{ }; struct StepCase{ StepInput input; - std::optional expectation; + PlaceExpectation expectation; }; class Test_ConnectedMaps_Step : public UnitTest{ @@ -111,35 +117,35 @@ class Test_ConnectedMaps_Step : public UnitTest{ const StepCase STEP_CASES[] = { { .input = {.name = "a step on the same map", .from = {"Town", {1, 1}}, .direction = Direction::EAST}, - .expectation = NamedPlace{"Town", {2, 1}}, + .expectation = {.place = NamedPlace{"Town", {2, 1}}}, }, { .input = {.name = "north onto the route, shifted by its offset", .from = {"Town", {0, 0}}, .direction = Direction::NORTH}, - .expectation = NamedPlace{"Route", {1, 2}}, + .expectation = {.place = NamedPlace{"Route", {1, 2}}}, }, { .input = {.name = "south off the route into the town", .from = {"Route", {1, 2}}, .direction = Direction::SOUTH}, - .expectation = NamedPlace{"Town", {0, 0}}, + .expectation = {.place = NamedPlace{"Town", {0, 0}}}, }, { .input = {.name = "east into the lake", .from = {"Town", {3, 2}}, .direction = Direction::EAST}, - .expectation = NamedPlace{"Lake", {0, 2}}, + .expectation = {.place = NamedPlace{"Lake", {0, 2}}}, }, { .input = {.name = "west into the town", .from = {"Lake", {0, 1}}, .direction = Direction::WEST}, - .expectation = NamedPlace{"Town", {3, 1}}, + .expectation = {.place = NamedPlace{"Town", {3, 1}}}, }, { .input = {.name = "an edge no map joins", .from = {"Town", {0, 1}}, .direction = Direction::WEST}, - .expectation = std::nullopt, + .expectation = {.place = std::nullopt}, }, { .input = {.name = "past the joined map's span", .from = {"Route", {0, 2}}, .direction = Direction::SOUTH}, - .expectation = std::nullopt, + .expectation = {.place = std::nullopt}, }, { .input = {.name = "a map off the world grid joins nothing", .from = {"House", {1, 0}}, .direction = Direction::NORTH}, - .expectation = std::nullopt, + .expectation = {.place = std::nullopt}, }, }; @@ -150,7 +156,7 @@ struct WarpInput{ }; struct WarpCase{ WarpInput input; - std::optional expectation; + PlaceExpectation expectation; }; class Test_ConnectedMaps_Warp : public UnitTest{ @@ -172,19 +178,19 @@ class Test_ConnectedMaps_Warp : public UnitTest{ const WarpCase WARP_CASES[] = { { .input = {.name = "a warp to a loaded map's point", .warp = {.to = WarpDestination{"House", "door"}}}, - .expectation = NamedPlace{"House", {0, 1}}, + .expectation = {.place = NamedPlace{"House", {0, 1}}}, }, { .input = {.name = "a warp to a map that isn't loaded", .warp = {.to = WarpDestination{"Cave", "door"}}}, - .expectation = std::nullopt, + .expectation = {.place = std::nullopt}, }, { .input = {.name = "a warp to a point the map lacks", .warp = {.to = WarpDestination{"House", "stairs"}}}, - .expectation = std::nullopt, + .expectation = {.place = std::nullopt}, }, { .input = {.name = "a warp that leads nowhere", .warp = {}}, - .expectation = std::nullopt, + .expectation = {.place = std::nullopt}, }, }; From a0991bc871c9461542ebc1ef88163740b002f91b Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 20:36:15 -0800 Subject: [PATCH 12/20] Pokemon Navigation: ConnectedMaps::size() Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h index 905685db72..8b8c62948f 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h @@ -43,6 +43,10 @@ class ConnectedMaps{ : m_maps(&maps) {} + // How many maps are loaded: MapPlace::map runs from 0 to size() - 1. + size_t size() const{ + return m_maps->size(); + } const MapData& map(size_t index) const{ return (*m_maps)[index]; } From 78abee2da385d40de0af6aa1feda93dc95af7038 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 00:13:54 -0800 Subject: [PATCH 13/20] Pokemon Navigation: step taps per gait; default member values; failure messages name expected and actual (#402 review) FRLG's Bicycle taps 40 ms at one per 100 ms, its walk 66 ms with a 700 ms release, so the step tap moves from MoveMechanics onto Gait. Every scalar gets a default, and the test reports which gait and which value failed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Navigation/Pokemon_MoveMechanics.h | 68 +++++++++++++------ .../Pokemon_MoveMechanics_Tests.cpp | 62 +++++++++++++---- 2 files changed, 95 insertions(+), 35 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics.h index c96e424cd1..2b7d734b88 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics.h @@ -26,29 +26,37 @@ enum class OpenLegPress{ // Time per tile along each axis of the screen. struct TileTime{ - Milliseconds across; // east or west - Milliseconds up_down; // north or south + Milliseconds across{}; // east or west + Milliseconds up_down{}; // north or south constexpr Milliseconds along(Direction direction) const{ return direction == Direction::EAST || direction == Direction::WEST ? across : up_down; } }; +// A tap that takes one step: the press, and the release before the next +// press. Their sum is the time per tapped tile. +struct StepTap{ + Milliseconds hold{}; + Milliseconds release{}; +}; + // One way of moving: walking, running or riding. struct Gait{ TileTime tile; - OpenLegPress open_legs; + // The step tap in this gait; a game's taps differ by gait (FRLG's + // Bicycle taps far faster than its walk). + StepTap tap; + OpenLegPress open_legs = OpenLegPress::STEP_TAPS; }; -// How one game moves the player: its taps, and a tile time per gait. +// How one game moves the player: its turn tap, and a tile time and step +// tap per gait. struct MoveMechanics{ // A tap that turns a player facing another way, without a step. - Milliseconds turn_tap; - // A tap that takes one step, and the release before the next press. - Milliseconds step_tap; - Milliseconds step_tap_release; + Milliseconds turn_tap{}; // From pressing, standing still, to the first step under way. - Milliseconds start_delay; + Milliseconds start_delay{}; Gait walk; // B held, once the player has the Running Shoes. Gait run; @@ -64,27 +72,45 @@ struct MoveMechanics{ // tile times: PokemonBDSP_AutoStory_RouteTiming.h. inline constexpr MoveMechanics BDSP_MOVE_MECHANICS{ .turn_tap = Milliseconds(50), - .step_tap = Milliseconds(160), - .step_tap_release = Milliseconds(640), .start_delay = Milliseconds(250), - .walk = {.tile = {.across = Milliseconds(160), .up_down = Milliseconds(240)}, .open_legs = OpenLegPress::STEP_TAPS}, - .run = {.tile = {.across = Milliseconds(100), .up_down = Milliseconds(150)}, .open_legs = OpenLegPress::STEP_TAPS}, + .walk = { + .tile = {.across = Milliseconds(160), .up_down = Milliseconds(240)}, + .tap = {.hold = Milliseconds(160), .release = Milliseconds(640)}, + .open_legs = OpenLegPress::STEP_TAPS, + }, + .run = { + .tile = {.across = Milliseconds(100), .up_down = Milliseconds(150)}, + .tap = {.hold = Milliseconds(160), .release = Milliseconds(640)}, + .open_legs = OpenLegPress::STEP_TAPS, + }, .bike = std::nullopt, }; // FireRed and LeafGreen, measured on console B: a walking tile is 16 // frames, running 8, and a held leg stops where its time says, so open -// legs on foot are timed holds; on the Bicycle they are counted in taps. -// The walker's holds count no start delay. Measurements: -// PokemonFRLG_MovementMechanics.h and PokemonFRLG_BikeSpinMechanics.h. +// legs on foot are timed holds; on the Bicycle they are counted in taps, +// 40 ms at one per 100 ms (BIKE_TAP_PERIOD_WORKED; at a 60 ms period one +// tap in 12 drops). The walker's holds count no start delay. +// Measurements: PokemonFRLG_MovementMechanics.h and +// PokemonFRLG_BikeSpinMechanics.h. inline constexpr MoveMechanics FRLG_MOVE_MECHANICS{ .turn_tap = Milliseconds(40), - .step_tap = Milliseconds(66), - .step_tap_release = Milliseconds(700), .start_delay = Milliseconds(0), - .walk = {.tile = {.across = Milliseconds(267), .up_down = Milliseconds(267)}, .open_legs = OpenLegPress::TIMED_HOLD}, - .run = {.tile = {.across = Milliseconds(133), .up_down = Milliseconds(133)}, .open_legs = OpenLegPress::TIMED_HOLD}, - .bike = Gait{.tile = {.across = Milliseconds(100), .up_down = Milliseconds(100)}, .open_legs = OpenLegPress::STEP_TAPS}, + .walk = { + .tile = {.across = Milliseconds(267), .up_down = Milliseconds(267)}, + .tap = {.hold = Milliseconds(66), .release = Milliseconds(700)}, + .open_legs = OpenLegPress::TIMED_HOLD, + }, + .run = { + .tile = {.across = Milliseconds(133), .up_down = Milliseconds(133)}, + .tap = {.hold = Milliseconds(66), .release = Milliseconds(700)}, + .open_legs = OpenLegPress::TIMED_HOLD, + }, + .bike = Gait{ + .tile = {.across = Milliseconds(100), .up_down = Milliseconds(100)}, + .tap = {.hold = Milliseconds(40), .release = Milliseconds(60)}, + .open_legs = OpenLegPress::STEP_TAPS, + }, }; diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp index bdb39073ab..c0de39e0f5 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp @@ -42,6 +42,39 @@ std::optional not_faster(std::string_view faster_name, const Gait& return std::nullopt; } +// Why the turn tap would step on foot in `gait`, if it would: a turn tap +// must be shorter than the gait's step tap. +std::optional turn_steps(std::string_view gait_name, const Gait& gait, Milliseconds turn_tap){ + if (turn_tap >= gait.tap.hold){ + return std::format("The turn tap ({} ms) is not shorter than the {} step tap ({} ms).", + turn_tap.count(), gait_name, gait.tap.hold.count()); + } + return std::nullopt; +} + +// Why a gait's step tap is unusable, if it is: both its press and its +// release must take time. +std::optional empty_tap(std::string_view gait_name, const Gait& gait){ + if (gait.tap.hold <= Milliseconds(0) || gait.tap.release <= Milliseconds(0)){ + return std::format("The {} step tap is {} ms pressed, {} ms released; both must be over 0.", + gait_name, gait.tap.hold.count(), gait.tap.release.count()); + } + return std::nullopt; +} + +std::string_view open_leg_press_name(OpenLegPress press){ + return press == OpenLegPress::STEP_TAPS ? "step taps" : "a timed hold"; +} + +// Why `gait` presses its open legs other than `expected`, if it does. +std::optional wrong_open_legs(std::string_view gait_name, const Gait& gait, OpenLegPress expected){ + if (gait.open_legs != expected){ + return std::format("Open legs {} are pressed as {}, expected {}.", + gait_name, open_leg_press_name(gait.open_legs), open_leg_press_name(expected)); + } + return std::nullopt; +} + class Test_MoveMechanics : public UnitTest{ public: explicit Test_MoveMechanics(MoveMechanicsCase scenario) @@ -49,21 +82,22 @@ class Test_MoveMechanics : public UnitTest{ {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ const MoveMechanics& game = m_scenario.input.mechanics; - if (game.turn_tap >= game.step_tap){ - return std::format("The turn tap ({} ms) is not shorter than the step tap ({} ms).", - game.turn_tap.count(), game.step_tap.count()); - } - if (std::optional slower = not_faster("running", game.run, "walking", game.walk)){ - return *slower; - } - if (game.bike){ - if (std::optional slower = not_faster("the bike", *game.bike, "running", game.run)){ - return *slower; - } - } const OpenLegPress expected = m_scenario.expectation.open_legs_on_foot; - if (game.walk.open_legs != expected || game.run.open_legs != expected){ - return "Open legs on foot are not pressed the way the game's walker presses them."; + const std::optional failures[] = { + empty_tap("walking", game.walk), + empty_tap("running", game.run), + game.bike ? empty_tap("bike", *game.bike) : std::nullopt, + turn_steps("walking", game.walk, game.turn_tap), + turn_steps("running", game.run, game.turn_tap), + not_faster("running", game.run, "walking", game.walk), + game.bike ? not_faster("the bike", *game.bike, "running", game.run) : std::nullopt, + wrong_open_legs("walking", game.walk, expected), + wrong_open_legs("running", game.run, expected), + }; + for (const std::optional& failure : failures){ + if (failure){ + return *failure; + } } return true; } From 371bd8d1d163f8e3b1298970f674310ed1bd7086 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 00:15:57 -0800 Subject: [PATCH 14/20] Pokemon Navigation: ConnectedMaps refuses temporaries, checks map indexes, orders MapPlace (#408 review) The rvalue constructor is deleted, map() throws InternalProgramError past the last map, and MapPlace gets a defaulted <=> over TilePos's. The test art matches the maps, the Lake to Route edge has two cases, and stale map indexes have their own. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Navigation/Pokemon_ConnectedMaps.cpp | 10 ++++ .../Navigation/Pokemon_ConnectedMaps.h | 10 +++- .../Pokemon_ConnectedMaps_Tests.cpp | 55 ++++++++++++++++++- 3 files changed, 69 insertions(+), 6 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp index 73b0495f30..1bd697a03e 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp @@ -5,6 +5,8 @@ */ #include +#include +#include "Common/Cpp/Exceptions.h" #include "Pokemon_ConnectedMaps.h" namespace PokemonAutomation{ @@ -35,6 +37,14 @@ TilePos edge_entry(const TilePos& here, Direction side, const MapConnection& con } // namespace +const MapData& ConnectedMaps::map(size_t index) const{ + if (index >= m_maps->size()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, + std::format("Map index {} is past the {} connected maps.", index, m_maps->size())); + } + return (*m_maps)[index]; +} + std::optional ConnectedMaps::find(std::string_view name) const{ for (size_t index = 0; index < m_maps->size(); index++){ if ((*m_maps)[index].name == name){ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h index 8b8c62948f..5fef2d16a6 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h @@ -32,6 +32,8 @@ struct MapPlace{ TilePos tile; bool operator==(const MapPlace& other) const = default; + // Map, then tile: an order for sets and maps of places. + auto operator<=>(const MapPlace& other) const = default; }; @@ -42,14 +44,16 @@ class ConnectedMaps{ explicit ConnectedMaps(const std::vector& maps) : m_maps(&maps) {} + // A temporary list would be gone by the first call. + explicit ConnectedMaps(std::vector&& maps) = delete; // How many maps are loaded: MapPlace::map runs from 0 to size() - 1. size_t size() const{ return m_maps->size(); } - const MapData& map(size_t index) const{ - return (*m_maps)[index]; - } + // The map at `index`; throws InternalProgramError past the last map, + // as from a MapPlace of another world. + const MapData& map(size_t index) const; // The loaded map named `name`, or nothing. std::optional find(std::string_view name) const; diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp index d39c6d2a3e..abcc99f641 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp @@ -7,8 +7,8 @@ * door warps into: * * world x: -1 0 1 2 3 4 5 - * y 0..2: [ Route (6 wide) ] - * y 3..5: [ Town (4) ][Lake] + * y 0..2: [ Route (6 wide) ] + * y 3..5: [ Town (4) ][Lake] * */ @@ -18,6 +18,7 @@ #include #include #include +#include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTest.h" #include "Pokemon_ConnectedMaps.h" #include "Pokemon_ConnectedMaps_Tests.h" @@ -67,12 +68,12 @@ std::string describe(const ConnectedMaps& world, const std::optional& return std::format("{} {}", world.map(place->map).name, to_string(place->tile)); } -// Why `actual` is not `expected`, if it is not. // 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 wanted; @@ -135,6 +136,14 @@ const StepCase STEP_CASES[] = { .input = {.name = "west into the town", .from = {"Lake", {0, 1}}, .direction = Direction::WEST}, .expectation = {.place = NamedPlace{"Town", {3, 1}}}, }, + { + .input = {.name = "north out of the lake onto the route's last column", .from = {"Lake", {0, 0}}, .direction = Direction::NORTH}, + .expectation = {.place = NamedPlace{"Route", {5, 2}}}, + }, + { + .input = {.name = "north out of the lake past the route's span", .from = {"Lake", {1, 0}}, .direction = Direction::NORTH}, + .expectation = {.place = std::nullopt}, + }, { .input = {.name = "an edge no map joins", .from = {"Town", {0, 1}}, .direction = Direction::WEST}, .expectation = {.place = std::nullopt}, @@ -195,6 +204,43 @@ const WarpCase WARP_CASES[] = { }; +struct StalePlaceInput{ + std::string_view name; + size_t map; +}; +struct StalePlaceCase{ + StalePlaceInput input; +}; + +// A place whose map index is past the loaded maps (from another world, or +// one that has since shrunk) is an InternalProgramError, not a read past +// the end. +class Test_ConnectedMaps_StalePlace : public UnitTest{ +public: + explicit Test_ConnectedMaps_StalePlace(StalePlaceCase scenario) + : UnitTest(std::format("Pokemon::ConnectedMaps - {}", scenario.input.name)), m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const ConnectedMaps world(test_maps()); + const MapPlace stale{m_scenario.input.map, {0, 0}}; + try{ + const std::optional place = world.neighbour(stale, Direction::NORTH); + return std::format("Map {} of {} was read: got {}, expected an InternalProgramError.", + stale.map, world.size(), place ? to_string(place->tile) : "nowhere"); + }catch (const InternalProgramError&){ + return true; + } + } +private: + StalePlaceCase m_scenario; +}; + +const StalePlaceCase STALE_PLACE_CASES[] = { + {.input = {.name = "a map index one past the last is rejected", .map = 4}}, + {.input = {.name = "a map index far past the last is rejected", .map = 1000}}, +}; + + } // namespace void add_tests_ConnectedMaps(UnitTestDatabase& database){ @@ -204,6 +250,9 @@ void add_tests_ConnectedMaps(UnitTestDatabase& database){ for (const WarpCase& scenario : WARP_CASES){ database.add(scenario); } + for (const StalePlaceCase& scenario : STALE_PLACE_CASES){ + database.add(scenario); + } } From 213ceb78aaee19d59cbe9d8a0359047bb966a799 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 00:25:48 -0800 Subject: [PATCH 15/20] Pokemon Navigation: stale-place cases carry their expectation (code health) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon_ConnectedMaps_Tests.cpp | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp index abcc99f641..ceafa9304d 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp @@ -208,8 +208,13 @@ 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; }; // A place whose map index is past the loaded maps (from another world, or @@ -223,21 +228,26 @@ class Test_ConnectedMaps_StalePlace : public UnitTest{ virtual UnitTestResult run(Logger&, CancellableScope&) const override{ const ConnectedMaps world(test_maps()); const MapPlace stale{m_scenario.input.map, {0, 0}}; + bool rejected = false; try{ - const std::optional place = world.neighbour(stale, Direction::NORTH); - return std::format("Map {} of {} was read: got {}, expected an InternalProgramError.", - stale.map, world.size(), place ? to_string(place->tile) : "nowhere"); + world.neighbour(stale, Direction::NORTH); }catch (const InternalProgramError&){ - return true; + rejected = true; + } + if (rejected != m_scenario.expectation.rejected){ + return std::format("Map {} of {} was {}, expected it {}.", stale.map, world.size(), + rejected ? "rejected" : "read", m_scenario.expectation.rejected ? "rejected" : "read"); } + return true; } private: StalePlaceCase m_scenario; }; const StalePlaceCase STALE_PLACE_CASES[] = { - {.input = {.name = "a map index one past the last is rejected", .map = 4}}, - {.input = {.name = "a map index far past the last is rejected", .map = 1000}}, + {.input = {.name = "the last map index is read", .map = 3}, .expectation = {.rejected = false}}, + {.input = {.name = "a map index one past the last is rejected", .map = 4}, .expectation = {.rejected = true}}, + {.input = {.name = "a map index far past the last is rejected", .map = 1000}, .expectation = {.rejected = true}}, }; From f10f18ffc0d0349017f0c65f9f40cfe5adc4b362 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:15:33 -0800 Subject: [PATCH 16/20] 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 3c4d8671e11387e5d80e873f972124262aa0bdaf Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:35:25 -0800 Subject: [PATCH 17/20] 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 b681c75f392ddadf1ec052447c416b0efd1889d5 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:41:39 -0800 Subject: [PATCH 18/20] 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 8eb6f347ef066595d951c6b9b594d1b29978be25 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:02:58 -0800 Subject: [PATCH 19/20] 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 20/20] 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 = {{}}, }, {