From 29440eb25abb65ed86babddf304a8d3f672e0391 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 00:14:37 -0800 Subject: [PATCH 1/2] AutoStory: a checkpoint as story events, outcome classes and tile poses --- .../AutoStory/Pokemon_AutoStory_Tests.h | 2 + .../Pokemon/AutoStory/Pokemon_StoryEvents.cpp | 578 +++++++++++++ .../Pokemon/AutoStory/Pokemon_StoryEvents.h | 74 ++ .../AutoStory/Pokemon_StoryEvents_Tests.cpp | 771 ++++++++++++++++++ .../AutoStory/Pokemon_StoryEvents_Tests.h | 23 + .../AutoStory/Pokemon_StoryOutcomeClass.cpp | 35 + .../AutoStory/Pokemon_StoryOutcomeClass.h | 35 + .../Pokemon/AutoStory/Pokemon_TilePose.cpp | 54 ++ .../Pokemon/AutoStory/Pokemon_TilePose.h | 49 ++ SerialPrograms/cmake/SourceFiles.cmake | 8 + 10 files changed, 1629 insertions(+) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 3b2328fa87..5fa5e61830 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -12,6 +12,7 @@ #define PokemonAutomation_Pokemon_AutoStory_Tests_H #include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon_StoryEvents_Tests.h" #include "Pokemon_StoryFailureClasses_Tests.h" #include "Pokemon_StoryLog_Tests.h" #include "Types/Pokemon_StoryActionArg_Tests.h" @@ -25,6 +26,7 @@ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_StoryActionArg(database); add_tests_StoryLog(database); add_tests_StoryFailureClasses(database); + add_tests_StoryEvents(database); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp new file mode 100644 index 0000000000..1dd6975bff --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp @@ -0,0 +1,578 @@ +/* Story Events + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_StoryOutcomeClass.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string event_log_line(std::string_view checkpoint, size_t number, std::string_view event, std::string_view status){ + return std::format("[Event] {}/{} {}: {}", checkpoint, number, event, status); +} + +std::string checkpoint_log_line(std::string_view checkpoint, std::string_view text){ + return std::format("[Checkpoint] {}: {}", checkpoint, text); +} + +std::string certainty_name(PoseCertainty certainty){ + switch (certainty){ + case PoseCertainty::TILE: + return "tile"; + case PoseCertainty::COLUMN: + return "column"; + case PoseCertainty::ROW: + return "row"; + case PoseCertainty::SET: + return "set"; + case PoseCertainty::UNKNOWN: + return "unknown"; + } + return "?"; +} + +bool certainty_covers(PoseCertainty have, PoseCertainty need){ + switch (need){ + case PoseCertainty::UNKNOWN: + return true; + case PoseCertainty::SET: + return have != PoseCertainty::UNKNOWN; + case PoseCertainty::COLUMN: + case PoseCertainty::ROW: + return have == need || have == PoseCertainty::TILE; + case PoseCertainty::TILE: + return have == PoseCertainty::TILE; + } + return false; +} + +std::string to_string(const Pose& pose){ + std::string text = pose.map.empty() ? "?" : pose.map; + if (pose.where){ + const std::string where = pose.where->describe(); + if (!where.empty()){ + text += std::format(" {}", where); + } + } + return std::format("{} ({})", text, certainty_name(pose.certainty)); +} + + +bool Outcome::succeeded() const{ + return failure.empty(); +} +Outcome outcome_ok(std::optional pose){ + Outcome outcome; + outcome.pose = std::move(pose); + return outcome; +} + +Outcome outcome_unchanged(){ + Outcome outcome; + outcome.changed_nothing = true; + return outcome; +} + +Outcome outcome_failed(std::string failure, std::string detail, std::optional failure_class){ + Outcome outcome; + outcome.failure = std::move(failure); + outcome.detail = std::move(detail); + outcome.failure_class = failure_class; + return outcome; +} +std::string to_string(const Outcome& outcome){ + return outcome.detail.empty() ? outcome.failure : std::format("{}: {}", outcome.failure, outcome.detail); +} + +Outcome outcome_game_not_running(){ + return outcome_failed(std::string(GAME_NOT_RUNNING), "the game is not running: the Switch HOME menu is showing"); +} + +Condition condition(std::string name, Check check){ + return Condition{std::move(name), std::move(check)}; +} + +Condition pose_known(std::string map, PoseCertainty need){ + std::string name = std::format("pose {}{}", certainty_name(need), map.empty() ? "" : std::format(" on {}", map)); + return condition(std::move(name), [map = std::move(map), need](RunState& state){ + return (map.empty() || state.pose.map == map) && certainty_covers(state.pose.certainty, need); + }); +} + +std::string recovery_name(RecoveryKind kind){ + switch (kind){ + case RecoveryKind::WAIT: + return "wait"; + case RecoveryKind::REANCHOR: + return "re-anchor"; + case RecoveryKind::STOP: + return "stop"; + } + return "?"; +} + + +namespace{ + +// Runs an action; if it succeeded knowing where it left the player, that +// becomes the run's pose. +Outcome run_act(Act& act, RunState& state){ + Outcome outcome = act(state); + if (outcome.succeeded() && outcome.pose){ + state.pose = *outcome.pose; + } + return outcome; +} + +// The name of the first condition that does not hold. +std::optional first_failing(std::vector& conditions, RunState& state){ + for (Condition& item : conditions){ + if (!item.check(state)){ + return item.name; + } + } + return std::nullopt; +} + +bool already_done(Event& event, RunState& state){ + return !event.skip_if.empty() && !first_failing(event.skip_if, state); +} + +Outcome check_expects(Event& event, RunState& state){ + std::optional failing = first_failing(event.expect, state); + if (failing){ + return outcome_failed("expect_failed", *failing); + } + if (event.pose_learned){ + state.pose = *event.pose_learned; + } + return outcome_ok(); +} + +Outcome attempt_event(Event& event, RunState& state){ + std::optional failing = first_failing(event.require, state); + if (failing){ + return outcome_failed("require_failed", *failing); + } + Outcome outcome = run_act(event.act, state); + if (!outcome.succeeded()){ + return outcome; + } + return check_expects(event, state); +} + +} // namespace + +void apply_interrupt_pose(InterruptPose effect, Pose& pose){ + switch (effect){ + case InterruptPose::UNCHANGED: + return; + case InterruptPose::WITHIN_SET: + if (pose.certainty != PoseCertainty::UNKNOWN){ + pose.certainty = PoseCertainty::SET; + } + return; + case InterruptPose::LOST: + pose.where.reset(); + pose.certainty = PoseCertainty::UNKNOWN; + return; + } +} + +namespace{ + + +// One event being run, with what it has used up. +struct EventRun{ + Checkpoint& checkpoint; + size_t number; + Event& event; + RunState& state; + EventLogger& log; + std::vector recoveries_used; + size_t interrupts = 0; +}; + +void log_status(const std::string& status, EventRun& run){ + run.log(event_log_line(run.checkpoint.id, run.number, run.event.name, status)); +} + + +// What the interrupts showing after an action ask for. +struct InterruptResult{ + bool fired = false; + ResumePolicy resume = ResumePolicy::RECHECK_EXPECT; + Outcome outcome; +}; + +// The policy that asks for more: STOP over RETRY_EVENT over RECHECK_EXPECT. +ResumePolicy stronger(ResumePolicy x, ResumePolicy y){ + if (x == ResumePolicy::STOP || y == ResumePolicy::STOP){ + return ResumePolicy::STOP; + } + if (x == ResumePolicy::RETRY_EVENT || y == ResumePolicy::RETRY_EVENT){ + return ResumePolicy::RETRY_EVENT; + } + return ResumePolicy::RECHECK_EXPECT; +} + +// Clears every interrupt showing. +InterruptResult clear_interrupts(EventRun& run){ + InterruptResult result; + for (Interrupt& interrupt : run.checkpoint.interrupts){ + if (!interrupt.detect(run.state)){ + continue; + } + run.interrupts++; + log_status(std::format("interrupt: {}", interrupt.name), run); + if (run.interrupts > run.checkpoint.max_interrupts_per_event){ + result.outcome = outcome_failed("too_many_interrupts", interrupt.name); + return result; + } + if (interrupt.handle){ + Outcome handled = run_act(interrupt.handle, run.state); + if (!handled.succeeded()){ + result.outcome = outcome_failed("interrupt_failed", std::format("{}: {}", interrupt.name, to_string(handled))); + return result; + } + } + apply_interrupt_pose(interrupt.pose, run.state.pose); + result.resume = result.fired ? stronger(result.resume, interrupt.resume) : interrupt.resume; + result.fired = true; + } + return result; +} + + +// The next recovery for `failure`, using up one of its attempts. +Recovery* next_recovery(const std::string& failure, EventRun& run){ + std::vector& recoveries = run.event.recoveries; + for (size_t c = 0; c < recoveries.size(); c++){ + Recovery& recovery = recoveries[c]; + if (!recovery.on.empty() && recovery.on != failure){ + continue; + } + if (recovery.kind != RecoveryKind::STOP && run.recoveries_used[c] >= recovery.attempts){ + continue; + } + run.recoveries_used[c]++; + return &recovery; + } + return nullptr; +} + +// Answers `failure` with the event's recoveries. Returns nothing to try the +// event again, or the failure that stops it. A recovery that fails itself +// is answered in turn, so escalation goes on from there. +std::optional recover(Outcome failure, EventRun& run){ + while (true){ + if (failure.failure == GAME_NOT_RUNNING){ + return failure; + } + Recovery* recovery = next_recovery(failure.failure, run); + if (recovery == nullptr){ + return failure; + } + std::string line = std::format("recover: {} ({})", recovery_name(recovery->kind), failure.failure); + log_status(recovery->why.empty() ? line : std::format("{}: {}", line, recovery->why), run); + if (recovery->kind == RecoveryKind::STOP){ + return failure; + } + if (!recovery->prepare){ + return std::nullopt; + } + Outcome prepared = run_act(recovery->prepare, run.state); + if (prepared.succeeded()){ + return std::nullopt; + } + failure = std::move(prepared); + } +} + + +enum class Next{ + DONE, + RETRY, + RECOVER, + STOP, +}; + +// After one attempt: what the interrupts showing and the outcome call for. +// `outcome` becomes the failure to recover from or stop on. +Next after_attempt(EventRun& run, Outcome& outcome){ + InterruptResult interrupted = clear_interrupts(run); + if (!interrupted.outcome.succeeded()){ + outcome = std::move(interrupted.outcome); + return Next::STOP; + } + if (interrupted.fired){ + switch (interrupted.resume){ + case ResumePolicy::STOP: + outcome = outcome_failed("interrupted", "stopped by an interrupt"); + return Next::STOP; + case ResumePolicy::RETRY_EVENT: + return Next::RETRY; + case ResumePolicy::RECHECK_EXPECT: + outcome = check_expects(run.event, run.state); + return outcome.succeeded() ? Next::DONE : Next::RETRY; + } + } + return outcome.succeeded() ? Next::DONE : Next::RECOVER; +} + +// Runs one event to success or to the failure that stops it. +Outcome run_event(EventRun& run){ + log_status("start", run); + for (bool first = true; ; first = false){ + if (!first && already_done(run.event, run.state)){ + log_status("done: already showing", run); + return outcome_ok(); + } + Outcome outcome = attempt_event(run.event, run.state); + Next next = after_attempt(run, outcome); + if (next == Next::DONE){ + log_status("done", run); + return outcome_ok(); + } + if (next == Next::RETRY){ + continue; + } + if (next == Next::RECOVER){ + std::optional stop = recover(std::move(outcome), run); + if (!stop){ + continue; + } + outcome = std::move(*stop); + } + log_status(std::format("failed: {}", to_string_with_class(outcome)), run); + return outcome; + } +} + + +// What the exception being handled says, for a log line, with its class +// when the engine knows it. +std::string current_exception_text(){ + try{ + throw; + }catch (OperationFailedException& e){ + return std::format("{}: {} ({})", e.name(), e.message(), story_failure_class_tag(StoryFailureClass::OPERATION_FAILED)); + }catch (Exception& e){ + return std::format("{}: {}", e.name(), e.message()); + }catch (std::exception& e){ + return e.what(); + }catch (...){ + return "unknown exception"; + } +} + +// run_event(), logging the event and its checkpoint as failed before an +// exception from the game's steps leaves the runner. The exception goes +// on: the game decides what it means. +Outcome run_event_logging_throws(EventRun& run){ + try{ + return run_event(run); + }catch (...){ + const std::string what = current_exception_text(); + log_status(std::format("failed: {}", what), run); + run.log(checkpoint_log_line(run.checkpoint.id, std::format("failed at {} {}: {}", run.number, run.event.name, what))); + throw; + } +} + +CheckpointReport stop_checkpoint(EventLogger& log, const std::string& id, Outcome failure, CheckpointReport& report){ + std::string where = report.failed_event == 0 + ? "" + : std::format(" at {} {}", report.failed_event, report.failed_name); + log(checkpoint_log_line(id, std::format("failed{}: {}", where, to_string_with_class(failure)))); + report.failure = std::move(failure); + return report; +} + +Outcome finish_checkpoint(RunState& state, Checkpoint& checkpoint){ + std::optional failing = first_failing(checkpoint.end, state); + if (failing){ + return outcome_failed("end_failed", *failing); + } + if (!checkpoint.save){ + return outcome_ok(); + } + Outcome saved = run_act(checkpoint.save, state); + return saved.succeeded() ? saved : outcome_failed("save_failed", to_string(saved)); +} + +} // namespace + + +CheckpointReport run_checkpoint(RunState& state, Checkpoint& checkpoint, EventLogger& log){ + CheckpointReport report; + const std::string& id = checkpoint.id; + log(checkpoint_start_line(id, checkpoint.events.size())); + std::optional failing = first_failing(checkpoint.start, state); + if (failing){ + return stop_checkpoint(log, id, outcome_failed("start_failed", *failing), report); + } + for (size_t c = 0; c < checkpoint.events.size(); c++){ + Event& event = checkpoint.events[c]; + EventRun run{checkpoint, c + 1, event, state, log, std::vector(event.recoveries.size(), 0), 0}; + if (already_done(event, state)){ + log_status("skipped", run); + if (event.when_skipped){ + event.when_skipped(state); + } + report.events_skipped++; + continue; + } + report.events_run++; + Outcome outcome = run_event_logging_throws(run); + if (!outcome.succeeded()){ + report.failed_event = c + 1; + report.failed_name = event.name; + return stop_checkpoint(log, id, std::move(outcome), report); + } + } + Outcome finished = finish_checkpoint(state, checkpoint); + if (!finished.succeeded()){ + return stop_checkpoint(log, id, std::move(finished), report); + } + report.completed = true; + log(checkpoint_log_line(id, std::format("done, {} run, {} skipped", report.events_run, report.events_skipped))); + return report; +} + + +namespace{ + +void lint_conditions(const std::string& where, const std::vector& conditions, std::vector& problems){ + for (const Condition& item : conditions){ + if (item.name.empty() || !item.check){ + problems.emplace_back(std::format("{}: a condition without a name or a check", where)); + } + } +} + +void lint_recoveries(const Event& event, std::vector& problems){ + RecoveryKind last = RecoveryKind::WAIT; + for (const Recovery& recovery : event.recoveries){ + if ((int)recovery.kind < (int)last){ + problems.emplace_back(std::format( + "{}: recovery {} after {}", event.name, recovery_name(recovery.kind), recovery_name(last) + )); + } + if (recovery.kind != RecoveryKind::STOP && recovery.attempts == 0){ + problems.emplace_back(std::format("{}: recovery {} with no attempts", event.name, recovery_name(recovery.kind))); + } + last = recovery.kind; + } +} + +void lint_event(const Event& event, std::set& names, std::vector& problems){ + if (event.name.empty()){ + problems.emplace_back("an event without a name"); + }else if (!names.insert(event.name).second){ + problems.emplace_back(std::format("{}: two events with this name", event.name)); + } + if (!event.act){ + problems.emplace_back(std::format("{}: no action", event.name)); + } + lint_conditions(std::format("{} skip_if", event.name), event.skip_if, problems); + lint_conditions(std::format("{} require", event.name), event.require, problems); + lint_conditions(std::format("{} expect", event.name), event.expect, problems); + lint_recoveries(event, problems); +} + +} // namespace + + +std::vector lint_checkpoint(const Checkpoint& checkpoint){ + std::vector problems; + if (checkpoint.id.empty()){ + problems.emplace_back("a checkpoint without an id"); + } + if (checkpoint.events.empty()){ + problems.emplace_back(std::format("{}: no events", checkpoint.id)); + } + std::set names; + for (const Event& event : checkpoint.events){ + lint_event(event, names, problems); + } + for (const Interrupt& interrupt : checkpoint.interrupts){ + if (interrupt.name.empty() || !interrupt.detect){ + problems.emplace_back("an interrupt without a name or a detector"); + } + } + lint_conditions(std::format("{} start", checkpoint.id), checkpoint.start, problems); + lint_conditions(std::format("{} end", checkpoint.id), checkpoint.end, problems); + return problems; +} + + +namespace{ + +std::string names_of(const std::vector& conditions){ + std::string text; + for (const Condition& item : conditions){ + text += (text.empty() ? "" : ", ") + item.name; + } + return text; +} + +void describe_line(const std::string& indent, const std::string& label, const std::string& value, std::string& text){ + if (!value.empty()){ + text += std::format("{}{}: {}\n", indent, label, value); + } +} + +void describe_event(size_t number, const Event& event, std::string& text){ + text += std::format(" event {} {}{}\n", number, event.name, event.why.empty() ? "" : std::format(": {}", event.why)); + describe_line(" ", "skip_if", names_of(event.skip_if), text); + describe_line(" ", "require", names_of(event.require), text); + describe_line(" ", "expect", names_of(event.expect), text); + if (event.pose_learned){ + describe_line(" ", "pose_learned", to_string(*event.pose_learned), text); + } + for (const Recovery& recovery : event.recoveries){ + text += std::format( + " recovery: {} on {}{}{}\n", + recovery_name(recovery.kind), + recovery.on.empty() ? "any failure" : recovery.on, + recovery.kind == RecoveryKind::STOP ? "" : std::format(" x{}", recovery.attempts), + recovery.why.empty() ? "" : std::format(": {}", recovery.why) + ); + } +} + +} // namespace + + +std::string describe(const Checkpoint& checkpoint){ + std::string text = std::format("checkpoint {}: {} events\n", checkpoint.id, checkpoint.events.size()); + describe_line(" ", "start", names_of(checkpoint.start), text); + std::string interrupts; + for (const Interrupt& interrupt : checkpoint.interrupts){ + interrupts += (interrupts.empty() ? "" : ", ") + interrupt.name; + } + describe_line(" ", "interrupts", interrupts, text); + for (size_t c = 0; c < checkpoint.events.size(); c++){ + describe_event(c + 1, checkpoint.events[c], text); + } + describe_line(" ", "end", names_of(checkpoint.end), text); + if (checkpoint.save){ + text += " saves\n"; + } + return text; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h new file mode 100644 index 0000000000..860d7d5f45 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h @@ -0,0 +1,74 @@ +/* Story Events + * + * From: https://github.com/PokemonAutomation/ + * + * A story checkpoint as a list of events. Each event states what must hold + * before it (require), does one thing (act), and checks what the game shows + * afterwards (expect). An event whose effect is already on screen (skip_if) + * is skipped, so resuming a checkpoint after a reload re-checks instead of + * replaying. A failed event is answered by its named recoveries, in order + * of escalation (wait, then re-anchor, then stop), and anything without a + * recovery stops the checkpoint with the event and the reason. + * + * Interrupts (a wild battle, a trainer, a scene) are declared once per + * checkpoint: after each action the runner asks whether one is showing, + * clears it, marks what it did to the pose and resumes as it says. + * + * The run state is the runner's to change. An action that knows where it + * left the player says so in its Outcome, and the runner writes that into + * the pose once the action has succeeded. + * + * Observation and actuation are callables the game supplies, so this file + * knows nothing of any one game or console, and the runner can be tested + * against a scripted world. See docs/design/AutoStory-Event-Model.md. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryEvents_H +#define PokemonAutomation_Pokemon_StoryEvents_H + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon_StoryLog.h" +#include "Pokemon_StoryCheckpointTypes.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The runner's own log lines, beside the checkpoint lines of +// Pokemon_StoryLog.h. One event's line: +// [Event] 00.04/3 talk_mom: start +// [Event] 00.04/3 talk_mom: failed: expect_failed: has_parcel +std::string event_log_line(std::string_view checkpoint, size_t number, std::string_view event, std::string_view status); + +// Any other line about a checkpoint, such as how its run ended: +// [Checkpoint] 00.04: done, 3 run, 0 skipped +// [Checkpoint] 00.04: failed at 2 talk_mom: expect_failed: has_parcel +std::string checkpoint_log_line(std::string_view checkpoint, std::string_view text); + +// Problems an author should fix before running: unnamed or empty events, +// missing actions, recoveries out of escalation order. +std::vector lint_checkpoint(const Checkpoint& checkpoint); + +// A readable dump for review, one line per item: the checkpoint's start, +// interrupts and end by name, each event with its why, its conditions' +// names, its learned pose and its recoveries. Nothing runs. +std::string describe(const Checkpoint& checkpoint); + +// Runs the checkpoint's events in order, from the first. Events whose +// effect is already showing are skipped, so after a reload this resumes. +// Logs each event's start and end through `log`. +CheckpointReport run_checkpoint(RunState& state, Checkpoint& checkpoint, EventLogger& log); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp new file mode 100644 index 0000000000..3b54de788e --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp @@ -0,0 +1,771 @@ +/* Story Events Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The checkpoint runner against a scripted world: a few fields that the + * events' actions change and their checks read, instead of a console. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_StoryEvents_Tests.h" +#include "Pokemon_StoryOutcomeClass.h" +#include "Pokemon_TilePose.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// A small slice of Route 201/202 and the player's house. +struct World{ + std::string map = "Route 202"; + int potions = 0; + bool parcel = false; + bool dialogue_open = false; + bool battle_showing = false; + // Talks that open nothing before the NPC answers (she is wandering). + int talks_before_answer = 0; + // Rows between us and Mom; a talk from a row off reaches nobody. + int rows_off = 0; + // Walks that fail before one gets through. + int walk_failures = 0; + std::vector trace; +}; + +struct Lines{ + std::vector lines; + + EventLogger logger(){ + return [this](const std::string& line){ lines.push_back(line); }; + } + bool has(const std::string& line) const{ + return std::find(lines.begin(), lines.end(), line) != lines.end(); + } + std::string all() const{ + std::string text; + for (const std::string& line : lines){ + text += std::format("\n{}", line); + } + return text; + } +}; + +Event make_event(std::string name, Act act){ + Event event; + event.name = std::move(name); + event.act = std::move(act); + return event; +} + +// The pose, confirmed on a landmark. +Pose anchored(const Pose& pose){ + Pose anchored = pose; + anchored.certainty = PoseCertainty::TILE; + return anchored; +} + +Act record(std::string what, World& world){ + return [&world, what = std::move(what)](RunState&){ + world.trace.push_back(what); + return outcome_ok(); + }; +} + +Condition has_potions(World& world){ + return condition("potions in the Bag", [&world](RunState&){ return world.potions > 0; }); +} + +Condition dialogue_opened(World& world){ + return condition("dialogue opened", [&world](RunState&){ return world.dialogue_open; }); +} + +// The Poke Mart lady: answers once she has wandered back, gives 10 Potions. +Event talk_to_lady(World& world){ + Event event = make_event("talk_poke_mart_lady", [&world](RunState&){ + world.trace.push_back("talk"); + if (world.talks_before_answer > 0){ + world.talks_before_answer--; + return outcome_ok(); + } + world.dialogue_open = true; + world.potions += 10; + return outcome_ok(); + }); + event.skip_if.push_back(has_potions(world)); + event.expect.push_back(dialogue_opened(world)); + return event; +} + +Recovery recovery(std::string on, RecoveryKind kind, size_t attempts, Act prepare = nullptr){ + Recovery recovery; + recovery.on = std::move(on); + recovery.kind = kind; + recovery.attempts = attempts; + recovery.prepare = std::move(prepare); + return recovery; +} + +Checkpoint make_checkpoint(){ + Checkpoint checkpoint; + checkpoint.id = "00.04"; + return checkpoint; +} + + +UnitTestResult test_runs_events_in_order(){ + World world; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(make_event("walk_to_corner", record("walk", world))); + checkpoint.events.push_back(make_event("talk_lady", record("talk", world))); + checkpoint.events.push_back(make_event("save", record("save", world))); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + const std::vector expected = { + "[Checkpoint] 00.04: start, 3 events", + "[Event] 00.04/1 walk_to_corner: start", + "[Event] 00.04/1 walk_to_corner: done", + "[Event] 00.04/2 talk_lady: start", + "[Event] 00.04/2 talk_lady: done", + "[Event] 00.04/3 save: start", + "[Event] 00.04/3 save: done", + "[Checkpoint] 00.04: done, 3 run, 0 skipped", + }; + if (!report.completed || lines.lines != expected){ + return std::format("Unexpected log:{}", lines.all()); + } + if (world.trace != std::vector{"walk", "talk", "save"}){ + return "Events ran out of order."; + } + return true; +} + +UnitTestResult test_skips_done_event(){ + World world; + world.potions = 10; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(talk_to_lady(world)); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (!report.completed || report.events_skipped != 1 || report.events_run != 0){ + return "Expected the event skipped."; + } + if (!world.trace.empty() || !lines.has("[Event] 00.04/1 talk_poke_mart_lady: skipped")){ + return std::format("The skipped event should not act:{}", lines.all()); + } + return true; +} + +UnitTestResult test_expect_failure_waited_out(){ + World world; + world.talks_before_answer = 2; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(talk_to_lady(world)); + checkpoint.events.back().recoveries.push_back(recovery("expect_failed", RecoveryKind::WAIT, 2)); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (!report.completed || world.trace.size() != 3 || world.potions != 10){ + return std::format("Expected three talks, the last answered:{}", lines.all()); + } + if (!lines.has("[Event] 00.04/1 talk_poke_mart_lady: recover: wait (expect_failed)")){ + return std::format("Expected the wait logged:{}", lines.all()); + } + return true; +} + +// Mom: a talk from the wrong row reaches nobody. Waiting does not help; +// confirming the row on a landmark does. +Event talk_to_mom(World& world){ + Event event = make_event("talk_mom", [&world](RunState&){ + world.trace.push_back("talk"); + world.dialogue_open = world.rows_off == 0; + return outcome_ok(); + }); + event.expect.push_back(dialogue_opened(world)); + event.recoveries.push_back(recovery("expect_failed", RecoveryKind::WAIT, 1, record("wait", world))); + event.recoveries.push_back(recovery("expect_failed", RecoveryKind::REANCHOR, 1, [&world](RunState& state){ + world.trace.push_back("anchor"); + world.rows_off = 0; + return outcome_ok(anchored(state.pose)); + })); + event.recoveries.push_back(recovery("", RecoveryKind::STOP, 0)); + event.recoveries.back().why = "four rows cover the mat to the TV"; + return event; +} + +UnitTestResult test_escalates_to_reanchor(){ + World world; + world.rows_off = 1; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(talk_to_mom(world)); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + const std::vector expected = {"talk", "wait", "talk", "anchor", "talk"}; + if (!report.completed || world.trace != expected){ + return std::format("Expected wait, then re-anchor:{}", lines.all()); + } + if (state.pose.certainty != PoseCertainty::TILE){ + return "The re-anchor should have fixed the pose."; + } + return true; +} + +UnitTestResult test_stop_names_failed_event(){ + World world; + world.rows_off = 1; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(make_event("enter_home", record("enter", world))); + checkpoint.events.push_back(talk_to_mom(world)); + checkpoint.events.back().recoveries[1].prepare = record("anchor", world); // An anchor that does not help. + checkpoint.events.push_back(make_event("mom_dialogue", record("dialogue", world))); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (report.completed || report.failed_event != 2 || report.failed_name != "talk_mom"){ + return std::format("Expected event 2 reported:{}", lines.all()); + } + if (report.failure.failure != "expect_failed" || report.failure.detail != "dialogue opened"){ + return "Expected the failing expect reported."; + } + if (std::count(world.trace.begin(), world.trace.end(), "dialogue") != 0){ + return "Nothing after the failed event should run."; + } + if (!lines.has("[Event] 00.04/2 talk_mom: recover: stop (expect_failed): four rows cover the mat to the TV") + || !lines.has("[Event] 00.04/2 talk_mom: failed: expect_failed: dialogue opened (class=state_check_failed)") + || lines.lines.back() != "[Checkpoint] 00.04: failed at 2 talk_mom: expect_failed: dialogue opened (class=state_check_failed)" + ){ + return std::format("Unexpected log:{}", lines.all()); + } + return true; +} + +UnitTestResult test_unmatched_failure_stops(){ + World world; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(make_event("probe_for_mom", [&world](RunState&){ + world.trace.push_back("probe"); + return outcome_failed("probe_exhausted", "4 rows"); + })); + checkpoint.events.back().recoveries.push_back(recovery("blocked", RecoveryKind::WAIT, 3)); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (report.completed || report.failure.failure != "probe_exhausted" || world.trace.size() != 1){ + return std::format("A failure no recovery names should stop at once:{}", lines.all()); + } + if (!lines.has("[Event] 00.04/1 probe_for_mom: failed: probe_exhausted: 4 rows")){ + return std::format("Unexpected log:{}", lines.all()); + } + return true; +} + +// A game's own failure name with the class the game gives it. +UnitTestResult test_failure_names_its_class(){ + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(make_event("probe_for_mom", [](RunState&){ + return outcome_failed("probe_exhausted", "4 rows", StoryFailureClass::POSE_LOST); + })); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (failure_class_of(report.failure) != StoryFailureClass::POSE_LOST){ + return std::format("Expected the report's failure of class pose_lost:{}", lines.all()); + } + if (!lines.has("[Event] 00.04/1 probe_for_mom: failed: probe_exhausted: 4 rows (class=pose_lost)") + || lines.lines.back() != "[Checkpoint] 00.04: failed at 1 probe_for_mom: probe_exhausted: 4 rows (class=pose_lost)" + ){ + return std::format("Unexpected log:{}", lines.all()); + } + return true; +} + +// A game's action that throws OperationFailedException: the exception goes +// on, the log names its class. +UnitTestResult test_throw_names_its_class(){ + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(make_event("talk_mom", [](RunState&) -> Outcome{ + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, "no dialog"); + })); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + try{ + run_checkpoint(state, checkpoint, log); + return "Expected the exception to go on."; + }catch (OperationFailedException&){} + if (!lines.has("[Event] 00.04/1 talk_mom: failed: OperationFailedException: no dialog (class=operation_failed)") + || lines.lines.back() != "[Checkpoint] 00.04: failed at 1 talk_mom: OperationFailedException: no dialog (class=operation_failed)" + ){ + return std::format("Unexpected log:{}", lines.all()); + } + return true; +} + +Interrupt wild_battle(ResumePolicy resume, World& world){ + Interrupt interrupt; + interrupt.name = "wild_battle"; + interrupt.detect = [&world](RunState&){ return world.battle_showing; }; + interrupt.handle = [&world](RunState&){ + world.trace.push_back("flee"); + world.battle_showing = false; + return outcome_ok(); + }; + interrupt.pose = InterruptPose::WITHIN_SET; + interrupt.resume = resume; + return interrupt; +} + +// A walk through grass: the first try meets a wild battle half-way. +Event walk_through_grass(World& world){ + Event event = make_event("walk_to_corner", [&world](RunState&){ + world.trace.push_back("walk"); + if (world.walk_failures > 0){ + world.walk_failures--; + world.battle_showing = true; + return outcome_failed("walk_stopped"); + } + world.map = "Route 201"; + return outcome_ok(); + }); + event.require.push_back(pose_known("Route 202", PoseCertainty::TILE)); + event.expect.push_back(condition("on Route 201", [&world](RunState&){ return world.map == "Route 201"; })); + Pose corner; + corner.map = "Route 201"; + corner.certainty = PoseCertainty::TILE; + corner.where = std::make_shared(std::vector{TilePos{42, 3}}); + event.pose_learned = corner; + event.recoveries.push_back(recovery("require_failed", RecoveryKind::REANCHOR, 1, [&world](RunState& state){ + world.trace.push_back("anchor"); + return outcome_ok(anchored(state.pose)); + })); + return event; +} + +RunState at_catch_spot(std::optional facing = std::nullopt){ + RunState state; + state.pose.map = "Route 202"; + state.pose.certainty = PoseCertainty::TILE; + state.pose.where = std::make_shared(std::vector{TilePos{10, 20}}, facing); + return state; +} + +UnitTestResult test_interrupt_mid_event(){ + World world; + world.walk_failures = 1; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.interrupts.push_back(wild_battle(ResumePolicy::RETRY_EVENT, world)); + checkpoint.events.push_back(walk_through_grass(world)); + RunState state = at_catch_spot(); + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + // The battle leaves the pose inexact, so the retry first re-anchors. + const std::vector expected = {"walk", "flee", "anchor", "walk"}; + if (!report.completed || world.trace != expected){ + return std::format("Expected flee, re-anchor, walk again:{}", lines.all()); + } + if (!lines.has("[Event] 00.04/1 walk_to_corner: interrupt: wild_battle")){ + return std::format("Expected the interrupt logged:{}", lines.all()); + } + if (state.pose.map != "Route 201" || tiles_of(state.pose) != std::vector{TilePos{42, 3}}){ + return std::format("Expected the learned pose: {}", to_string(state.pose)); + } + return true; +} + +UnitTestResult test_interrupt_recheck_expect(){ + World world; + Checkpoint checkpoint = make_checkpoint(); + Interrupt interrupt = wild_battle(ResumePolicy::RECHECK_EXPECT, world); + interrupt.pose = InterruptPose::UNCHANGED; + checkpoint.interrupts.push_back(std::move(interrupt)); + // A talk-only trainer stops us on the last step: we arrived anyway. + checkpoint.events.push_back(make_event("walk_to_exit", [&world](RunState&){ + world.trace.push_back("walk"); + world.map = "Route 201"; + world.battle_showing = true; + return outcome_failed("walk_stopped"); + })); + checkpoint.events.back().expect.push_back(condition("on Route 201", [&world](RunState&){ return world.map == "Route 201"; })); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (!report.completed || world.trace != std::vector{"walk", "flee"}){ + return std::format("Expected done without walking again:{}", lines.all()); + } + return true; +} + +UnitTestResult test_too_many_interrupts(){ + World world; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.max_interrupts_per_event = 2; + checkpoint.interrupts.push_back(wild_battle(ResumePolicy::RETRY_EVENT, world)); + checkpoint.events.push_back(make_event("walk", [&world](RunState&){ + world.battle_showing = true; + return outcome_failed("walk_stopped"); + })); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (report.completed || report.failure.failure != "too_many_interrupts"){ + return std::format("Expected to give up after 2 interrupts:{}", lines.all()); + } + return true; +} + + +// 00.04 after the catch, shortened: Potions, save, then a walk north that +// fails on the first run. The reload restores the world as saved. +Checkpoint post_catch(World& world, World& saved){ + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(talk_to_lady(world)); + Event save = make_event("save_on_202", [&world, &saved](RunState&){ + world.trace.push_back("save"); + world.map = "Route 202"; + saved = world; + return outcome_ok(); + }); + save.skip_if.push_back(has_potions(world)); + save.skip_if.push_back(condition("on Route 202", [&world](RunState&){ return world.map == "Route 202"; })); + checkpoint.events.push_back(std::move(save)); + checkpoint.events.push_back(make_event("train", record("train", world))); + checkpoint.events.push_back(make_event("walk_north", [&world](RunState&){ + world.trace.push_back("walk"); + if (world.walk_failures > 0){ + world.walk_failures--; + return outcome_failed("blocked_unexplained"); + } + world.map = "Jubilife City"; + return outcome_ok(); + })); + checkpoint.end.push_back(condition("in Jubilife", [&world](RunState&){ return world.map == "Jubilife City"; })); + return checkpoint; +} + +UnitTestResult test_resume_after_reload(){ + World world; + world.map = "Route 201"; + world.walk_failures = 1; + World saved; + Checkpoint checkpoint = post_catch(world, saved); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport first = run_checkpoint(state, checkpoint, log); + if (first.completed || first.failed_event != 4){ + return std::format("Expected the first run to fail at the walk:{}", lines.all()); + } + world = saved; // Reload: the save has the Potions and stands on Route 202. + world.walk_failures = 0; // Whatever blocked the walk has moved on. + world.trace.clear(); + RunState reloaded; + const CheckpointReport second = run_checkpoint(reloaded, checkpoint, log); + if (!second.completed || second.events_skipped != 2 || second.events_run != 2){ + return std::format("Expected the Potions and the save skipped:{}", lines.all()); + } + if (world.trace != std::vector{"train", "walk"} || world.potions != 10){ + return "Expected only the training and the walk again."; + } + return true; +} + +UnitTestResult test_start_end_and_save(){ + World world; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.start.push_back(has_potions(world)); + checkpoint.events.push_back(make_event("walk", record("walk", world))); + checkpoint.end.push_back(condition("parcel in the Bag", [&world](RunState&){ return world.parcel; })); + checkpoint.save = record("save", world); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (report.completed || report.failure.failure != "start_failed" || !world.trace.empty()){ + return "Expected the start check to stop before any event."; + } + world.potions = 1; + report = run_checkpoint(state, checkpoint, log); + if (report.completed || report.failure.failure != "end_failed" || world.trace.size() != 1){ + return "Expected the end check to fail without a save."; + } + world.parcel = true; + report = run_checkpoint(state, checkpoint, log); + if (!report.completed || world.trace.back() != "save"){ + return "Expected a save after the end check."; + } + return true; +} + +UnitTestResult test_pose_certainty(){ + if (!certainty_covers(PoseCertainty::TILE, PoseCertainty::COLUMN) + || certainty_covers(PoseCertainty::ROW, PoseCertainty::COLUMN) + || certainty_covers(PoseCertainty::SET, PoseCertainty::ROW) + || !certainty_covers(PoseCertainty::SET, PoseCertainty::SET) + || certainty_covers(PoseCertainty::UNKNOWN, PoseCertainty::SET) + || !certainty_covers(PoseCertainty::UNKNOWN, PoseCertainty::UNKNOWN) + ){ + return "Wrong certainty order."; + } + RunState state = at_catch_spot(Direction::NORTH); + if (to_string(state.pose) != "Route 202 (10, 20) facing north (tile)"){ + return std::format("Unexpected pose text: {}", to_string(state.pose)); + } + Condition known = pose_known("Route 201", PoseCertainty::SET); + if (known.check(state)){ + return "The pose is on another map."; + } + return true; +} + +// A game without tiles: a point on its map, as Scarlet/Violet would give. +struct PointPose : public Position{ + int x = 0; + int y = 0; + + PointPose(int x, int y) : x(x), y(y){} + virtual std::string describe() const override{ + return std::format("({}, {})", x, y); + } +}; + +Pose at_point(std::string map, int x, int y){ + Pose pose; + pose.map = std::move(map); + pose.certainty = PoseCertainty::TILE; + pose.where = std::make_shared(x, y); + return pose; +} + +// The engine carries whatever position the game gives it: a battle leaves +// it within the set, a lost pose drops it, a learned pose replaces it. +UnitTestResult test_position_is_the_games(){ + World world; + world.walk_failures = 1; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.interrupts.push_back(wild_battle(ResumePolicy::RETRY_EVENT, world)); + Event ride = make_event("ride_to_mesagoza", [&world](RunState&){ + world.trace.push_back("ride"); + if (world.walk_failures > 0){ + world.walk_failures--; + world.battle_showing = true; + return outcome_failed("walk_stopped"); + } + return outcome_ok(); + }); + ride.require.push_back(pose_known("South Province", PoseCertainty::SET)); + ride.pose_learned = at_point("Mesagoza", 7, 8); + checkpoint.events.push_back(std::move(ride)); + RunState state; + state.pose = at_point("South Province", 3, 4); + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (!report.completed || world.trace != std::vector{"ride", "flee", "ride"}){ + return std::format("Expected the ride retried after the battle:{}", lines.all()); + } + if (to_string(state.pose) != "Mesagoza (7, 8) (tile)"){ + return std::format("Expected the learned point: {}", to_string(state.pose)); + } + Interrupt lost = wild_battle(ResumePolicy::RETRY_EVENT, world); + lost.pose = InterruptPose::LOST; + checkpoint.interrupts[0] = std::move(lost); + world.walk_failures = 1; + checkpoint.events[0].pose_learned.reset(); + checkpoint.events[0].require.clear(); + run_checkpoint(state, checkpoint, log); + if (state.pose.where || to_string(state.pose) != "Mesagoza (unknown)"){ + return std::format("Expected the lost pose to drop its position: {}", to_string(state.pose)); + } + return true; +} + +// An action that learns where it ends up returns the pose; the runner +// writes it before the expects, and only when the action succeeded. +UnitTestResult test_outcome_pose(){ + World world; + Checkpoint checkpoint = make_checkpoint(); + Event probe = make_event("probe_for_mom", [&world](RunState&){ + world.trace.push_back("probe"); + Pose found; + found.map = "Player's House"; + found.certainty = PoseCertainty::ROW; + found.where = std::make_shared(std::vector{TilePos{4, 6}, TilePos{5, 6}}); + return world.rows_off == 0 ? outcome_ok(found) : outcome_failed("probe_exhausted", "4 rows"); + }); + probe.expect.push_back(pose_known("Player's House", PoseCertainty::ROW)); + checkpoint.events.push_back(std::move(probe)); + RunState state = at_catch_spot(); + Lines lines; + EventLogger log = lines.logger(); + CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (!report.completed || to_string(state.pose) != "Player's House (4, 6) (5, 6) (row)"){ + return std::format("Expected the found pose written before the expect: {}{}", to_string(state.pose), lines.all()); + } + world.rows_off = 1; + state = at_catch_spot(); + report = run_checkpoint(state, checkpoint, log); + if (report.completed || state.pose.map != "Route 202"){ + return std::format("A failed action should leave the pose alone: {}", to_string(state.pose)); + } + return true; +} + +UnitTestResult test_lint(){ + World world; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(talk_to_mom(world)); + if (!lint_checkpoint(checkpoint).empty()){ + return "A good checkpoint should lint clean."; + } + checkpoint.events.push_back(make_event("talk_mom", nullptr)); + checkpoint.events.back().recoveries.push_back(recovery("", RecoveryKind::STOP, 0)); + checkpoint.events.back().recoveries.push_back(recovery("", RecoveryKind::WAIT, 0)); + const std::vector problems = lint_checkpoint(checkpoint); + // Duplicate name, no action, wait after stop, wait with no attempts. + if (problems.size() != 4){ + std::string text; + for (const std::string& problem : problems){ + text += std::format("\n{}", problem); + } + return std::format("Expected 4 problems:{}", text); + } + return true; +} + + +struct StoryEventTestCase{ + std::string name; + struct Input{ + UnitTestResult (*test)(); + }; + + struct Expectation{ + std::string_view description; + }; + + Input input; + Expectation expectation; +}; + +class Test_StoryEvents : public UnitTest{ +public: + explicit Test_StoryEvents(StoryEventTestCase scenario) + : UnitTest(std::format("Pokemon::StoryEvents - {}", scenario.name)) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_scenario.input.test(); + } + +private: + StoryEventTestCase m_scenario; +}; + +const StoryEventTestCase STORY_EVENT_CASES[] = { + { + .name = "events run in order", .input = {.test = test_runs_events_in_order}, + .expectation = {.description = "executes registered events in sequence and records traces"}, + }, + { + .name = "a done event is skipped", .input = {.test = test_skips_done_event}, + .expectation = {.description = "bypasses event execution when skip condition is satisfied"}, + }, + { + .name = "a failed expect is waited out", .input = {.test = test_expect_failure_waited_out}, + .expectation = {.description = "retries transient expectation failure until timeout"}, + }, + { + .name = "recoveries escalate to a re-anchor", .input = {.test = test_escalates_to_reanchor}, + .expectation = {.description = "escalates recovery strategy to re-anchor when wait fails"}, + }, + { + .name = "a stop names the failed event", .input = {.test = test_stop_names_failed_event}, + .expectation = {.description = "records identifier of the failed event upon stopping"}, + }, + { + .name = "an unanswered failure stops", .input = {.test = test_unmatched_failure_stops}, + .expectation = {.description = "stops checkpoint execution when failure has no handler"}, + }, + { + .name = "a failure names its class", .input = {.test = test_failure_names_its_class}, + .expectation = {.description = "logs the class a game gives its own failure name"}, + }, + { + .name = "a throw names its class", .input = {.test = test_throw_names_its_class}, + .expectation = {.description = "logs operation_failed for an OperationFailedException that goes on"}, + }, + { + .name = "an interrupt mid-event", .input = {.test = test_interrupt_mid_event}, + .expectation = {.description = "handles asynchronous interruption during event execution"}, + }, + { + .name = "an interrupt rechecks the expects", .input = {.test = test_interrupt_recheck_expect}, + .expectation = {.description = "re-evaluates expected conditions after an interrupt clears"}, + }, + { + .name = "too many interrupts", .input = {.test = test_too_many_interrupts}, + .expectation = {.description = "aborts execution when interrupt count exceeds threshold"}, + }, + { + .name = "resume after a reload", .input = {.test = test_resume_after_reload}, + .expectation = {.description = "resumes story execution cleanly following save reload"}, + }, + { + .name = "start, end and save", .input = {.test = test_start_end_and_save}, + .expectation = {.description = "validates start conditions, end conditions, and state save"}, + }, + { + .name = "pose certainty", .input = {.test = test_pose_certainty}, + .expectation = {.description = "tracks and adjusts player pose confidence levels"}, + }, + { + .name = "the position is the game's", .input = {.test = test_position_is_the_games}, + .expectation = {.description = "preserves game-specific coordinate representations"}, + }, + { + .name = "an action returns its pose", .input = {.test = test_outcome_pose}, + .expectation = {.description = "updates run pose from successful event action outcome"}, + }, + { + .name = "lint", .input = {.test = test_lint}, + .expectation = {.description = "validates checkpoint structural integrity and rules"}, + }, +}; + +} // namespace + + +void add_tests_StoryEvents(UnitTestDatabase& database){ + for (const auto& scenario : STORY_EVENT_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.h new file mode 100644 index 0000000000..970de36ba4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.h @@ -0,0 +1,23 @@ +/* Story Events Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryEvents_Tests_H +#define PokemonAutomation_Pokemon_StoryEvents_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for story event sequencing and execution. +void add_tests_StoryEvents(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.cpp new file mode 100644 index 0000000000..064bb87ee4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.cpp @@ -0,0 +1,35 @@ +/* Story Outcome Class + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryOutcomeClass.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::optional failure_class_of(const Outcome& outcome){ + if (outcome.succeeded()){ + return std::nullopt; + } + if (outcome.failure_class){ + return outcome.failure_class; + } + return story_failure_class_of_outcome(outcome.failure); +} + +std::string to_string_with_class(const Outcome& outcome){ + const std::optional failure_class = failure_class_of(outcome); + if (!failure_class){ + return to_string(outcome); + } + return std::format("{} ({})", to_string(outcome), story_failure_class_tag(*failure_class)); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.h new file mode 100644 index 0000000000..ec692db6ab --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.h @@ -0,0 +1,35 @@ +/* Story Outcome Class + * + * From: https://github.com/PokemonAutomation/ + * + * The class (Pokemon_StoryFailureClasses.h) of a failed Outcome, and the + * text a failure's log line ends with. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryOutcomeClass_H +#define PokemonAutomation_Pokemon_StoryOutcomeClass_H + +#include +#include +#include "Pokemon_StoryFailureClasses.h" +#include "Pokemon_StoryOutcome.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The class of a failed `outcome`: its own, else the shared list's for its +// name. Nothing for a success or a name no class lists. +std::optional failure_class_of(const Outcome& outcome); + +// to_string() and the class, as a failure's log line ends: +// "expect_failed: has_parcel (class=state_check_failed)"; without a class, +// to_string() alone. +std::string to_string_with_class(const Outcome& outcome); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.cpp new file mode 100644 index 0000000000..4d53eeff06 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.cpp @@ -0,0 +1,54 @@ +/* Tile Pose + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Pokemon_TilePose.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +TilePose::TilePose(std::vector tiles, std::optional facing) + : tiles(std::move(tiles)) + , facing(facing) +{} + +std::string TilePose::describe() const{ + std::string text; + for (const TilePos& tile : tiles){ + text += (text.empty() ? "" : " ") + to_string(tile); + } + if (facing){ + text += std::format("{}facing {}", text.empty() ? "" : " ", direction_name(*facing)); + } + return text; +} + +std::vector tiles_of(const Pose& pose){ + const TilePose* position = dynamic_cast(pose.where.get()); + return position ? position->tiles : std::vector{}; +} + +std::optional facing_of(const Pose& pose){ + const TilePose* position = dynamic_cast(pose.where.get()); + return position ? position->facing : std::nullopt; +} + +Pose tile_pose(std::string map, std::vector tiles, std::optional facing){ + Pose pose; + pose.map = std::move(map); + pose.certainty = tiles.empty() ? PoseCertainty::UNKNOWN + : tiles.size() == 1 ? PoseCertainty::TILE : PoseCertainty::SET; + pose.where = std::make_shared(std::move(tiles), facing); + return pose; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.h new file mode 100644 index 0000000000..bf937c3912 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.h @@ -0,0 +1,49 @@ +/* Tile Pose + * + * From: https://github.com/PokemonAutomation/ + * + * The position a 2D tile game (BDSP, FRLG) gives the story-event engine: + * the tiles the player may stand on and the way they face. The engine + * (Pokemon_StoryEvents.h) does not know tiles; games include this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_TilePose_H +#define PokemonAutomation_Pokemon_TilePose_H + +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "Pokemon_StoryEvents.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// One of `tiles`, facing `facing` if known. +struct TilePose : public Position{ + std::vector tiles; + std::optional facing; + + explicit TilePose(std::vector tiles, std::optional facing = std::nullopt); + // "(10, 20) facing north": the tiles, then the facing, each after a space. + virtual std::string describe() const override; +}; + +// The tiles of a pose: empty when the pose holds no position, or one that +// is not a tile pose. +std::vector tiles_of(const Pose& pose); + +// The facing of a tile pose; nothing for another pose or none. +std::optional facing_of(const Pose& pose); + +// A pose on one of `tiles` of `map`, facing `facing` if set: TILE for one +// tile, SET for several, UNKNOWN for none. +Pose tile_pose(std::string map, std::vector tiles, std::optional facing = std::nullopt); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 0f0f3896a8..46deae7c65 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1451,6 +1451,10 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_MapUtil.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_StoryFailureClasses.cpp Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.h Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses_Tests.cpp @@ -1460,7 +1464,11 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.h Source/Pokemon/AutoStory/Pokemon_StoryOutcome.h + Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.cpp + Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.h Source/Pokemon/AutoStory/Pokemon_StoryPose.h + Source/Pokemon/AutoStory/Pokemon_TilePose.cpp + Source/Pokemon/AutoStory/Pokemon_TilePose.h Source/Pokemon/AutoStory/Types/Pokemon_DeclaredPose.h Source/Pokemon/AutoStory/Types/Pokemon_GridPose.h Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.cpp From effea5e83696d94076c92a63ebaaee9524db118e Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 00:51:43 -0800 Subject: [PATCH 2/2] AutoStory: the event runner keeps only the runner The Outcome, Pose, Condition and interrupt functions now live with the headers that declare them, so they leave Pokemon_StoryEvents.cpp. The header no longer points at a design note that is not in the repo, and the event tests are plain named tests: their descriptions were never compared. --- .../Pokemon/AutoStory/Pokemon_StoryEvents.cpp | 116 ------------------ .../Pokemon/AutoStory/Pokemon_StoryEvents.h | 2 +- .../AutoStory/Pokemon_StoryEvents_Tests.cpp | 99 +++------------ 3 files changed, 21 insertions(+), 196 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp index 1dd6975bff..cffe331443 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp @@ -24,103 +24,6 @@ std::string checkpoint_log_line(std::string_view checkpoint, std::string_view te return std::format("[Checkpoint] {}: {}", checkpoint, text); } -std::string certainty_name(PoseCertainty certainty){ - switch (certainty){ - case PoseCertainty::TILE: - return "tile"; - case PoseCertainty::COLUMN: - return "column"; - case PoseCertainty::ROW: - return "row"; - case PoseCertainty::SET: - return "set"; - case PoseCertainty::UNKNOWN: - return "unknown"; - } - return "?"; -} - -bool certainty_covers(PoseCertainty have, PoseCertainty need){ - switch (need){ - case PoseCertainty::UNKNOWN: - return true; - case PoseCertainty::SET: - return have != PoseCertainty::UNKNOWN; - case PoseCertainty::COLUMN: - case PoseCertainty::ROW: - return have == need || have == PoseCertainty::TILE; - case PoseCertainty::TILE: - return have == PoseCertainty::TILE; - } - return false; -} - -std::string to_string(const Pose& pose){ - std::string text = pose.map.empty() ? "?" : pose.map; - if (pose.where){ - const std::string where = pose.where->describe(); - if (!where.empty()){ - text += std::format(" {}", where); - } - } - return std::format("{} ({})", text, certainty_name(pose.certainty)); -} - - -bool Outcome::succeeded() const{ - return failure.empty(); -} -Outcome outcome_ok(std::optional pose){ - Outcome outcome; - outcome.pose = std::move(pose); - return outcome; -} - -Outcome outcome_unchanged(){ - Outcome outcome; - outcome.changed_nothing = true; - return outcome; -} - -Outcome outcome_failed(std::string failure, std::string detail, std::optional failure_class){ - Outcome outcome; - outcome.failure = std::move(failure); - outcome.detail = std::move(detail); - outcome.failure_class = failure_class; - return outcome; -} -std::string to_string(const Outcome& outcome){ - return outcome.detail.empty() ? outcome.failure : std::format("{}: {}", outcome.failure, outcome.detail); -} - -Outcome outcome_game_not_running(){ - return outcome_failed(std::string(GAME_NOT_RUNNING), "the game is not running: the Switch HOME menu is showing"); -} - -Condition condition(std::string name, Check check){ - return Condition{std::move(name), std::move(check)}; -} - -Condition pose_known(std::string map, PoseCertainty need){ - std::string name = std::format("pose {}{}", certainty_name(need), map.empty() ? "" : std::format(" on {}", map)); - return condition(std::move(name), [map = std::move(map), need](RunState& state){ - return (map.empty() || state.pose.map == map) && certainty_covers(state.pose.certainty, need); - }); -} - -std::string recovery_name(RecoveryKind kind){ - switch (kind){ - case RecoveryKind::WAIT: - return "wait"; - case RecoveryKind::REANCHOR: - return "re-anchor"; - case RecoveryKind::STOP: - return "stop"; - } - return "?"; -} - - namespace{ // Runs an action; if it succeeded knowing where it left the player, that @@ -170,25 +73,6 @@ Outcome attempt_event(Event& event, RunState& state){ return check_expects(event, state); } -} // namespace - -void apply_interrupt_pose(InterruptPose effect, Pose& pose){ - switch (effect){ - case InterruptPose::UNCHANGED: - return; - case InterruptPose::WITHIN_SET: - if (pose.certainty != PoseCertainty::UNKNOWN){ - pose.certainty = PoseCertainty::SET; - } - return; - case InterruptPose::LOST: - pose.where.reset(); - pose.certainty = PoseCertainty::UNKNOWN; - return; - } -} - -namespace{ // One event being run, with what it has used up. diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h index 860d7d5f45..ef1759d022 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h @@ -20,7 +20,7 @@ * * Observation and actuation are callables the game supplies, so this file * knows nothing of any one game or console, and the runner can be tested - * against a scripted world. See docs/design/AutoStory-Event-Model.md. + * against a scripted world. * */ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp index 3b54de788e..23198d1c64 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp @@ -657,18 +657,10 @@ UnitTestResult test_lint(){ } +// A named test; it returns its own failure. struct StoryEventTestCase{ std::string name; - struct Input{ - UnitTestResult (*test)(); - }; - - struct Expectation{ - std::string_view description; - }; - - Input input; - Expectation expectation; + UnitTestResult (*test)(); }; class Test_StoryEvents : public UnitTest{ @@ -678,7 +670,7 @@ class Test_StoryEvents : public UnitTest{ , m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - return m_scenario.input.test(); + return m_scenario.test(); } private: @@ -686,74 +678,23 @@ class Test_StoryEvents : public UnitTest{ }; const StoryEventTestCase STORY_EVENT_CASES[] = { - { - .name = "events run in order", .input = {.test = test_runs_events_in_order}, - .expectation = {.description = "executes registered events in sequence and records traces"}, - }, - { - .name = "a done event is skipped", .input = {.test = test_skips_done_event}, - .expectation = {.description = "bypasses event execution when skip condition is satisfied"}, - }, - { - .name = "a failed expect is waited out", .input = {.test = test_expect_failure_waited_out}, - .expectation = {.description = "retries transient expectation failure until timeout"}, - }, - { - .name = "recoveries escalate to a re-anchor", .input = {.test = test_escalates_to_reanchor}, - .expectation = {.description = "escalates recovery strategy to re-anchor when wait fails"}, - }, - { - .name = "a stop names the failed event", .input = {.test = test_stop_names_failed_event}, - .expectation = {.description = "records identifier of the failed event upon stopping"}, - }, - { - .name = "an unanswered failure stops", .input = {.test = test_unmatched_failure_stops}, - .expectation = {.description = "stops checkpoint execution when failure has no handler"}, - }, - { - .name = "a failure names its class", .input = {.test = test_failure_names_its_class}, - .expectation = {.description = "logs the class a game gives its own failure name"}, - }, - { - .name = "a throw names its class", .input = {.test = test_throw_names_its_class}, - .expectation = {.description = "logs operation_failed for an OperationFailedException that goes on"}, - }, - { - .name = "an interrupt mid-event", .input = {.test = test_interrupt_mid_event}, - .expectation = {.description = "handles asynchronous interruption during event execution"}, - }, - { - .name = "an interrupt rechecks the expects", .input = {.test = test_interrupt_recheck_expect}, - .expectation = {.description = "re-evaluates expected conditions after an interrupt clears"}, - }, - { - .name = "too many interrupts", .input = {.test = test_too_many_interrupts}, - .expectation = {.description = "aborts execution when interrupt count exceeds threshold"}, - }, - { - .name = "resume after a reload", .input = {.test = test_resume_after_reload}, - .expectation = {.description = "resumes story execution cleanly following save reload"}, - }, - { - .name = "start, end and save", .input = {.test = test_start_end_and_save}, - .expectation = {.description = "validates start conditions, end conditions, and state save"}, - }, - { - .name = "pose certainty", .input = {.test = test_pose_certainty}, - .expectation = {.description = "tracks and adjusts player pose confidence levels"}, - }, - { - .name = "the position is the game's", .input = {.test = test_position_is_the_games}, - .expectation = {.description = "preserves game-specific coordinate representations"}, - }, - { - .name = "an action returns its pose", .input = {.test = test_outcome_pose}, - .expectation = {.description = "updates run pose from successful event action outcome"}, - }, - { - .name = "lint", .input = {.test = test_lint}, - .expectation = {.description = "validates checkpoint structural integrity and rules"}, - }, + {.name = "events run in order", .test = test_runs_events_in_order}, + {.name = "a done event is skipped", .test = test_skips_done_event}, + {.name = "a failed expect is waited out", .test = test_expect_failure_waited_out}, + {.name = "recoveries escalate to a re-anchor", .test = test_escalates_to_reanchor}, + {.name = "a stop names the failed event", .test = test_stop_names_failed_event}, + {.name = "an unanswered failure stops", .test = test_unmatched_failure_stops}, + {.name = "a failure names its class", .test = test_failure_names_its_class}, + {.name = "a throw names its class", .test = test_throw_names_its_class}, + {.name = "an interrupt mid-event", .test = test_interrupt_mid_event}, + {.name = "an interrupt rechecks the expects", .test = test_interrupt_recheck_expect}, + {.name = "too many interrupts", .test = test_too_many_interrupts}, + {.name = "resume after a reload", .test = test_resume_after_reload}, + {.name = "start, end and save", .test = test_start_end_and_save}, + {.name = "pose certainty", .test = test_pose_certainty}, + {.name = "the position is the game's", .test = test_position_is_the_games}, + {.name = "an action returns its pose", .test = test_outcome_pose}, + {.name = "lint", .test = test_lint}, }; } // namespace