diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index f18de60c58..bbfd50fee3 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -19,7 +19,9 @@ #include "Pokemon_AutoStoryStats_Tests.h" #include "Pokemon_Interrupts_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_StorySegments_Tests.h" #include "Pokemon_StoryStepExecutor_Tests.h" @@ -45,6 +47,8 @@ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_ScreenEvents(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 25f9292ebc..14dc71eabb 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1528,6 +1528,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 @@ -1542,12 +1543,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 @@ -1898,6 +1907,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