diff --git a/Common/Cpp/MoveOnlyFunction.h b/Common/Cpp/MoveOnlyFunction.h new file mode 100644 index 0000000000..9cc71f3422 --- /dev/null +++ b/Common/Cpp/MoveOnlyFunction.h @@ -0,0 +1,118 @@ +/* Move-Only Function + * + * From: https://github.com/PokemonAutomation/ + * + * A callable wrapper that can be moved but not copied. + * + * Prefer this over std::function for a callback that has one owner. + * Copying a std::function copies its callable, so a stateful lambda + * silently splits into two independent states. And std::function cannot + * hold a lambda that captures a move-only object (e.g. std::unique_ptr). + * + * This is std::move_only_function (C++23) where the standard library has + * it. Apple's libc++ (Xcode 26 / Apple Clang 21) does not, so this header + * has a minimal fallback for the plain "R(Args...)" signature. Delete the + * fallback once every supported compiler defines + * __cpp_lib_move_only_function. + * + */ + +#ifndef PokemonAutomation_MoveOnlyFunction_H +#define PokemonAutomation_MoveOnlyFunction_H + +#include +#include + +#ifndef __cpp_lib_move_only_function +#include +#include +#include +#include +#endif + +namespace PokemonAutomation{ + + + +#ifdef __cpp_lib_move_only_function + +template +using MoveOnlyFunction = std::move_only_function; + +#else + +template +class MoveOnlyFunction; + +template +class MoveOnlyFunction{ +public: + MoveOnlyFunction() noexcept = default; + MoveOnlyFunction(std::nullptr_t) noexcept {} + + template + requires ( + !std::is_same_v, MoveOnlyFunction> && + std::is_invocable_r_v&, Args...> + ) + MoveOnlyFunction(Function&& function){ + using Stored = std::decay_t; + // Like std::move_only_function, a null function pointer makes an + // empty wrapper. + if constexpr (std::is_pointer_v || std::is_member_pointer_v){ + if (function == nullptr){ + return; + } + } + m_callable = std::make_unique>(std::forward(function)); + } + + MoveOnlyFunction(MoveOnlyFunction&&) noexcept = default; + MoveOnlyFunction& operator=(MoveOnlyFunction&&) noexcept = default; + MoveOnlyFunction(const MoveOnlyFunction&) = delete; + MoveOnlyFunction& operator=(const MoveOnlyFunction&) = delete; + + explicit operator bool() const noexcept{ + return m_callable != nullptr; + } + friend bool operator==(const MoveOnlyFunction& function, std::nullptr_t) noexcept{ + return !function; + } + + // Calling an empty wrapper is undefined, as for std::move_only_function. + R operator()(Args... args){ + return m_callable->call(std::forward(args)...); + } + + +private: + class Callable{ + public: + virtual ~Callable() = default; + virtual R call(Args&&... args) = 0; + }; + + template + class Holder final : public Callable{ + public: + template + explicit Holder(Source&& source) + : m_stored(std::forward(source)) + {} + virtual R call(Args&&... args) override{ + return std::invoke_r(m_stored, std::forward(args)...); + } + + private: + Stored m_stored; + }; + + std::unique_ptr m_callable; +}; + +#endif + + + +} +#endif diff --git a/Common/Cpp/MoveOnlyFunction_Tests.cpp b/Common/Cpp/MoveOnlyFunction_Tests.cpp new file mode 100644 index 0000000000..72ed5998ae --- /dev/null +++ b/Common/Cpp/MoveOnlyFunction_Tests.cpp @@ -0,0 +1,190 @@ +/* Move-Only Function Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "TestRunners/UnitTestDatabase.h" +#include "MoveOnlyFunction.h" +#include "MoveOnlyFunction_Tests.h" + +namespace PokemonAutomation{ +namespace{ + + + +// Copying would fork a stateful callable, so it must not compile. +static_assert(!std::is_copy_constructible_v>); +static_assert(!std::is_copy_assignable_v>); +static_assert(std::is_nothrow_move_constructible_v>); + + + +std::string expected_int(const char* what, int expected, int actual){ + return std::string(what) + ": expected " + std::to_string(expected) + + ", got " + std::to_string(actual); +} + + + +class Test_MoveOnlyFunction_MoveOnlyCapture : public UnitTest{ +public: + Test_MoveOnlyFunction_MoveOnlyCapture() + : UnitTest("Common::MoveOnlyFunction - Move-only capture") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + auto value = std::make_unique(42); + MoveOnlyFunction function = [value = std::move(value)](int add){ + return *value + add; + }; + int actual = function(1); + if (actual != 43){ + return UnitTestResult(expected_int("call with a unique_ptr capture", 43, actual)); + } + + MoveOnlyFunction moved = std::move(function); + actual = moved(2); + if (actual != 44){ + return UnitTestResult(expected_int("call after a move", 44, actual)); + } + return true; + } +}; + + + +class Test_MoveOnlyFunction_StateNotForked : public UnitTest{ +public: + Test_MoveOnlyFunction_StateNotForked() + : UnitTest("Common::MoveOnlyFunction - Moving keeps one state") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + MoveOnlyFunction counter = [count = 0]() mutable{ + return ++count; + }; + int actual = counter(); + if (actual != 1){ + return UnitTestResult(expected_int("first call", 1, actual)); + } + + // The moved-to wrapper continues the same count. + MoveOnlyFunction constructed = std::move(counter); + actual = constructed(); + if (actual != 2){ + return UnitTestResult(expected_int("call after a move construction", 2, actual)); + } + + MoveOnlyFunction assigned; + assigned = std::move(constructed); + actual = assigned(); + if (actual != 3){ + return UnitTestResult(expected_int("call after a move assignment", 3, actual)); + } + return true; + } +}; + + + +int return_seven(){ + return 7; +} + +class Test_MoveOnlyFunction_Empty : public UnitTest{ +public: + Test_MoveOnlyFunction_Empty() + : UnitTest("Common::MoveOnlyFunction - Empty is false") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + MoveOnlyFunction defaulted; + if (defaulted){ + return UnitTestResult("default constructed: expected empty, got non-empty"); + } + MoveOnlyFunction from_nullptr = nullptr; + if (from_nullptr){ + return UnitTestResult("constructed from nullptr: expected empty, got non-empty"); + } + int (*null_pointer)() = nullptr; + MoveOnlyFunction from_null_pointer = null_pointer; + if (from_null_pointer){ + return UnitTestResult("constructed from a null function pointer: expected empty, got non-empty"); + } + + MoveOnlyFunction from_pointer = &return_seven; + if (!from_pointer){ + return UnitTestResult("constructed from a function pointer: expected non-empty, got empty"); + } + int actual = from_pointer(); + if (actual != 7){ + return UnitTestResult(expected_int("call through a function pointer", 7, actual)); + } + return true; + } +}; + + + +class Test_MoveOnlyFunction_Reassignment : public UnitTest{ +public: + Test_MoveOnlyFunction_Reassignment() + : UnitTest("Common::MoveOnlyFunction - Reassignment") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + // The use count shows whether the wrapper still holds the first + // callable. + auto token = std::make_shared(1); + MoveOnlyFunction function = [token]{ + return *token; + }; + int actual = function(); + if (actual != 1){ + return UnitTestResult(expected_int("first callable", 1, actual)); + } + + function = []{ + return 2; + }; + actual = function(); + if (actual != 2){ + return UnitTestResult(expected_int("call after reassignment", 2, actual)); + } + actual = (int)token.use_count(); + if (actual != 1){ + return UnitTestResult(expected_int("token owners after reassignment", 1, actual)); + } + + function = nullptr; + if (function){ + return UnitTestResult("assigned nullptr: expected empty, got non-empty"); + } + if (function != nullptr){ + return UnitTestResult("assigned nullptr: expected == nullptr, got != nullptr"); + } + return true; + } +}; + + + +} // anonymous namespace + + + +void add_tests_MoveOnlyFunction(UnitTestDatabase& database){ + database.add(); + database.add(); + database.add(); + database.add(); +} + + + +} diff --git a/Common/Cpp/MoveOnlyFunction_Tests.h b/Common/Cpp/MoveOnlyFunction_Tests.h new file mode 100644 index 0000000000..c43f518bdc --- /dev/null +++ b/Common/Cpp/MoveOnlyFunction_Tests.h @@ -0,0 +1,21 @@ +/* Move-Only Function Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_MoveOnlyFunction_Tests_H +#define PokemonAutomation_MoveOnlyFunction_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ + + + +void add_tests_MoveOnlyFunction(UnitTestDatabase& database); + + + +} +#endif diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index cde8df2162..10be448287 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -5,6 +5,7 @@ */ #include "Common/Cpp/ListenerSet.h" +#include "Common/Cpp/MoveOnlyFunction_Tests.h" #include "Common/Cpp/ScopeExit.h" #include "Common/Cpp/PrettyPrint.h" #include "Common/Cpp/TestRunners/TestImageDistortionManager.h" @@ -53,6 +54,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ add_tests_QtEventThreadPool(ret, GlobalThreadPools::computation_normal()); add_tests_BlackBorderDetector(ret); add_tests_ListenerSet(ret); + add_tests_MoveOnlyFunction(ret); add_tests_AudioInfo(ret); add_tests_ChannelMixerMatrix(ret); add_tests_FFTStreamer(ret); @@ -62,6 +64,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ OCR::add_tests(ret); Kernels::add_tests(ret); Pokemon::add_tests_LegPlanner(ret); + Pokemon::add_tests_StoryEvents(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); NintendoSwitch::add_tests_UpdatePopupDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h index 5919dd56b2..e6d709afce 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h @@ -14,6 +14,7 @@ namespace Pokemon{ void add_tests_LegPlanner(UnitTestDatabase& database); +void add_tests_StoryEvents(UnitTestDatabase& database); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StoryEvents.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StoryEvents.cpp new file mode 100644 index 0000000000..99ac0ba560 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StoryEvents.cpp @@ -0,0 +1,446 @@ +/* Story Events + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryEvents.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const char* 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; + for (const TilePos& tile : pose.tiles){ + text += " " + to_string(tile); + } + if (pose.facing){ + text += std::string(" facing ") + direction_name(*pose.facing); + } + return text + " (" + certainty_name(pose.certainty) + ")"; +} + + +bool Outcome::succeeded() const{ + return failure.empty(); +} +Outcome outcome_ok(){ + return Outcome{}; +} +Outcome outcome_failed(std::string failure, std::string detail){ + return Outcome{std::move(failure), std::move(detail)}; +} + +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::string("pose ") + certainty_name(need) + (map.empty() ? "" : " 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); + }); +} + +const char* recovery_name(RecoveryKind kind){ + switch (kind){ + case RecoveryKind::WAIT: + return "wait"; + case RecoveryKind::REANCHOR: + return "re-anchor"; + case RecoveryKind::STOP: + return "stop"; + } + return "?"; +} + + +std::string event_log_line(const std::string& checkpoint, size_t number, const std::string& event, const std::string& status){ + return "[Event] " + checkpoint + "/" + std::to_string(number) + " " + event + ": " + status; +} + + +namespace{ + +std::string describe(const Outcome& outcome){ + return outcome.detail.empty() ? outcome.failure : outcome.failure + ": " + outcome.detail; +} + +// 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 = event.act(state); + if (!outcome.succeeded()){ + return outcome; + } + return check_expects(event, state); +} + +void apply_interrupt_pose(Pose& pose, InterruptPose effect){ + switch (effect){ + case InterruptPose::UNCHANGED: + return; + case InterruptPose::INEXACT: + if (pose.certainty != PoseCertainty::UNKNOWN){ + pose.certainty = PoseCertainty::SET; + } + return; + case InterruptPose::LOST: + pose.tiles.clear(); + pose.facing.reset(); + pose.certainty = PoseCertainty::UNKNOWN; + return; + } +} + + +// 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(EventRun& run, const std::string& status){ + 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(run, "interrupt: " + interrupt.name); + 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 = interrupt.handle(run.state); + if (!handled.succeeded()){ + result.outcome = outcome_failed("interrupt_failed", interrupt.name + ": " + describe(handled)); + return result; + } + } + apply_interrupt_pose(run.state.pose, interrupt.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(EventRun& run, const std::string& failure){ + 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(EventRun& run, Outcome failure){ + while (true){ + Recovery* recovery = next_recovery(run, failure.failure); + if (recovery == nullptr){ + return failure; + } + std::string line = std::string("recover: ") + recovery_name(recovery->kind) + " (" + failure.failure + ")"; + log_status(run, recovery->why.empty() ? line : line + ": " + recovery->why); + if (recovery->kind == RecoveryKind::STOP){ + return failure; + } + if (!recovery->prepare){ + return std::nullopt; + } + Outcome prepared = 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(run, "start"); + for (bool first = true; ; first = false){ + if (!first && already_done(run.event, run.state)){ + log_status(run, "done: already showing"); + return outcome_ok(); + } + Outcome outcome = attempt_event(run.event, run.state); + Next next = after_attempt(run, outcome); + if (next == Next::DONE){ + log_status(run, "done"); + return outcome_ok(); + } + if (next == Next::RETRY){ + continue; + } + if (next == Next::RECOVER){ + std::optional stop = recover(run, std::move(outcome)); + if (!stop){ + continue; + } + outcome = std::move(*stop); + } + log_status(run, "failed: " + describe(outcome)); + return outcome; + } +} + + +CheckpointReport stop_checkpoint(CheckpointReport& report, EventLogger& log, const std::string& id, Outcome failure){ + std::string where = report.failed_event == 0 + ? "" + : " at " + std::to_string(report.failed_event) + " " + report.failed_name; + log("[Checkpoint] " + id + ": failed" + where + ": " + describe(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 = checkpoint.save(state); + return saved.succeeded() ? saved : outcome_failed("save_failed", describe(saved)); +} + +} + + +CheckpointReport run_checkpoint(RunState& state, Checkpoint& checkpoint, EventLogger& log){ + CheckpointReport report; + const std::string& id = checkpoint.id; + log("[Checkpoint] " + id + ": start, " + std::to_string(checkpoint.events.size()) + " events"); + std::optional failing = first_failing(checkpoint.start, state); + if (failing){ + return stop_checkpoint(report, log, id, outcome_failed("start_failed", *failing)); + } + 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(run, "skipped"); + report.events_skipped++; + continue; + } + report.events_run++; + Outcome outcome = run_event(run); + if (!outcome.succeeded()){ + report.failed_event = c + 1; + report.failed_name = event.name; + return stop_checkpoint(report, log, id, std::move(outcome)); + } + } + Outcome finished = finish_checkpoint(state, checkpoint); + if (!finished.succeeded()){ + return stop_checkpoint(report, log, id, std::move(finished)); + } + report.completed = true; + log("[Checkpoint] " + id + ": done, " + std::to_string(report.events_run) + " run, " + std::to_string(report.events_skipped) + " skipped"); + return report; +} + + +namespace{ + +void lint_conditions(std::vector& problems, const std::string& where, const std::vector& conditions){ + for (const Condition& item : conditions){ + if (item.name.empty() || !item.check){ + problems.emplace_back(where + ": a condition without a name or a check"); + } + } +} + +void lint_recoveries(std::vector& problems, const Event& event){ + RecoveryKind last = RecoveryKind::WAIT; + for (const Recovery& recovery : event.recoveries){ + if ((int)recovery.kind < (int)last){ + problems.emplace_back(event.name + ": recovery " + recovery_name(recovery.kind) + " after " + recovery_name(last)); + } + if (recovery.kind != RecoveryKind::STOP && recovery.attempts == 0){ + problems.emplace_back(event.name + ": recovery " + recovery_name(recovery.kind) + " with no attempts"); + } + last = recovery.kind; + } +} + +void lint_event(std::vector& problems, std::set& names, const Event& event){ + if (event.name.empty()){ + problems.emplace_back("an event without a name"); + }else if (!names.insert(event.name).second){ + problems.emplace_back(event.name + ": two events with this name"); + } + if (!event.act){ + problems.emplace_back(event.name + ": no action"); + } + lint_conditions(problems, event.name + " skip_if", event.skip_if); + lint_conditions(problems, event.name + " require", event.require); + lint_conditions(problems, event.name + " expect", event.expect); + lint_recoveries(problems, event); +} + +} + + +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(checkpoint.id + ": no events"); + } + std::set names; + for (const Event& event : checkpoint.events){ + lint_event(problems, names, event); + } + 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(problems, checkpoint.id + " start", checkpoint.start); + lint_conditions(problems, checkpoint.id + " end", checkpoint.end); + return problems; +} + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StoryEvents.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StoryEvents.h new file mode 100644 index 0000000000..c70f2f72f2 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StoryEvents.h @@ -0,0 +1,202 @@ +/* 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. + * + * 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 "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How much of the pose is known. COLUMN and ROW pin one axis (a wall, a +// door); SET means one of `tiles`. +enum class PoseCertainty{ + TILE, + COLUMN, + ROW, + SET, + UNKNOWN, +}; +const char* certainty_name(PoseCertainty certainty); + +// Whether a pose known to `have` is good enough for an event that needs `need`. +bool certainty_covers(PoseCertainty have, PoseCertainty need); + +// Where the player is believed to be. The screen is read; the pose is +// tracked, and only an anchor (a wall, a door, an NPC who answered) makes +// it certain. +struct Pose{ + std::string map; + std::vector tiles; + std::optional facing; + PoseCertainty certainty = PoseCertainty::UNKNOWN; +}; +std::string to_string(const Pose& pose); + + +// What a run knows. Flags are set only by confirmed effects and are lost +// on a reload. +struct RunState{ + Pose pose; + std::set flags; +}; + + +// How an action or a check ended: empty `failure` is success; otherwise a +// name that recoveries match (e.g. "probe_exhausted"). +struct Outcome{ + std::string failure; + std::string detail; + + bool succeeded() const; +}; +Outcome outcome_ok(); +Outcome outcome_failed(std::string failure, std::string detail = ""); + + +using Act = MoveOnlyFunction; +using Check = MoveOnlyFunction; + +// A question the screen (or the run state) answers, named for the log. +struct Condition{ + std::string name; + Check check; +}; +Condition condition(std::string name, Check check); + +// Holds while the pose is on `map` (any map if empty) and at least as +// certain as `need`. +Condition pose_known(std::string map, PoseCertainty need); + + +enum class RecoveryKind{ + WAIT, // Something transient (a wanderer, a slow scene): wait, try again. + REANCHOR, // The pose is in doubt: confirm it on a landmark, try again. + STOP, // Nothing to do: stop the checkpoint. +}; +const char* recovery_name(RecoveryKind kind); + +// Answers a failure named `on` (any failure if empty): runs `prepare`, if +// any, and tries the event again, up to `attempts` times. +struct Recovery{ + std::string on; + RecoveryKind kind = RecoveryKind::STOP; + Act prepare; + size_t attempts = 1; + std::string why; +}; + + +struct Event{ + std::string name; + std::string why; + // Skipped when all of these hold (and there is at least one). + std::vector skip_if; + // Must hold before `act`; a failure is "require_failed". + std::vector require; + Act act; + // Must hold after `act`; a failure is "expect_failed". + std::vector expect; + // Written to the run's pose once the event succeeds. An action that + // learns its pose as it goes (the row that answered) writes it itself. + std::optional pose_learned; + // In order of escalation. + std::vector recoveries; +}; + + +enum class InterruptPose{ + UNCHANGED, // Cleared where we stood (a talk-only trainer). + INEXACT, // Moved an unknown part of a leg: one of the tiles we had. + LOST, // Anywhere. +}; +enum class ResumePolicy{ + RETRY_EVENT, // Run the event again, from its skip_if. + RECHECK_EXPECT, // The action may have finished: done if its expects hold, else retry. + STOP, // Stop the checkpoint. +}; + +// Something that can stop an action part-way. +struct Interrupt{ + std::string name; + Check detect; + Act handle; + InterruptPose pose = InterruptPose::UNCHANGED; + ResumePolicy resume = ResumePolicy::RETRY_EVENT; +}; + + +struct Checkpoint{ + std::string id; + // Must hold before the first event (the save it starts from). + std::vector start; + std::vector interrupts; + std::vector events; + // Must hold after the last event. + std::vector end; + // Saves the game after the end check, if set. + Act save; + size_t max_interrupts_per_event = 5; +}; + + +struct CheckpointReport{ + bool completed = false; + // 1-based number of the event that failed; 0 for the start or end check + // or the save, or when nothing failed. + size_t failed_event = 0; + std::string failed_name; + Outcome failure; + size_t events_run = 0; + size_t events_skipped = 0; +}; + +using EventLogger = MoveOnlyFunction; + + +// One log line, in a format the lab watcher parses: +// [Event] 00.04/3 talk_mom: start +// [Event] 00.04/3 talk_mom: failed: expect_failed: has_parcel +std::string event_log_line(const std::string& checkpoint, size_t number, const std::string& event, const std::string& status); + +// 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); + +// 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); + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StoryEvents_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StoryEvents_Tests.cpp new file mode 100644 index 0000000000..433065884f --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_StoryEvents_Tests.cpp @@ -0,0 +1,550 @@ +/* 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 "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_Navigation_Tests.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 += "\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; +} + +Act record(World& world, std::string what){ + 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(world, "walk"))); + checkpoint.events.push_back(make_event("talk_lady", record(world, "talk"))); + checkpoint.events.push_back(make_event("save", record(world, "save"))); + 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 "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 "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 "Expected three talks, the last answered:" + lines.all(); + } + if (!lines.has("[Event] 00.04/1 talk_poke_mart_lady: recover: wait (expect_failed)")){ + return "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(world, "wait"))); + event.recoveries.push_back(recovery("expect_failed", RecoveryKind::REANCHOR, 1, [&world](RunState& state){ + world.trace.push_back("anchor"); + world.rows_off = 0; + state.pose.certainty = PoseCertainty::TILE; + return outcome_ok(); + })); + 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 "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(world, "enter"))); + checkpoint.events.push_back(talk_to_mom(world)); + checkpoint.events.back().recoveries[1].prepare = record(world, "anchor"); // An anchor that does not help. + checkpoint.events.push_back(make_event("mom_dialogue", record(world, "dialogue"))); + 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 "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.lines.back() != "[Checkpoint] 00.04: failed at 2 talk_mom: expect_failed: dialogue opened" + ){ + return "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 "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 "Unexpected log:" + lines.all(); + } + return true; +} + +Interrupt wild_battle(World& world, ResumePolicy resume){ + 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::INEXACT; + 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.tiles = {TilePos{42, 3}}; + corner.certainty = PoseCertainty::TILE; + event.pose_learned = corner; + event.recoveries.push_back(recovery("require_failed", RecoveryKind::REANCHOR, 1, [&world](RunState& state){ + world.trace.push_back("anchor"); + state.pose.certainty = PoseCertainty::TILE; + return outcome_ok(); + })); + return event; +} + +RunState at_catch_spot(){ + RunState state; + state.pose.map = "Route 202"; + state.pose.tiles = {TilePos{10, 20}}; + state.pose.certainty = PoseCertainty::TILE; + return state; +} + +UnitTestResult test_interrupt_mid_event(){ + World world; + world.walk_failures = 1; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.interrupts.push_back(wild_battle(world, ResumePolicy::RETRY_EVENT)); + 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 "Expected flee, re-anchor, walk again:" + lines.all(); + } + if (!lines.has("[Event] 00.04/1 walk_to_corner: interrupt: wild_battle")){ + return "Expected the interrupt logged:" + lines.all(); + } + if (state.pose.map != "Route 201" || state.pose.tiles.size() != 1 || state.pose.tiles[0] != TilePos{42, 3}){ + return "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(world, ResumePolicy::RECHECK_EXPECT); + 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 "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(world, ResumePolicy::RETRY_EVENT)); + 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 "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(world, "train"))); + 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 "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 "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(world, "walk"))); + checkpoint.end.push_back(condition("parcel in the Bag", [&world](RunState&){ return world.parcel; })); + checkpoint.save = record(world, "save"); + 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(); + state.pose.facing = Direction::NORTH; + if (to_string(state.pose) != "Route 202 (10, 20) facing north (tile)"){ + return "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; +} + +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 += "\n" + problem; + } + return "Expected 4 problems:" + text; + } + return true; +} + + +class Test_StoryEvents : public UnitTest{ +public: + Test_StoryEvents(std::string name, std::function body) + : UnitTest("Pokemon::StoryEvents - " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_body(); + } + +private: + std::function m_body; +}; + +} + + +void add_tests_StoryEvents(UnitTestDatabase& database){ + database.add("events run in order", test_runs_events_in_order); + database.add("a done event is skipped", test_skips_done_event); + database.add("a failed expect is waited out", test_expect_failure_waited_out); + database.add("recoveries escalate to a re-anchor", test_escalates_to_reanchor); + database.add("a stop names the failed event", test_stop_names_failed_event); + database.add("an unanswered failure stops", test_unmatched_failure_stops); + database.add("an interrupt mid-event", test_interrupt_mid_event); + database.add("an interrupt rechecks the expects", test_interrupt_recheck_expect); + database.add("too many interrupts", test_too_many_interrupts); + database.add("resume after a reload", test_resume_after_reload); + database.add("start, end and save", test_start_end_and_save); + database.add("pose certainty", test_pose_certainty); + database.add("lint", test_lint); +} + + + +} +} diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index c650d0494d..3b8bdff17f 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -118,6 +118,9 @@ file(GLOB CORE_LIBRARY_SOURCES ../Common/Cpp/Logging/MultiOutputLogger.h ../Common/Cpp/Logging/TaggedLogger.cpp ../Common/Cpp/Logging/TaggedLogger.h + ../Common/Cpp/MoveOnlyFunction.h + ../Common/Cpp/MoveOnlyFunction_Tests.cpp + ../Common/Cpp/MoveOnlyFunction_Tests.h ../Common/Cpp/Options/BatchOption.cpp ../Common/Cpp/Options/BatchOption.h ../Common/Cpp/Options/BooleanCheckBoxOption.cpp @@ -1439,6 +1442,9 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_LegPlanner.h Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h + Source/Pokemon/Navigation/Pokemon_StoryEvents.cpp + Source/Pokemon/Navigation/Pokemon_StoryEvents.h + Source/Pokemon/Navigation/Pokemon_StoryEvents_Tests.cpp Source/Pokemon/Options/Pokemon_BoxSortingTable.cpp Source/Pokemon/Options/Pokemon_BoxSortingTable.h Source/Pokemon/Options/Pokemon_EncounterBotOptions.h