From febd94cc777fa5925351d8ec703e9d0220d33cf8 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 00:15:12 -0800 Subject: [PATCH 1/4] AutoStory: action registry, shared built-in actions and the step runner --- .../Engine/Pokemon_StoryActionRegistry.cpp | 186 +++++++++ .../Engine/Pokemon_StoryActionRegistry.h | 94 +++++ .../Engine/Pokemon_StoryBuiltinActions.cpp | 189 +++++++++ .../Engine/Pokemon_StoryBuiltinActions.h | 54 +++ .../Engine/Pokemon_StoryEngine_Tests.cpp | 367 ++++++++++++++++++ .../Engine/Pokemon_StoryEngine_Tests.h | 26 ++ .../Engine/Pokemon_StoryFakeBackend.cpp | 99 +++++ .../Engine/Pokemon_StoryFakeBackend.h | 88 +++++ .../Engine/Pokemon_StoryStepRunner.cpp | 89 +++++ .../Engine/Pokemon_StoryStepRunner.h | 61 +++ .../AutoStory/Pokemon_AutoStory_Tests.h | 2 + SerialPrograms/cmake/SourceFiles.cmake | 10 + 12 files changed, 1265 insertions(+) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBuiltinActions.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBuiltinActions.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.cpp new file mode 100644 index 0000000000..3f09cfaeb6 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.cpp @@ -0,0 +1,186 @@ +/* Story Action Registry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_MapUtil.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "Pokemon_StoryActionRegistry.h" +#include "Pokemon_StoryBuiltinActions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// A walk of no legs, or a leg of no tiles. +inline std::vector leg_problems(const StoryActionArgs& args){ + const std::vector* legs = value_if_at_it>(args, args.find("legs")); + if (legs == nullptr){ + return {}; + } + std::vector problems; + if (legs->empty()){ + problems.emplace_back("no legs"); + } + for (const StoryLeg& leg : *legs){ + if (leg.tiles <= 0){ + problems.emplace_back("a leg of no tiles"); + } + } + return problems; +} + + +// Why `declared` is no pose of a game whose poses are `tile` ones or not. +inline std::string undeclarable(const DeclaredPose& declared, bool tile){ + const std::string name = std::holds_alternative(declared) + ? std::get(declared).map + : std::get(declared).place; + return tile + ? std::format("\"{}\" is a place, but this game's poses are tiles: declare a map, tiles and a facing", name) + : std::format("\"{}\" is a map, but this game has no tiles: declare a place, a spot and a heading", name); +} + +// Whether an arg of `type` only means something on a tile grid. +inline bool tile_arg(StoryArgType type){ + return type == StoryArgType::DIRECTION || type == StoryArgType::LEGS || type == StoryArgType::GRID_POSE; +} + +// Each tile arg among `game`'s own actions, for a game with no tiles. +template +std::vector tile_arg_problems(const StoryGame& game){ + std::vector problems; + if constexpr (!StoryPoseTraits::TILE_MOVES){ + for (const StoryAction& action : game.actions){ + for (const StoryArgSpec& arg : action.spec.args){ + if (tile_arg(arg.type)){ + problems.push_back(std::format( + "action {} takes a tile argument \"{}\", but this game has no tiles", action.spec.name, arg.key + )); + } + } + } + } + return problems; +} + + +} // namespace + + +template +StoryActionRegistry::StoryActionRegistry(const StoryGame& game) + : m_game(game) + , m_actions(builtin_story_handlers()) + , m_game_problems(tile_arg_problems(game)) + , m_pause(game.breakpoints, game.pause_point) +{ + // A game's action replaces the built-in of its kind and name in place, + // so a kind's default stays the built-in one's position. + for (const StoryAction& action : game.actions){ + const auto same = std::find_if(m_actions.begin(), m_actions.end(), [&](const StoryAction& builtin){ + return builtin.spec.kind == action.spec.kind && builtin.spec.name == action.spec.name; + }); + if (same != m_actions.end()){ + *same = action; + }else{ + m_actions.push_back(action); + } + } + for (const StoryAction& action : m_actions){ + m_specs.push_back(action.spec); + } +} + +template +const StoryAction* StoryActionRegistry::find(StoryStepKind kind, std::string_view name) const{ + for (const StoryAction& action : m_actions){ + if (action.spec.kind == kind && (name.empty() || action.spec.name == name)){ + return &action; + } + } + return nullptr; +} + +template +std::vector StoryActionRegistry::check(const StoryStep& step) const{ + if (step.kind == StoryStepKind::GAME && step.action.empty()){ + return {"no action"}; + } + const StoryAction* action = find(step.kind, step.action); + if (action == nullptr){ + return {std::format("unknown action \"{}\" for {}", step.action, story_step_kind_name(step.kind))}; + } + std::vector problems = story_args_errors(action->spec, step.args); + for (std::string& problem : leg_problems(step.args)){ + problems.push_back(std::move(problem)); + } + if constexpr (!StoryPoseTraits::TILE_MOVES){ + for (const auto& [key, value] : step.args){ + if (tile_arg(story_arg_type(value))){ + problems.push_back(std::format("argument \"{}\" is a tile one, but this game has no tiles", key)); + } + } + } + return problems; +} + +template +std::vector StoryActionRegistry::lint(const StoryCheckpoint& checkpoint) const{ + constexpr bool TILE = StoryPoseTraits::TILE_MOVES; + std::vector problems = m_game_problems; + if (checkpoint.id.empty()){ + problems.emplace_back("a checkpoint has no id"); + } + if (checkpoint.start && !check_declared(*checkpoint.start)){ + problems.push_back(std::format("{} start: {}", checkpoint.id, undeclarable(*checkpoint.start, TILE))); + } + std::set names; + for (size_t c = 0; c < checkpoint.steps.size(); c++){ + const StoryStep& step = checkpoint.steps[c]; + const std::string where = std::format("{} step {} {}", checkpoint.id, c + 1, step.name); + if (step.name.empty() || !names.insert(step.name).second){ + problems.push_back(std::format("{}: empty or repeated name", where)); + } + for (const std::string& problem : check(step)){ + problems.push_back(std::format("{}: {}", where, problem)); + } + if (step.pose_after && !check_declared(*step.pose_after)){ + problems.push_back(std::format("{}: declared_after: {}", where, undeclarable(*step.pose_after, TILE))); + } + } + return problems; +} + +template +Outcome StoryActionRegistry::dispatch(StoryBackend& backend, const StoryStep& step, RunState& state) const{ + const StoryAction* action = find(step.kind, step.action); + if (action == nullptr || !action->handler){ + return unsupported_step(step); + } + if (action->spec.console_only && backend.kind() != StoryBackendKind::CONSOLE){ + return outcome_failed(std::string(CONSOLE_ONLY), std::format( + "{} runs only on a console, not on a {} backend", action->spec.name, story_backend_kind_name(backend.kind()) + )); + } + const StoryActionArgs args = with_fallbacks(action->spec, step.args); + return action->handler(backend, StoryActionCall{.step = step, .args = args, .pause = m_pause}, state); +} + + +template class StoryActionRegistry; +template class StoryActionRegistry; + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.h new file mode 100644 index 0000000000..7c2e923acf --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.h @@ -0,0 +1,94 @@ +/* Story Action Registry + * + * From: https://github.com/PokemonAutomation/ + * + * A game's actions, looked up by a step's kind and action name: the + * shared built-ins (Pokemon_StoryBuiltinActions.h) with the game's own on + * top. It checks a step against its action's spec before anything runs, + * and runs a step's action with the spec's fallbacks filled in. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryActionRegistry_H +#define PokemonAutomation_Pokemon_StoryActionRegistry_H + +#include +#include +#include +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryStep.h" +#include "Pokemon_StoryGame.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The failure of a console_only action (StoryActionSpec) on a backend that +// is not a console. Every attempt would fail the same way, so the engine +// does not reload for it. +inline constexpr std::string_view CONSOLE_ONLY = "console_only"; + +// `game`'s actions. `game` must outlive the registry. +template +class StoryActionRegistry{ +public: + explicit StoryActionRegistry(const StoryGame& game); + StoryActionRegistry(const StoryActionRegistry&) = delete; + StoryActionRegistry& operator=(const StoryActionRegistry&) = delete; + + const StoryGame& game() const{ + return m_game; + } + + // Every action's spec, for the JSON reader (read_story_checkpoint()). + const std::vector& specs() const{ + return m_specs; + } + + // What is wrong with `step` before it runs: an action that is not + // registered, args that don't fit its spec, a walk of no legs. + std::vector check(const StoryStep& step) const; + + // check() for each step of `checkpoint`, its step names (none empty, + // none repeated), and its declared poses (its start, each step's + // declared_after): each must be the kind the game's pose type + // declares (check_declared()). In a game with no tiles, a tile arg + // (DIRECTION, LEGS, GRID_POSE) in a step or in one of the game's + // actions fails too. + std::vector lint(const StoryCheckpoint& checkpoint) const; + + // The pause points of this game's run (StoryGame::breakpoints and + // pause_point). Mutable state of the run, not of the game's actions. + StoryPausePoints& pause_points() const{ + return m_pause; + } + + // Runs `step`'s action with its args' fallbacks filled in; a step with + // no registered action fails as unsupported_step(), a console_only + // action on another backend as CONSOLE_ONLY, before any input. + Outcome dispatch(StoryBackend& backend, const StoryStep& step, RunState& state) const; + +private: + // The action of `kind` named `name`; for an empty name, the kind's + // first. Null when there is none. + const StoryAction* find(StoryStepKind kind, std::string_view name) const; + + const StoryGame& m_game; + std::vector> m_actions; + std::vector m_specs; + // What is wrong with the game's own actions, reported with every lint. + std::vector m_game_problems; + mutable StoryPausePoints m_pause; +}; + +// Instantiated once, in Pokemon_StoryActionRegistry.cpp. +extern template class StoryActionRegistry; +// And for ZonePose (Pokemon_ZonePose.h). +extern template class StoryActionRegistry; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBuiltinActions.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBuiltinActions.cpp new file mode 100644 index 0000000000..63ca85527d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBuiltinActions.cpp @@ -0,0 +1,189 @@ +/* Story Builtin Actions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Pokemon_StoryBuiltinActions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// Looks before a text or scene counts as stuck. +inline constexpr size_t MAX_TEXT_LOOKS = 80; +// Looks for a text box to open after a talk's A. +inline constexpr size_t MAX_OPEN_LOOKS = 20; +// A press through text or an answer: held, then released before the next +// look, the same for every text press so they read alike in the log. +inline constexpr std::chrono::milliseconds TEXT_PRESS_HOLD{80}; +inline constexpr std::chrono::milliseconds TEXT_PRESS_RELEASE{120}; + + +// The action of a built-in that needs the game's own code. +template +StoryActionHandler needs_game(std::string name){ + return [name = std::move(name)](StoryBackend&, const StoryActionCall&, RunState&){ + return outcome_failed( + "unsupported_step", + std::format("{} needs the game's own action: register one named \"{}\" in StoryGame::actions", name, name) + ); + }; +} + +// The SAVE step outside StoryEngine. +template +Outcome needs_engine_save(StoryBackend&, const StoryActionCall&, RunState&){ + return outcome_failed("unsupported_step", "a SAVE step runs through StoryEngine, which calls StoryGame::save"); +} + +// Presses A through text and scenes until the player can move. +template +Outcome mash_to_overworld(StoryBackend& backend){ + using namespace std::chrono_literals; + for (size_t c = 0; c < MAX_TEXT_LOOKS; c++){ + const Observation now = backend.observe(); + if (now.events.has(ScreenEvent::PLAYER_CAN_MOVE) && !now.events.has(ScreenEvent::DIALOG_BOX)){ + return outcome_ok(); + } + backend.press(NintendoSwitch::BUTTON_A, TEXT_PRESS_HOLD, TEXT_PRESS_RELEASE); + } + return outcome_failed("mash_no_overworld", std::format("no overworld after {} looks", MAX_TEXT_LOOKS)); +} + +template +Outcome mash(StoryBackend& backend, const StoryActionCall&, RunState&){ + return mash_to_overworld(backend); +} + +// A at what the player faces must open a text box; then text to the +// overworld. No box is a failure: nobody was there to talk to. +template +Outcome talk(StoryBackend& backend, const StoryActionCall&, RunState&){ + using namespace std::chrono_literals; + backend.press(NintendoSwitch::BUTTON_A, TEXT_PRESS_HOLD, TEXT_PRESS_RELEASE); + for (size_t c = 0; c < MAX_OPEN_LOOKS; c++){ + if (backend.observe().events.has(ScreenEvent::DIALOG_BOX)){ + return mash_to_overworld(backend); + } + backend.wait(100ms); + } + return outcome_failed("talk_no_text", "A opened no text box"); +} + +// Where `legs` leave a run that stood on one tile; nothing otherwise. +inline std::optional after_legs(const Pose& start, const std::vector& legs){ + const std::vector tiles = tiles_of(start); + if (tiles.size() != 1 || legs.empty()){ + return std::nullopt; + } + TilePos tile = tiles[0]; + for (const StoryLeg& leg : legs){ + for (int c = 0; c < leg.tiles; c++){ + tile = tile.next(leg.direction); + } + } + return tile_pose(start.map, {tile}, legs.back().direction); +} + +template +Outcome walk_legs(StoryBackend& backend, const StoryActionCall& call, RunState& state){ + const std::vector& legs = story_arg>(call.args, "legs"); + const std::vector start = tiles_of(state.pose); + std::optional tile = start.size() == 1 ? std::optional(start[0]) : std::nullopt; + for (size_t index = 0; index < legs.size(); index++){ + const StoryLeg& leg = legs[index]; + for (int c = 0; tile && c < leg.tiles; c++){ + tile = tile->next(leg.direction); + } + call.pause.before_leg(story_leg_pause_label(index, legs.size(), leg.direction, leg.tiles, tile)); + backend.scope().throw_if_cancelled(); + for (int c = 0; c < leg.tiles; c++){ + backend.tap(leg.direction); + } + } + return outcome_ok(after_legs(state.pose, legs)); +} + +template +Outcome face(StoryBackend& backend, const StoryActionCall& call, RunState&){ + backend.tap(story_arg(call.args, "direction")); + return outcome_ok(); +} + +template +Outcome answer(StoryBackend& backend, const StoryActionCall& call, RunState&){ + using namespace std::chrono_literals; + backend.press(story_arg(call.args, "yes") ? NintendoSwitch::BUTTON_A : NintendoSwitch::BUTTON_B, TEXT_PRESS_HOLD, TEXT_PRESS_RELEASE); + return outcome_ok(); +} + +template +Outcome fight(StoryBackend& backend, const StoryActionCall& call, RunState&){ + return backend.battle(call.args); +} + +// The built-in action named `name`, or the hook for a game's own. Null +// for a tile action ("legs", "face") of a pose type with no tiles: the +// game has no such action, so a step naming one fails the lint. +template +StoryActionHandler builtin_handler(std::string_view name){ + std::map, std::less<>> handlers{ + {"answer", &answer}, + {"fight", &fight}, + }; + if constexpr (StoryPoseTraits::TILE_MOVES){ + handlers.emplace("legs", &walk_legs); + handlers.emplace("face", &face); + }else{ + if (name == "legs" || name == "face"){ + return nullptr; + } + } + const auto it = handlers.find(name); + return it != handlers.end() ? it->second : needs_game(std::string(name)); +} + + +} // namespace + + +template +std::vector> builtin_story_handlers(){ + std::vector> actions; + for (const StoryActionSpec& spec : builtin_story_actions()){ + StoryActionHandler handler = builtin_handler(spec.name); + if (handler){ + actions.push_back({.spec = spec, .handler = std::move(handler)}); + } + } + actions.push_back({.spec = {.kind = StoryStepKind::TALK, .name = "talk", .args = {}}, .handler = &talk}); + actions.push_back({.spec = {.kind = StoryStepKind::MASH, .name = "mash", .args = {}}, .handler = &mash}); + // StoryEngine replaces it: the engine owns the save, to hold it back + // while a checkpoint is under test. + actions.push_back({ + .spec = {.kind = StoryStepKind::SAVE, .name = "save", .args = {}}, + .handler = needs_engine_save, + }); + return actions; +} + +template std::vector> builtin_story_handlers(); +template std::vector> builtin_story_handlers(); + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBuiltinActions.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBuiltinActions.h new file mode 100644 index 0000000000..f16b838786 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryBuiltinActions.h @@ -0,0 +1,54 @@ +/* Story Builtin Actions + * + * From: https://github.com/PokemonAutomation/ + * + * The code of the shared built-in actions, written once against the + * backend, so every game and both backends do them the same way: + * + * legs LEGS a tap per tile; the pose moves along when it was one tile + * face STEP a tap in `direction` + * (legs and face only for a pose type with tile moves, + * StoryPoseTraits::TILE_MOVES; elsewhere a step naming + * them fails the lint) + * answer ANSWER A for yes, B for no + * talk TALK A, then a text box must open, then text to the overworld + * mash MASH text until the player can move + * fight BATTLE the backend's battle + * save SAVE StoryEngine's: the game's save (StoryGame::save) as + * the checkpoint's phase allows; outside the engine it + * fails as "unsupported_step" + * + * route, ready, train and shop need a game's map, planner or menus: their + * built-in action fails as "unsupported_step" naming the hook, and a game + * that has them registers an action of the same kind and name in + * StoryGame::actions, which replaces the built-in one. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryBuiltinActions_H +#define PokemonAutomation_Pokemon_StoryBuiltinActions_H + +#include +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" +#include "Pokemon_StoryGame.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The built-in actions, in the order a kind's default comes first: the +// specs of builtin_story_actions() (Pokemon_BuiltinStoryActions.h), then +// talk, mash and save, which take no args. +template +std::vector> builtin_story_handlers(); + +// Instantiated once, in Pokemon_StoryBuiltinActions.cpp. +extern template std::vector> builtin_story_handlers(); +// And for ZonePose (Pokemon_ZonePose.h). +extern template std::vector> builtin_story_handlers(); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp new file mode 100644 index 0000000000..a61824e09d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp @@ -0,0 +1,367 @@ +/* Story Engine Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The engine's lower layers on a scripted backend: the action registry + * (lint and dispatch, a game's action replacing a built-in), the step + * runner (skip_if from flags and readers, the declared end pose, the + * "[Step]" line), and the worked example of a game action, take_warp. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "Pokemon_StoryActionRegistry.h" +#include "Pokemon_StoryFakeBackend.h" +#include "Pokemon_StoryStepRunner.h" +#include "Pokemon_StoryEngine_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +using namespace std::chrono_literals; + + +// One look: `events`, standing on `pose` if given. +Observation look(std::initializer_list events, std::optional pose = std::nullopt){ + Observation observation; + observation.events = ScreenEvents(events); + observation.pose = std::move(pose); + return observation; +} + +GridPose on_map(std::string map){ + return GridPose{.map = std::move(map), .tiles = {}, .facing = std::nullopt}; +} + +std::string joined(const std::vector& items){ + std::string text; + for (const std::string& item : items){ + text += (text.empty() ? "" : ", ") + item; + } + return text; +} + +bool has_line(const FakeStoryBackend& backend, std::string_view line){ + for (const std::string& each : backend.lines()){ + if (each == line){ + return true; + } + } + return false; +} + + +// The worked example of a game's own action: a door or stairs warp. A +// warp is a fade out, then a fade in on the target's map. No fade is not +// "arrived": FRLG 00.31 (console B, 2026-11-10) took it so and saved on +// the wrong floor. +Outcome take_warp(StoryBackend& backend, const StoryActionCall& call, RunState&){ + const Direction direction = story_arg(call.args, "direction"); + const GridPose& to = story_arg(call.args, "to"); + backend.hold(direction, 400ms, StoryPace::WALK); + bool faded = false; + for (size_t c = 0; c < 40; c++){ + const Observation now = backend.observe(); + if (now.events.has(ScreenEvent::FADE_BLACK)){ + faded = true; + }else if (faded && now.pose && now.pose->map == to.map){ + return outcome_ok(pose_of(*now.pose)); + } + backend.wait(100ms); + } + return outcome_failed(faded ? "warp_wrong_map" : "warp_no_fade"); +} + +// A game with take_warp, a route of its own (one hold north) and a +// reader "door_open" that reads `door_open`. +StoryGame test_game(std::optional door_open = std::nullopt){ + StoryGame game; + game.id = "test"; + game.actions.push_back({ + .spec = {.kind = StoryStepKind::GAME, .name = "take_warp", .args = { + {.key = "direction", .type = StoryArgType::DIRECTION, .required = true, .fallback = std::nullopt, .why = "into the door"}, + {.key = "to", .type = StoryArgType::GRID_POSE, .required = true, .fallback = std::nullopt, .why = "the warp's end"}, + }}, + .handler = &take_warp, + }); + game.actions.push_back({ + .spec = *find_story_action(builtin_story_actions(), StoryStepKind::ROUTE, "route"), + .handler = [](StoryBackend& backend, const StoryActionCall&, RunState&){ + backend.hold(Direction::NORTH, 100ms, StoryPace::RUN); + return outcome_ok(); + }, + }); + if (door_open){ + game.readers.push_back({ + .name = "door_open", .supplies = {"door_open"}, .use = StoryReaderUse::ON_REQUEST, .console_only = false, + .read = [value = *door_open](StoryBackend&, Observation& observation){ + observation.readings["door_open"] = value; + }, + }); + } + return game; +} + +StoryStep make_step(StoryStepKind kind, std::string action, StoryActionArgs args){ + StoryStep step; + step.kind = kind; + step.name = "s"; + step.action = std::move(action); + step.args = std::move(args); + return step; +} + + + +struct RegistryCase{ + // A step checked and, when it lints clean, dispatched on a backend that + // shows talk text once, then the overworld. + struct Input{ + StoryStep step; + }; + + // The lint errors joined by "; ", then (for a clean step) the failure and + // the inputs sent. + struct Expectation{ + std::string_view lint = {}; + std::string_view failure = {}; + std::string_view inputs = {}; + }; + + std::string_view name; + Input input; + Expectation expectation; +}; + +const RegistryCase REGISTRY_CASES[] = { + {.name = "legs tap each tile", .input = {.step = make_step(StoryStepKind::LEGS, "", {{"legs", std::vector{{Direction::NORTH, 2}, {Direction::EAST, 1}}}})}, + .expectation = {.inputs = "tap north, tap north, tap east"}}, + {.name = "legs empty", .input = {.step = make_step(StoryStepKind::LEGS, "", {{"legs", std::vector{}}})}, + .expectation = {.lint = "no legs"}}, + {.name = "face without direction", .input = {.step = make_step(StoryStepKind::STEP, "face", {})}, + .expectation = {.lint = "missing argument \"direction\" (the way to step or face)"}}, + {.name = "unknown game action", .input = {.step = make_step(StoryStepKind::GAME, "take_wrap", {})}, + .expectation = {.lint = "unknown action \"take_wrap\" for GAME"}}, + {.name = "talk", .input = {.step = make_step(StoryStepKind::TALK, "", {})}, + .expectation = {.inputs = "press A, press A"}}, + {.name = "answer no", .input = {.step = make_step(StoryStepKind::ANSWER, "", {{"yes", false}})}, + .expectation = {.inputs = "press B"}}, + {.name = "battle", .input = {.step = make_step(StoryStepKind::BATTLE, "", {})}, + .expectation = {.inputs = "battle"}}, + {.name = "ready needs the game", .input = {.step = make_step(StoryStepKind::READY, "", {{"target", on_map("CeruleanCity")}})}, + .expectation = {.failure = "unsupported_step"}}, + {.name = "game route replaces the built-in", .input = {.step = make_step(StoryStepKind::ROUTE, "", {{"target", on_map("Route4")}})}, + .expectation = {.inputs = "hold north 100ms run"}}, + {.name = "save without the game's save", .input = {.step = make_step(StoryStepKind::SAVE, "", {})}, + .expectation = {.failure = "unsupported_step"}}, +}; + +std::string check_registry(const RegistryCase& test, CancellableScope& scope){ + const StoryGame game = test_game(); + const StoryActionRegistry registry(game); + std::vector lint = registry.check(test.input.step); + if (joined(lint) != test.expectation.lint){ + return std::format("expected lint \"{}\", got \"{}\"", test.expectation.lint, joined(lint)); + } + if (!lint.empty()){ + return ""; + } + FakeStoryBackend backend({.looks = {look({ScreenEvent::DIALOG_BOX}), look({ScreenEvent::DIALOG_BOX}), look({ScreenEvent::PLAYER_CAN_MOVE})}}, scope); + RunState state; + const Outcome outcome = registry.dispatch(backend, test.input.step, state); + if (outcome.failure != test.expectation.failure){ + return std::format("expected failure \"{}\", got \"{}\"", test.expectation.failure, to_string(outcome)); + } + if (joined(backend.inputs()) != test.expectation.inputs){ + return std::format("expected inputs \"{}\", got \"{}\"", test.expectation.inputs, joined(backend.inputs())); + } + return ""; +} + +class StoryActionRegistryTest : public UnitTest{ +public: + explicit StoryActionRegistryTest(RegistryCase test) + : UnitTest(std::format("Pokemon::StoryEngine registry - {}", test.name)) + , m_case(std::move(test)) + {} + virtual UnitTestResult run(Logger&, CancellableScope& scope) const override{ + const std::string error = check_registry(m_case, scope); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } +private: + RegistryCase m_case; +}; + + + +struct RunnerCase{ + // One step, read from JSON, run by the step runner on a backend that + // shows the overworld, with `flags` set and the "door_open" reader + // reading `door_open`. + struct Input{ + std::string_view step; + std::vector flags = {}; + std::optional door_open = std::nullopt; + }; + + // The failure, a line the run logged and the map of the outcome's pose. + struct Expectation{ + std::string_view failure = {}; + std::string_view line = {}; + std::string_view pose_map = {}; + }; + + std::string_view name; + Input input; + Expectation expectation; +}; + +const RunnerCase RUNNER_CASES[] = { + {.name = "skip_if a flag", .input = {.step = R"({"id": "s", "kind": "talk", "skip_if": ["got_candy"]})", .flags = {"got_candy"}}, + .expectation = {.line = "[Step] s TALK/default: skipped"}}, + {.name = "skip_if a reader", .input = {.step = R"({"id": "s", "kind": "talk", "skip_if": ["door_open"]})", .door_open = 1}, + .expectation = {.line = "[Step] s TALK/default: skipped"}}, + {.name = "skip_if a reader that says no", .input = {.step = R"({"id": "s", "kind": "scene", "skip_if": ["door_open"]})", .door_open = 0}, + .expectation = {.line = "[Step] s MASH/default: ok"}}, + {.name = "skip_if nobody answers", .input = {.step = R"({"id": "s", "kind": "scene", "skip_if": ["door_open"]})"}, + .expectation = {.line = "[Step] s MASH/default: ok"}}, + {.name = "declared end pose", .input = {.step = R"({"id": "s", "kind": "scene", "declared_after": {"map": "Route1", "tiles": [[1, 2]]}})"}, + .expectation = {.line = "[Step] s MASH/default: ok", .pose_map = "Route1"}}, + {.name = "talk to nobody fails", .input = {.step = R"({"id": "s", "kind": "talk"})"}, + .expectation = {.failure = "talk_no_text", .line = "[Step] s TALK/default: failed: talk_no_text: A opened no text box (class=screen_unread)"}}, +}; + +std::string check_runner(const RunnerCase& test, CancellableScope& scope){ + const StoryGame game = test_game(test.input.door_open); + const StoryActionRegistry registry(game); + FakeStoryBackend backend({.looks = {look({ScreenEvent::PLAYER_CAN_MOVE})}}, scope); + StoryStepRunner runner(registry, backend); + RunState state; + state.flags.insert(test.input.flags.begin(), test.input.flags.end()); + const StoryStep step = read_story_step(parse_json(std::string(test.input.step)), test.name, registry.specs()); + const Outcome outcome = runner.run(step, state); + if (outcome.failure != test.expectation.failure){ + return std::format("expected failure \"{}\", got \"{}\"", test.expectation.failure, to_string(outcome)); + } + if (!has_line(backend, test.expectation.line)){ + return std::format("expected the line \"{}\", logged: {}", test.expectation.line, joined(backend.lines())); + } + const std::string map = outcome.pose ? outcome.pose->map : ""; + if (map != test.expectation.pose_map){ + return std::format("expected the pose on \"{}\", got \"{}\"", test.expectation.pose_map, map); + } + return ""; +} + +class StoryStepRunnerTest : public UnitTest{ +public: + explicit StoryStepRunnerTest(RunnerCase test) + : UnitTest(std::format("Pokemon::StoryEngine runner - {}", test.name)) + , m_case(std::move(test)) + {} + virtual UnitTestResult run(Logger&, CancellableScope& scope) const override{ + const std::string error = check_runner(m_case, scope); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } +private: + RunnerCase m_case; +}; + + + +struct WarpCase{ + // take_warp north to B3F, from B4F, on a scripted game. + struct Input{ + std::vector> looks; + }; + + // How take_warp ended: "" for arrived. + struct Expectation{ + std::string_view failure = {}; + }; + + std::string_view name; + Input input; + Expectation expectation; +}; + +const WarpCase WARP_CASES[] = { + {.name = "fade then B3F", .input = { .looks = { + look({}, on_map("RocketHideout_B4F")), look({ScreenEvent::FADE_BLACK}), look({ScreenEvent::PLAYER_CAN_MOVE}, on_map("RocketHideout_B3F")), + }}, .expectation = {}}, + // The screen darkens at the stairs but no fade starts and the map + // stays B4F: the old wait took this for arrived (00.31's false pass). + {.name = "black_without_warp", .input = {.looks = {look({ScreenEvent::SCREEN_STILL}, on_map("RocketHideout_B4F"))}}, + .expectation = {.failure = "warp_no_fade"}}, + {.name = "fade back to B4F", .input = {.looks = {look({ScreenEvent::FADE_BLACK}), look({ScreenEvent::PLAYER_CAN_MOVE}, on_map("RocketHideout_B4F"))}}, + .expectation = {.failure = "warp_wrong_map"}}, +}; + +std::string check_warp(const WarpCase& test, CancellableScope& scope){ + const StoryGame game = test_game(); + const StoryActionRegistry registry(game); + FakeStoryBackend backend({.looks = test.input.looks}, scope); + StoryStepRunner runner(registry, backend); + RunState state; + const StoryStep step = make_step(StoryStepKind::GAME, "take_warp", { + {"direction", Direction::NORTH}, + {"to", on_map("RocketHideout_B3F")}, + }); + const Outcome outcome = runner.run(step, state); + if (outcome.failure != test.expectation.failure){ + return std::format("expected \"{}\", got \"{}\"", test.expectation.failure, to_string(outcome)); + } + if (outcome.succeeded() && (!outcome.pose || outcome.pose->map != "RocketHideout_B3F")){ + return "expected the pose on RocketHideout_B3F"; + } + return ""; +} + +class StoryTakeWarpTest : public UnitTest{ +public: + explicit StoryTakeWarpTest(WarpCase test) + : UnitTest(std::format("Pokemon::StoryEngine take_warp - {}", test.name)) + , m_case(std::move(test)) + {} + virtual UnitTestResult run(Logger&, CancellableScope& scope) const override{ + const std::string error = check_warp(m_case, scope); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } +private: + WarpCase m_case; +}; + + +} // namespace + + +void add_tests_StoryEngine(UnitTestDatabase& database){ + for (const RegistryCase& test : REGISTRY_CASES){ + database.add(test); + } + for (const RunnerCase& test : RUNNER_CASES){ + database.add(test); + } + for (const WarpCase& test : WARP_CASES){ + database.add(test); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.h new file mode 100644 index 0000000000..bacd91cf40 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.h @@ -0,0 +1,26 @@ +/* Story Engine Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The unit tests of the action registry, the step runner and the + * take_warp example (Pokemon/AutoStory/Engine). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryEngine_Tests_H +#define PokemonAutomation_Pokemon_StoryEngine_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the action registry, the step runner and the take_warp example. +void add_tests_StoryEngine(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.cpp new file mode 100644 index 0000000000..e1031273ae --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.cpp @@ -0,0 +1,99 @@ +/* Story Fake Backend + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Pokemon_StoryFakeBackend.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// "walk" or "run". +std::string_view pace_name(StoryPace pace){ + return pace == StoryPace::RUN ? "run" : "walk"; +} + + +} // namespace + + +template +FakeStoryBackend::FakeStoryBackend(FakeStoryScript script, CancellableScope& scope) + : m_script(std::move(script)) + , m_scope(scope) +{} + +template +StoryBackendKind FakeStoryBackend::kind() const{ + return m_script.kind; +} + +template +void FakeStoryBackend::press(NintendoSwitch::Button button, Milliseconds, Milliseconds){ + m_inputs.push_back(std::format("press {}", NintendoSwitch::button_to_string(button))); +} + +template +void FakeStoryBackend::tap(Direction direction){ + m_inputs.push_back(std::format("tap {}", direction_name(direction))); +} + +template +void FakeStoryBackend::hold(Direction direction, Milliseconds duration, StoryPace pace){ + m_inputs.push_back(std::format("hold {} {}ms {}", direction_name(direction), duration.count(), pace_name(pace))); +} + +template +void FakeStoryBackend::stick(double degrees, Milliseconds duration, Milliseconds release, StoryPace pace){ + std::string input = std::format("stick {}deg {}ms {}", degrees, duration.count(), pace_name(pace)); + if (release > Milliseconds::zero()){ + input += std::format(", release {}ms", release.count()); + } + m_inputs.push_back(std::move(input)); +} + +template +void FakeStoryBackend::wait(Milliseconds duration){ + m_inputs.push_back(std::format("wait {}ms", duration.count())); +} + +template +Observation FakeStoryBackend::observe(){ + if (m_script.looks.empty()){ + return {}; + } + const size_t look = m_next_look < m_script.looks.size() ? m_next_look++ : m_script.looks.size() - 1; + return m_script.looks[look]; +} + +template +Outcome FakeStoryBackend::battle(const StoryActionArgs&){ + m_inputs.push_back("battle"); + return m_script.battle; +} + +template +void FakeStoryBackend::log(std::string_view line){ + m_lines.emplace_back(line); +} + +template +CancellableScope& FakeStoryBackend::scope(){ + return m_scope; +} + + +template class FakeStoryBackend; +template class FakeStoryBackend; + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.h new file mode 100644 index 0000000000..68efc50d67 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.h @@ -0,0 +1,88 @@ +/* Story Fake Backend + * + * From: https://github.com/PokemonAutomation/ + * + * A scripted game for engine tests, with no console and no model: each + * observe() returns the script's next look (the last one repeats), every + * input and log line is recorded, and a battle ends as scripted. A fault + * is a script: "black_without_warp" is a door that dims the screen and + * never warps. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryFakeBackend_H +#define PokemonAutomation_Pokemon_StoryFakeBackend_H + +#include +#include +#include +#include +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" +#include "Pokemon_StoryBackend.h" +#include "Pokemon_ZonePose.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What a FakeStoryBackend shows and does. +template +struct FakeStoryScript{ + // observe()'s answers in order; the last repeats. None: an empty look. + std::vector> looks = {}; + // How each battle ends. + Outcome battle = outcome_ok(); + // What it says it plays on: SCRIPT, or CONSOLE to run a console_only + // action's code in a test. + StoryBackendKind kind = StoryBackendKind::SCRIPT; +}; + +// The backend of the engine's unit tests and of executor-level sim tests +// that only need a script, for any pose type. +// code-health: allow public_methods -- the backend calls it fakes plus the two recordings tests read; nothing to split +template +class FakeStoryBackend : public StoryBackend{ +public: + FakeStoryBackend(FakeStoryScript script, CancellableScope& scope); + + // Each input, in order: "press A", "press +" (by button_to_string()), + // "tap north", "hold east 400ms walk", "stick 90deg 150ms walk", + // "stick 90deg 150ms walk, release 300ms" (a release only when not + // zero), "wait 100ms", "battle". + const std::vector& inputs() const{ + return m_inputs; + } + // Each log line, in order. + const std::vector& lines() const{ + return m_lines; + } + + virtual StoryBackendKind kind() const override; + virtual void press(NintendoSwitch::Button button, Milliseconds hold, Milliseconds release) override; + virtual void tap(Direction direction) override; + virtual void hold(Direction direction, Milliseconds duration, StoryPace pace) override; + virtual void stick(double degrees, Milliseconds duration, Milliseconds release, StoryPace pace) override; + virtual void wait(Milliseconds duration) override; + virtual Observation observe() override; + virtual Outcome battle(const StoryActionArgs& args) override; + virtual void log(std::string_view line) override; + virtual CancellableScope& scope() override; + +private: + FakeStoryScript m_script; + CancellableScope& m_scope; + size_t m_next_look = 0; + std::vector m_inputs; + std::vector m_lines; +}; + +// Instantiated once, in Pokemon_StoryFakeBackend.cpp. +extern template class FakeStoryBackend; +// And for ZonePose (Pokemon_ZonePose.h). +extern template class FakeStoryBackend; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.cpp new file mode 100644 index 0000000000..300ec4f33c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.cpp @@ -0,0 +1,89 @@ +/* Story Step Runner + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Pokemon/AutoStory/Pokemon_StoryOutcomeClass.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "Pokemon_StoryStepRunner.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// "route/route" or "game_action/take_warp": the step's kind and action. +inline std::string step_label(const StoryStep& step){ + return std::format("{}/{}", story_step_kind_name(step.kind), step.action.empty() ? "default" : step.action); +} + + +} // namespace + + +template +StoryStepRunner::StoryStepRunner(const StoryActionRegistry& registry, StoryBackend& backend) + : m_registry(registry) + , m_backend(backend) +{} + +template +Outcome StoryStepRunner::run(const StoryStep& step, RunState& state){ + bool skip = !step.skip_if.empty(); + for (const std::string& condition : step.skip_if){ + skip = skip && holds(condition, state); + } + if (skip){ + m_backend.log(std::format("[Step] {} {}: skipped", step.name, step_label(step))); + return outcome_unchanged(); + } + return act(step, state); +} + +template +Outcome StoryStepRunner::act(const StoryStep& step, RunState& state){ + m_backend.scope().throw_if_cancelled(); + Outcome outcome = m_registry.dispatch(m_backend, step, state); + if (outcome.succeeded() && !outcome.pose && step.pose_after){ + outcome.pose = pose_of(*step.pose_after); + } + m_backend.log(std::format( + "[Step] {} {}: {}", step.name, step_label(step), + outcome.succeeded() ? "ok" : std::format("failed: {}", to_string_with_class(outcome)) + )); + return outcome; +} + +template +bool StoryStepRunner::holds(std::string_view condition, RunState& state){ + if (state.flags.contains(std::string(condition))){ + return true; + } + for (const StoryGameReader& reader : m_registry.game().readers){ + if (reader.name != condition || !reader.read){ + continue; + } + if (reader.console_only && m_backend.kind() != StoryBackendKind::CONSOLE){ + continue; + } + Observation observation = m_backend.observe(); + reader.read(m_backend, observation); + const auto reading = observation.readings.find(condition); + return reading != observation.readings.end() && reading->second != 0; + } + return false; +} + + +template class StoryStepRunner; +template class StoryStepRunner; + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.h new file mode 100644 index 0000000000..5d0840c3ca --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.h @@ -0,0 +1,61 @@ +/* Story Step Runner + * + * From: https://github.com/PokemonAutomation/ + * + * Runs one story step on a backend: skips it when its skip_if conditions + * hold, runs its action through the registry, writes its declared end + * pose into the outcome, and logs a "[Step]" line. The one step executor + * of every game, on a console or in a simulation; it replaces + * StoryStepExecutor and the games' own executors. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStepRunner_H +#define PokemonAutomation_Pokemon_StoryStepRunner_H + +#include +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryStep.h" +#include "Pokemon_StoryActionRegistry.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Runs steps with `registry`'s actions on `backend`. Both must outlive it. +template +class StoryStepRunner{ +public: + StoryStepRunner(const StoryActionRegistry& registry, StoryBackend& backend); + StoryStepRunner(const StoryStepRunner&) = delete; + StoryStepRunner& operator=(const StoryStepRunner&) = delete; + + // `step`, unless all its skip_if conditions hold (and it has some): + // then it changes nothing and says so. + Outcome run(const StoryStep& step, RunState& state); + + // `step`'s action without the skip_if check, for a caller that checks + // it itself (the event layer): dispatch, then the declared end pose + // when the action gave none, then the "[Step]" line. + Outcome act(const StoryStep& step, RunState& state); + + // Whether `condition` holds: a flag of the run, or else a non-zero + // reading from the game's reader of that name on a fresh observation + // (none from a console_only reader off a console). + bool holds(std::string_view condition, RunState& state); + +private: + const StoryActionRegistry& m_registry; + StoryBackend& m_backend; +}; + +// Instantiated once, in Pokemon_StoryStepRunner.cpp. +extern template class StoryStepRunner; +// And for ZonePose (Pokemon_ZonePose.h). +extern template class StoryStepRunner; + + + +} // 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 ba36f3a546..b549581b3a 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -17,6 +17,7 @@ #include "Data/Pokemon_StoryStepJson_Tests.h" #include "Engine/Pokemon_CoveredWatch_Tests.h" #include "Engine/Pokemon_FrameCoverage_Tests.h" +#include "Engine/Pokemon_StoryEngine_Tests.h" #include "Pokemon_SceneJudges_Tests.h" #include "Pokemon_StoryEvents_Tests.h" #include "Pokemon_StoryFailureClasses_Tests.h" @@ -40,6 +41,7 @@ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_AuthoredCheckpointJson(database); add_tests_CoveredWatch(database); add_tests_FrameCoverage(database); + add_tests_StoryEngine(database); add_tests_StorySegments(database); add_tests_SceneJudges(database); add_tests_StoryFiles(database); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 40df300d2f..50abf05d48 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1478,11 +1478,21 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Engine/Pokemon_FrameCoverage_Tests.h Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionNotImplemented.cpp Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionNotImplemented.h + Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.cpp + Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.h Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend.cpp Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend.h + Source/Pokemon/AutoStory/Engine/Pokemon_StoryBuiltinActions.cpp + Source/Pokemon/AutoStory/Engine/Pokemon_StoryBuiltinActions.h + Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp + Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.h + Source/Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.cpp + Source/Pokemon/AutoStory/Engine/Pokemon_StoryFakeBackend.h Source/Pokemon/AutoStory/Engine/Pokemon_StoryGame.h Source/Pokemon/AutoStory/Engine/Pokemon_StoryPoseConcept.cpp Source/Pokemon/AutoStory/Engine/Pokemon_StoryPoseConcept.h + Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.cpp + Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.h Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.cpp Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.h Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h From 86f3dad15bfb31b1a658d0449a9595054464fd87 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 00:59:42 -0800 Subject: [PATCH 2/4] AutoStory: step runner and engine test comments describe the code, not the run The step runner's header says what it is rather than what it replaced, and the warp test describes the wrong-floor fault instead of the console run that found it. --- .../Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp | 5 ++--- .../Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.h | 5 ++--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp index a61824e09d..c9408c9dc7 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp @@ -67,8 +67,7 @@ bool has_line(const FakeStoryBackend& backend, std::string_view line){ // The worked example of a game's own action: a door or stairs warp. A // warp is a fade out, then a fade in on the target's map. No fade is not -// "arrived": FRLG 00.31 (console B, 2026-11-10) took it so and saved on -// the wrong floor. +// "arrived": a run that takes it so goes on, and saves, on the wrong floor. Outcome take_warp(StoryBackend& backend, const StoryActionCall& call, RunState&){ const Direction direction = story_arg(call.args, "direction"); const GridPose& to = story_arg(call.args, "to"); @@ -304,7 +303,7 @@ const WarpCase WARP_CASES[] = { look({}, on_map("RocketHideout_B4F")), look({ScreenEvent::FADE_BLACK}), look({ScreenEvent::PLAYER_CAN_MOVE}, on_map("RocketHideout_B3F")), }}, .expectation = {}}, // The screen darkens at the stairs but no fade starts and the map - // stays B4F: the old wait took this for arrived (00.31's false pass). + // stays B4F: a wait for a dark screen alone would take this for arrived. {.name = "black_without_warp", .input = {.looks = {look({ScreenEvent::SCREEN_STILL}, on_map("RocketHideout_B4F"))}}, .expectation = {.failure = "warp_no_fade"}}, {.name = "fade back to B4F", .input = {.looks = {look({ScreenEvent::FADE_BLACK}), look({ScreenEvent::PLAYER_CAN_MOVE}, on_map("RocketHideout_B4F"))}}, diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.h index 5d0840c3ca..54c7ed6f1e 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.h @@ -4,9 +4,8 @@ * * Runs one story step on a backend: skips it when its skip_if conditions * hold, runs its action through the registry, writes its declared end - * pose into the outcome, and logs a "[Step]" line. The one step executor - * of every game, on a console or in a simulation; it replaces - * StoryStepExecutor and the games' own executors. + * pose into the outcome, and logs a "[Step]" line. One step executor for + * every game that has a StoryBackend, on a console or in a simulation. * */ From ff8a5cfd2063a30624efd34b0d936285e82c1931 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 01:13:24 -0800 Subject: [PATCH 3/4] AutoStory: the fake backend's inputs and the step an action sees are tested here (moved from the engine PR) --- .../Engine/Pokemon_StoryEngine_Tests.cpp | 93 ++++++++++++++++++- 1 file changed, 92 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp index c9408c9dc7..b09fadc008 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp @@ -5,12 +5,14 @@ * The engine's lower layers on a scripted backend: the action registry * (lint and dispatch, a game's action replacing a built-in), the step * runner (skip_if from flags and readers, the declared end pose, the - * "[Step]" line), and the worked example of a game action, take_warp. + * "[Step]" line), the worked example of a game action, take_warp, and the + * scripted backend's inputs. * */ #include #include +#include #include #include #include @@ -345,6 +347,92 @@ class StoryTakeWarpTest : public UnitTest{ }; + +// The move stick at an angle, and the heading reading; a turn lets +// go of the stick for its release. +std::string stick_and_heading(CancellableScope& scope){ + Observation facing_east; + facing_east.readings[std::string(STORY_HEADING)] = 90; + FakeStoryBackend backend({.looks = {facing_east, {}}}, scope); + backend.stick(45, 150ms, 0ms, StoryPace::WALK); + backend.stick(-90, 300ms, 0ms, StoryPace::RUN); + backend.stick(90, 150ms, 300ms, StoryPace::WALK); + if (story_heading(backend.observe()) != 90){ + return "expected the heading 90"; + } + if (story_heading(backend.observe())){ + return "expected no heading where nothing read it"; + } + const std::string expected = "stick 45deg 150ms walk, stick -90deg 300ms run, stick 90deg 150ms walk, release 300ms"; + const std::string got = joined(backend.inputs()); + return got == expected ? "" : std::format("expected inputs \"{}\", got \"{}\"", expected, got); +} + +// The fake logs each press by the button's name. +std::string buttons_by_name(CancellableScope& scope){ + FakeStoryBackend backend({}, scope); + for (const NintendoSwitch::Button button : { + NintendoSwitch::BUTTON_L, NintendoSwitch::BUTTON_R, NintendoSwitch::BUTTON_PLUS, + NintendoSwitch::BUTTON_A, NintendoSwitch::BUTTON_B, NintendoSwitch::BUTTON_ZL, + }){ + backend.press(button, 80ms, 120ms); + } + const std::string expected = "press L, press R, press +, press A, press B, press ZL"; + const std::string got = joined(backend.inputs()); + return got == expected ? "" : std::format("expected inputs \"{}\", got \"{}\"", expected, got); +} + +// An action sees its step. +std::string handler_sees_step(CancellableScope& scope){ + StoryGame game; + std::shared_ptr seen = std::make_shared(); + game.actions.push_back({ + .spec = {.kind = StoryStepKind::GAME, .name = "scene", .args = {}}, + .handler = [seen](StoryBackend&, const StoryActionCall& call, RunState&){ + *seen = std::format("{} / {}", call.step.name, call.step.why); + return outcome_ok(); + }, + }); + const StoryActionRegistry registry(game); + FakeStoryBackend backend({}, scope); + StoryStep step = make_step(StoryStepKind::GAME, "scene", {}); + step.name = "opening"; + step.why = "the long intro"; + RunState state; + const Outcome outcome = registry.dispatch(backend, step, state); + if (!outcome.succeeded()){ + return std::format("expected a pass, got {}", to_string(outcome)); + } + return *seen == "opening / the long intro" ? "" : std::format("expected the step, got \"{}\"", *seen); +} + +// A named test; it returns its error, empty when it passed. +struct NamedCheck{ + std::string_view name; + std::string (*check)(CancellableScope& scope); +}; + +const NamedCheck NAMED_CHECKS[] = { + {.name = "stick and heading", .check = &stick_and_heading}, + {.name = "buttons by name", .check = &buttons_by_name}, + {.name = "handler sees its step", .check = &handler_sees_step}, +}; + +class StoryEngineCheckTest : public UnitTest{ +public: + explicit StoryEngineCheckTest(NamedCheck test) + : UnitTest(std::format("Pokemon::StoryEngine - {}", test.name)) + , m_case(std::move(test)) + {} + virtual UnitTestResult run(Logger&, CancellableScope& scope) const override{ + const std::string error = m_case.check(scope); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } +private: + NamedCheck m_case; +}; + + } // namespace @@ -358,6 +446,9 @@ void add_tests_StoryEngine(UnitTestDatabase& database){ for (const WarpCase& test : WARP_CASES){ database.add(test); } + for (const NamedCheck& test : NAMED_CHECKS){ + database.add(test); + } } From 40f08f844bbe301b1704ea18e13777d865854be3 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 01:15:40 -0800 Subject: [PATCH 4/4] AutoStory engine tests: the fake backend and the step an action sees as case tables --- .../Engine/Pokemon_StoryEngine_Tests.cpp | 156 +++++++++--------- 1 file changed, 82 insertions(+), 74 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp index b09fadc008..12e1f051ac 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp @@ -12,7 +12,6 @@ #include #include -#include #include #include #include @@ -87,8 +86,8 @@ Outcome take_warp(StoryBackend& backend, const StoryActionCall& call, return outcome_failed(faded ? "warp_wrong_map" : "warp_no_fade"); } -// A game with take_warp, a route of its own (one hold north) and a -// reader "door_open" that reads `door_open`. +// A game with take_warp, a route of its own (one hold north), an action +// that logs its step and a reader "door_open" that reads `door_open`. StoryGame test_game(std::optional door_open = std::nullopt){ StoryGame game; game.id = "test"; @@ -106,6 +105,14 @@ StoryGame test_game(std::optional door_open = std::nullopt){ return outcome_ok(); }, }); + // Logs "[Test] step / ": what an action sees of its step. + game.actions.push_back({ + .spec = {.kind = StoryStepKind::GAME, .name = "echo_step", .args = {}}, + .handler = [](StoryBackend& backend, const StoryActionCall& call, RunState&){ + backend.log(std::format("[Test] step {} / {}", call.step.name, call.step.why)); + return outcome_ok(); + }, + }); if (door_open){ game.readers.push_back({ .name = "door_open", .supplies = {"door_open"}, .use = StoryReaderUse::ON_REQUEST, .console_only = false, @@ -126,6 +133,11 @@ StoryStep make_step(StoryStepKind kind, std::string action, StoryActionArgs args return step; } +StoryStep with_why(StoryStep step, std::string why){ + step.why = std::move(why); + return step; +} + struct RegistryCase{ @@ -135,12 +147,13 @@ struct RegistryCase{ StoryStep step; }; - // The lint errors joined by "; ", then (for a clean step) the failure and - // the inputs sent. + // The lint errors joined by "; ", then (for a clean step) the failure, + // the inputs sent and a line the action logged. struct Expectation{ std::string_view lint = {}; std::string_view failure = {}; std::string_view inputs = {}; + std::string_view line = {}; }; std::string_view name; @@ -167,6 +180,8 @@ const RegistryCase REGISTRY_CASES[] = { .expectation = {.failure = "unsupported_step"}}, {.name = "game route replaces the built-in", .input = {.step = make_step(StoryStepKind::ROUTE, "", {{"target", on_map("Route4")}})}, .expectation = {.inputs = "hold north 100ms run"}}, + {.name = "handler sees its step", .input = {.step = with_why(make_step(StoryStepKind::GAME, "echo_step", {}), "the long intro")}, + .expectation = {.line = "[Test] step s / the long intro"}}, {.name = "save without the game's save", .input = {.step = make_step(StoryStepKind::SAVE, "", {})}, .expectation = {.failure = "unsupported_step"}}, }; @@ -190,6 +205,9 @@ std::string check_registry(const RegistryCase& test, CancellableScope& scope){ if (joined(backend.inputs()) != test.expectation.inputs){ return std::format("expected inputs \"{}\", got \"{}\"", test.expectation.inputs, joined(backend.inputs())); } + if (!test.expectation.line.empty() && !has_line(backend, test.expectation.line)){ + return std::format("expected the line \"{}\", logged: {}", test.expectation.line, joined(backend.lines())); + } return ""; } @@ -348,88 +366,78 @@ class StoryTakeWarpTest : public UnitTest{ -// The move stick at an angle, and the heading reading; a turn lets -// go of the stick for its release. -std::string stick_and_heading(CancellableScope& scope){ - Observation facing_east; - facing_east.readings[std::string(STORY_HEADING)] = 90; - FakeStoryBackend backend({.looks = {facing_east, {}}}, scope); - backend.stick(45, 150ms, 0ms, StoryPace::WALK); - backend.stick(-90, 300ms, 0ms, StoryPace::RUN); - backend.stick(90, 150ms, 300ms, StoryPace::WALK); - if (story_heading(backend.observe()) != 90){ - return "expected the heading 90"; - } - if (story_heading(backend.observe())){ - return "expected no heading where nothing read it"; - } - const std::string expected = "stick 45deg 150ms walk, stick -90deg 300ms run, stick 90deg 150ms walk, release 300ms"; - const std::string got = joined(backend.inputs()); - return got == expected ? "" : std::format("expected inputs \"{}\", got \"{}\"", expected, got); -} -// The fake logs each press by the button's name. -std::string buttons_by_name(CancellableScope& scope){ - FakeStoryBackend backend({}, scope); - for (const NintendoSwitch::Button button : { - NintendoSwitch::BUTTON_L, NintendoSwitch::BUTTON_R, NintendoSwitch::BUTTON_PLUS, - NintendoSwitch::BUTTON_A, NintendoSwitch::BUTTON_B, NintendoSwitch::BUTTON_ZL, - }){ - backend.press(button, 80ms, 120ms); - } - const std::string expected = "press L, press R, press +, press A, press B, press ZL"; - const std::string got = joined(backend.inputs()); - return got == expected ? "" : std::format("expected inputs \"{}\", got \"{}\"", expected, got); -} -// An action sees its step. -std::string handler_sees_step(CancellableScope& scope){ - StoryGame game; - std::shared_ptr seen = std::make_shared(); - game.actions.push_back({ - .spec = {.kind = StoryStepKind::GAME, .name = "scene", .args = {}}, - .handler = [seen](StoryBackend&, const StoryActionCall& call, RunState&){ - *seen = std::format("{} / {}", call.step.name, call.step.why); - return outcome_ok(); - }, - }); - const StoryActionRegistry registry(game); - FakeStoryBackend backend({}, scope); - StoryStep step = make_step(StoryStepKind::GAME, "scene", {}); - step.name = "opening"; - step.why = "the long intro"; - RunState state; - const Outcome outcome = registry.dispatch(backend, step, state); - if (!outcome.succeeded()){ - return std::format("expected a pass, got {}", to_string(outcome)); - } - return *seen == "opening / the long intro" ? "" : std::format("expected the step, got \"{}\"", *seen); -} +struct BackendCase{ + // Inputs sent to a scripted zone backend that shows `looks`, then one + // look per entry of the expected headings. + struct Input{ + std::vector> looks; + void (*drive)(StoryBackend& backend); + }; + + // The inputs the fake recorded, and the heading each look read. + struct Expectation{ + std::string_view inputs; + std::vector> headings = {}; + }; -// A named test; it returns its error, empty when it passed. -struct NamedCheck{ std::string_view name; - std::string (*check)(CancellableScope& scope); + Input input; + Expectation expectation; }; -const NamedCheck NAMED_CHECKS[] = { - {.name = "stick and heading", .check = &stick_and_heading}, - {.name = "buttons by name", .check = &buttons_by_name}, - {.name = "handler sees its step", .check = &handler_sees_step}, +Observation heading_look(int degrees){ + Observation observation; + observation.readings[std::string(STORY_HEADING)] = degrees; + return observation; +} + +const BackendCase BACKEND_CASES[] = { + // A turn lets go of the stick for its release; a look that read no + // heading has none. + {.name = "stick and heading", .input = {.looks = {heading_look(90), {}}, .drive = [](StoryBackend& backend){ + backend.stick(45, 150ms, 0ms, StoryPace::WALK); + backend.stick(-90, 300ms, 0ms, StoryPace::RUN); + backend.stick(90, 150ms, 300ms, StoryPace::WALK); + }}, .expectation = {.inputs = "stick 45deg 150ms walk, stick -90deg 300ms run, stick 90deg 150ms walk, release 300ms", .headings = {90, std::nullopt}}}, + {.name = "buttons by name", .input = {.looks = {}, .drive = [](StoryBackend& backend){ + for (const NintendoSwitch::Button button : { + NintendoSwitch::BUTTON_L, NintendoSwitch::BUTTON_R, NintendoSwitch::BUTTON_PLUS, + NintendoSwitch::BUTTON_A, NintendoSwitch::BUTTON_B, NintendoSwitch::BUTTON_ZL, + }){ + backend.press(button, 80ms, 120ms); + } + }}, .expectation = {.inputs = "press L, press R, press +, press A, press B, press ZL"}}, }; -class StoryEngineCheckTest : public UnitTest{ +std::string check_backend(const BackendCase& test, CancellableScope& scope){ + FakeStoryBackend backend({.looks = test.input.looks}, scope); + test.input.drive(backend); + for (size_t c = 0; c < test.expectation.headings.size(); c++){ + const std::optional heading = story_heading(backend.observe()); + if (heading != test.expectation.headings[c]){ + return std::format("look {}: expected the heading {}, got {}", c, + test.expectation.headings[c] ? std::to_string(*test.expectation.headings[c]) : "none", + heading ? std::to_string(*heading) : "none"); + } + } + const std::string got = joined(backend.inputs()); + return got == test.expectation.inputs ? "" : std::format("expected inputs \"{}\", got \"{}\"", test.expectation.inputs, got); +} + +class StoryFakeBackendTest : public UnitTest{ public: - explicit StoryEngineCheckTest(NamedCheck test) - : UnitTest(std::format("Pokemon::StoryEngine - {}", test.name)) + explicit StoryFakeBackendTest(BackendCase test) + : UnitTest(std::format("Pokemon::StoryEngine fake backend - {}", test.name)) , m_case(std::move(test)) {} virtual UnitTestResult run(Logger&, CancellableScope& scope) const override{ - const std::string error = m_case.check(scope); + const std::string error = check_backend(m_case, scope); return error.empty() ? UnitTestResult(true) : UnitTestResult(error); } private: - NamedCheck m_case; + BackendCase m_case; }; @@ -446,8 +454,8 @@ void add_tests_StoryEngine(UnitTestDatabase& database){ for (const WarpCase& test : WARP_CASES){ database.add(test); } - for (const NamedCheck& test : NAMED_CHECKS){ - database.add(test); + for (const BackendCase& test : BACKEND_CASES){ + database.add(test); } }