From 32493f02b4467e4284c261fbc858490925772eed Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 13:04:41 -0800 Subject: [PATCH 1/4] AutoStory: story checkpoint data and its JSON reader The shared story data a game reads from its checkpoint files: steps, their action specs and typed args, the checkpoint with its zone start and metadata, outcomes and run log lines, the authored-checkpoint envelope, and the shared execution fields (save autosave/unverified/absent, reload_when_chained) that mark a story's rows. Trimmed from the PLZA AutoStory branch to what PLZA's first slice reads; no tile poses, dev files or postconditions. --- .../ComputerPrograms_UnitTestRunner.cpp | 2 + .../Data/Pokemon_AuthoredCheckpointJson.cpp | 48 ++++ .../Data/Pokemon_AuthoredCheckpointJson.h | 64 +++++ .../Pokemon_AuthoredCheckpointJson_Tests.cpp | 151 ++++++++++ .../Pokemon_AuthoredCheckpointJson_Tests.h | 23 ++ .../AutoStory/Data/Pokemon_StoryFiles.cpp | 51 ++++ .../AutoStory/Data/Pokemon_StoryFiles.h | 117 ++++++++ .../Data/Pokemon_StoryFiles_Tests.cpp | 266 ++++++++++++++++++ .../AutoStory/Data/Pokemon_StoryFiles_Tests.h | 24 ++ .../Data/Pokemon_StoryRowExecution.cpp | 90 ++++++ .../Data/Pokemon_StoryRowExecution.h | 86 ++++++ .../AutoStory/Data/Pokemon_StoryStepJson.cpp | 259 +++++++++++++++++ .../AutoStory/Data/Pokemon_StoryStepJson.h | 51 ++++ .../Data/Pokemon_StoryStepJson_Tests.cpp | 215 ++++++++++++++ .../Data/Pokemon_StoryStepJson_Tests.h | 23 ++ .../AutoStory/Engine/Pokemon_ZonePose.cpp | 26 ++ .../AutoStory/Engine/Pokemon_ZonePose.h | 37 +++ .../AutoStory/Pokemon_AutoStory_Tests.h | 38 +++ .../Pokemon/AutoStory/Pokemon_MapUtil.h | 44 +++ .../Pokemon/AutoStory/Pokemon_StoryLog.cpp | 85 ++++++ .../Pokemon/AutoStory/Pokemon_StoryLog.h | 89 ++++++ .../AutoStory/Pokemon_StoryLog_Tests.cpp | 168 +++++++++++ .../AutoStory/Pokemon_StoryLog_Tests.h | 23 ++ .../AutoStory/Pokemon_StoryOutcome.cpp | 49 ++++ .../Pokemon/AutoStory/Pokemon_StoryOutcome.h | 62 ++++ .../Pokemon/AutoStory/Pokemon_StoryPose.cpp | 59 ++++ .../Pokemon/AutoStory/Pokemon_StoryPose.h | 73 +++++ .../AutoStory/Types/Pokemon_DeclaredPose.h | 40 +++ .../Types/Pokemon_StoryActionArg.cpp | 22 ++ .../AutoStory/Types/Pokemon_StoryActionArg.h | 89 ++++++ .../Types/Pokemon_StoryActionArg_Tests.cpp | 117 ++++++++ .../Types/Pokemon_StoryActionArg_Tests.h | 23 ++ .../Types/Pokemon_StoryActionSpec.cpp | 71 +++++ .../AutoStory/Types/Pokemon_StoryActionSpec.h | 62 ++++ .../AutoStory/Types/Pokemon_StoryCheckpoint.h | 40 +++ .../Types/Pokemon_StoryCheckpointMetadata.cpp | 37 +++ .../Types/Pokemon_StoryCheckpointMetadata.h | 52 ++++ .../AutoStory/Types/Pokemon_StoryStep.h | 41 +++ .../AutoStory/Types/Pokemon_StoryStepKind.cpp | 52 ++++ .../AutoStory/Types/Pokemon_StoryStepKind.h | 45 +++ SerialPrograms/cmake/SourceFiles.cmake | 39 +++ 41 files changed, 2953 insertions(+) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_MapUtil.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcome.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcome.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_DeclaredPose.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 03cded771c..4be358605a 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -15,6 +15,7 @@ #include "Common/Qt/QtThreadPool_Tests.h" #include "Kernels/Kernels_Tests.h" #include "Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h" +#include "Pokemon/AutoStory/Pokemon_AutoStory_Tests.h" #include "Pokemon/Options/Pokemon_StoryRangeOptions_Tests.h" #include "CommonFramework/AudioPipeline/AudioInfo_Tests.h" #include "CommonFramework/AudioPipeline/Tools/ChannelMixer.h" @@ -73,6 +74,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ OCR::add_tests(ret); Kernels::add_tests(ret); Pokemon::add_tests_AutoStorySelect(ret); + Pokemon::add_tests_AutoStory(ret); Pokemon::add_tests_StoryRangeOptions(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp new file mode 100644 index 0000000000..2cec518b33 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp @@ -0,0 +1,48 @@ +/* Shared Authored Checkpoint JSON + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_StoryStepJson.h" +#include "Pokemon_AuthoredCheckpointJson.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +void validate_json_fields( + const JsonObject& object, std::initializer_list fields, std::string_view source +){ + if (object.size() != fields.size()){ + throw ParseException(std::format("{}: missing or extra authored checkpoint fields.", source)); + } + for (std::string_view field : fields){ + object.get_value_throw(std::string(field), std::string(source)); + } +} + +StoryCheckpoint read_authored_checkpoint( + const JsonValue& value, std::string_view game, std::string_view source, + const ExecutionReader& read_execution, std::span actions +){ + const JsonObject& root = value.to_object_throw(std::string(source)); + validate_json_fields(root, {"format", "game", "checkpoint", "execution"}, source); + if (game.empty() || root.get_string_throw("format") != "pokesim-authored-checkpoint/1" + || root.get_string_throw("game") != game + ){ + throw ParseException(std::format("{}: unsupported authored checkpoint format/game.", source)); + } + StoryCheckpoint checkpoint = read_story_checkpoint(root.get_value_throw("checkpoint"), source, actions); + read_execution(root.get_object_throw("execution", std::string(source)), source); + return checkpoint; +} + + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h new file mode 100644 index 0000000000..baabaf74e0 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h @@ -0,0 +1,64 @@ +/* Shared Authored Checkpoint JSON + * + * From: https://github.com/PokemonAutomation/ + * + * Reading an authored checkpoint file: the shared + * StoryCheckpoint (Pokemon_StoryStepJson.h) in an envelope that names the + * game, plus the game's own execution object, which the game parses into + * its own type through a reader it passes in. Only parsing: + * nothing here binds or runs a step, and nothing read keeps JSON. + * + * The envelope's "format" is "pokesim-authored-checkpoint/1": the + * files are written by PokemonSimulation's story tools, which plan + * and check a checkpoint's steps offline; a file written by hand uses the + * same name. + * + */ + +#ifndef PokemonAutomation_Pokemon_AuthoredCheckpointJson_H +#define PokemonAutomation_Pokemon_AuthoredCheckpointJson_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The game's reader of an envelope's execution object: it parses the +// object into the game's own type and throws ParseException when it is +// malformed. +using ExecutionReader = std::function; + +// Require exactly these fields, including fields whose value is null/zero/false. +// Missing/unknown fields throw ParseException with the document source. +void validate_json_fields( + const JsonObject& object, std::initializer_list fields, std::string_view source +); + +// The checkpoint of `game`'s strict authored envelope, its steps read +// against `actions` (read_story_checkpoint()); its execution object goes +// to `read_execution`. +StoryCheckpoint read_authored_checkpoint( + const JsonValue& value, std::string_view game, std::string_view source, + const ExecutionReader& read_execution, + std::span actions +); + +// A JSON file built into the program: its name without ".json", and its +// text. +using EmbeddedJsonFile = std::pair; + + + +} // namespace Pokemon +} // namespace PokemonAutomation + +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp new file mode 100644 index 0000000000..5585dbb672 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp @@ -0,0 +1,151 @@ +/* Shared Authored Checkpoint JSON Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_AuthoredCheckpointJson.h" +#include "Pokemon_AuthoredCheckpointJson_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// Documents intentionally contain no game headers or native bookkeeping. +const std::string FRLG = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{"id":"00.05","title":"Parcel","events":[{"id":"first","kind":"talk"},{"id":"second","kind":"scene"}]},"execution":{"menu":"before_pokedex"}})"; +const std::string BDSP = R"({"format":"pokesim-authored-checkpoint/1","game":"bdsp","checkpoint":{"id":"01.03","title":"Mine","events":[{"id":"roark","kind":"talk"}]},"execution":{"on_failure":"reload_and_retry","saves_in":"Oreburgh City"}})"; + +// How a case fails, if it does. +enum class Failure{ + NONE, + PARSE, +}; + +struct AuthoredCase{ + std::string name; + struct Input{ + std::string json; + std::string game = "frlg"; + }; + + struct Expectation{ + std::string checkpoint = "00.05"; + std::string execution = R"({"menu":"before_pokedex"})"; + std::vector events = {"first", "second"}; + Failure failure = Failure::NONE; + }; + + Input input; + Expectation expectation; +}; + +const AuthoredCase CASES[] = { + {.name = "FRLG envelope", .input = {.json = FRLG}, .expectation = {}}, + {.name = "BDSP envelope", .input = {.json = BDSP, .game = "bdsp"}, .expectation = { + .checkpoint = "01.03", .execution = R"({"on_failure":"reload_and_retry","saves_in":"Oreburgh City"})", .events = {"roark"}}}, + {.name = "wrong game", .input = {.json = BDSP}, .expectation = {.failure = Failure::PARSE}}, + {.name = "empty expected game", .input = {.json = FRLG, .game = ""}, .expectation = {.failure = Failure::PARSE}}, + {.name = "wrong format", .input = {.json = R"({"format":"future","game":"frlg","checkpoint":{},"execution":{}})"}, .expectation = {.failure = Failure::PARSE}}, + {.name = "missing execution", .input = {.json = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{}})"}, .expectation = {.failure = Failure::PARSE}}, + {.name = "same count wrong field", .input = {.json = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{},"extra":{}})"}, .expectation = {.failure = Failure::PARSE}}, + {.name = "extra envelope field", .input = {.json = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{},"execution":{},"extra":0})"}, .expectation = {.failure = Failure::PARSE}}, + {.name = "execution must be object", .input = {.json = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{"id":"x","title":"X","events":[]},"execution":false})"}, .expectation = {.failure = Failure::PARSE}}, + {.name = "invalid common action", .input = {.json = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{"id":"x","title":"X","events":[{"id":"bad","kind":"magic"}]},"execution":{}})"}, .expectation = {.failure = Failure::PARSE}}, + {.name = "execution stays game owned", .input = {.json = R"({"format":"pokesim-authored-checkpoint/1","game":"future","checkpoint":{"id":"x","title":"X","events":[]},"execution":{"zero":0,"false":false,"null":null}})", .game = "future"}, .expectation = { + .checkpoint = "x", .execution = R"({"zero":0,"false":false,"null":null})", .events = {}}}, +}; + + +// The actions the documents name: none, so each step is its kind's default. +std::span story_actions(){ + return {}; +} + +// What a test reads: the checkpoint, and the execution object its reader +// kept. +struct Loaded{ + StoryCheckpoint checkpoint; + JsonObject execution; +}; + +// A reader that keeps the execution object in `kept`. +ExecutionReader keep_execution(JsonObject& kept){ + return [&kept](const JsonObject& execution, std::string_view){ + kept = execution.clone(); + }; +} + +// "" when `actual` is what `test` expects, else what was expected and +// what was read. +std::string check_loaded(const Loaded& actual, const AuthoredCase& test){ + if (test.expectation.failure != Failure::NONE){ + return "Expected rejection, read accepted authored checkpoint."; + } + if (actual.checkpoint.id != test.expectation.checkpoint){ + return std::format("Expected checkpoint {}, read {}", test.expectation.checkpoint, actual.checkpoint.id); + } + if (!(JsonValue(actual.execution.clone()) == parse_json(test.expectation.execution))){ + return std::format("Expected execution {}, read {}", test.expectation.execution, actual.execution.dump()); + } + std::vector events; + for (const StoryStep& step : actual.checkpoint.steps){ + events.push_back(step.name); + } + if (events != test.expectation.events){ + return "Expected authored event IDs in their original order."; + } + return ""; +} + +// "" when `test` reads or fails as expected. +std::string check_case(const AuthoredCase& test){ + try{ + Loaded actual; + actual.checkpoint = read_authored_checkpoint( + parse_json(test.input.json), test.input.game, test.name, keep_execution(actual.execution), story_actions() + ); + return check_loaded(actual, test); + }catch (const ParseException& error){ + return test.expectation.failure == Failure::PARSE ? "" : std::format("Unexpected parse failure: {}", error.message()); + } +} + + +class AuthoredJsonTest : public UnitTest{ +public: + explicit AuthoredJsonTest(AuthoredCase test) + : UnitTest(std::format("Pokemon::AuthoredCheckpointJson - {}", test.name)) + , m_case(std::move(test)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string error = check_case(m_case); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } + +private: + AuthoredCase m_case; +}; + + +} // namespace + + +void add_tests_AuthoredCheckpointJson(UnitTestDatabase& database){ + for (const AuthoredCase& test : CASES){ + database.add(test); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.h new file mode 100644 index 0000000000..ae88e442a4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.h @@ -0,0 +1,23 @@ +/* Authored Checkpoint JSON Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_AuthoredCheckpointJson_Tests_H +#define PokemonAutomation_Pokemon_AuthoredCheckpointJson_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the shared authored envelope, game identity and embedded-resource loading. +void add_tests_AuthoredCheckpointJson(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.cpp new file mode 100644 index 0000000000..8f8abb5529 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.cpp @@ -0,0 +1,51 @@ +/* Story Files + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_StoryFiles.h" + +namespace PokemonAutomation{ +namespace Pokemon{ +namespace detail{ + + +void add_story_row( + std::string_view id, const StoryRowExecution& execution, RowSave start, + std::optional previous, std::string_view source, StoryRows& rows +){ + if (execution.reload != StoryReload::NEVER){ + if (start == RowSave::WITHOUT_SAVE){ + throw ParseException(std::format("{}: reload_when_chained on a checkpoint with no save to reload", source)); + } + if (!previous || !rows.autosaves.contains(*previous)){ + throw ParseException(std::format( + "{}: reload_when_chained after a checkpoint that does not end on the game's autosave: the reload would load an older save", + source + )); + } + rows.reload_when_chained.emplace(id); + } + if (execution.reload == StoryReload::ALWAYS){ + rows.reload_always.emplace(id); + } + switch (execution.save){ + case StoryRowSave::NONE: + break; + case StoryRowSave::AUTOSAVE: + rows.autosaves.emplace(id); + break; + case StoryRowSave::UNVERIFIED: + rows.unverified_autosaves.emplace(id); + break; + } +} + + + +} // namespace detail +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.h new file mode 100644 index 0000000000..03d27635da --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.h @@ -0,0 +1,117 @@ +/* Story Files + * + * From: https://github.com/PokemonAutomation/ + * + * A game's story read from its checkpoint files, passed in by name and + * text. The game reads each file into its own checkpoint type; this reads + * the shared execution fields (Pokemon_StoryRowExecution.h) into the rows + * they mark, and checks what holds for every game: a row reloads only a + * save it can count on. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryFiles_H +#define PokemonAutomation_Pokemon_StoryFiles_H + +#include +#include +#include +#include +#include +#include +#include "Pokemon_AuthoredCheckpointJson.h" +#include "Pokemon_StoryRowExecution.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What a game reads from one checkpoint file. +template +struct StoryFileRow{ + Checkpoint checkpoint; + StoryRowExecution execution; +}; + +// How a game reads its checkpoint files. +template +struct StoryFileReader{ + // The file `text`'s checkpoint and shared execution fields + // (read_story_row_execution()); `source` names the file in errors. + // Throws ParseException when it is malformed. + std::function(std::string_view text, std::string_view source)> read; + // Whether a row starts with no save to load (a new game): it may not + // reload. None set: every row starts from a save. + std::function starts_without_save = {}; +}; + +// The story of the built-in checkpoint files `builtin`, in their order. +// Throws ParseException naming the file when a file does not parse, or a +// row reloads a save it cannot count on in the order the story plays. +template +StoryData load_story_data( + std::span builtin, const StoryFileReader& reader +); + +// The rows a run from `first` to `last` of `rows` plays, in order. Empty +// if `first` comes after `last` or `last` is past the end. +template +std::vector story_run_rows(std::span rows, size_t first, size_t last); + + + +namespace detail{ + +// Whether a row starts from a save, which a reload can load. +enum class RowSave{ + FROM_SAVE, + WITHOUT_SAVE, // a new game +}; + +// Adds row `id` to the sets of `rows`. Throws ParseException naming +// `source` when it reloads and starts WITHOUT_SAVE or the row it follows +// (`previous`, none for the first row) does not end on the game's +// autosave: a reload loads the last save, which must be that autosave. +void add_story_row( + std::string_view id, const StoryRowExecution& execution, RowSave start, + std::optional previous, std::string_view source, StoryRows& rows +); + +} // namespace detail + + + +template +StoryData load_story_data( + std::span builtin, const StoryFileReader& reader +){ + StoryData data; + for (const auto& [name, text] : builtin){ + StoryFileRow row = reader.read(text, name); + const bool new_game = reader.starts_without_save && reader.starts_without_save(row.checkpoint); + const std::optional previous = data.checkpoints.empty() + ? std::nullopt + : std::optional(data.checkpoints.back().id); + detail::add_story_row( + row.checkpoint.id, row.execution, + new_game ? detail::RowSave::WITHOUT_SAVE : detail::RowSave::FROM_SAVE, + previous, name, data + ); + data.checkpoints.push_back(std::move(row.checkpoint)); + } + return data; +} + +template +std::vector story_run_rows(std::span rows, size_t first, size_t last){ + if (first > last || last >= rows.size()){ + return {}; + } + return std::vector(rows.begin() + first, rows.begin() + last + 1); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.cpp new file mode 100644 index 0000000000..70e1b1e95b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.cpp @@ -0,0 +1,266 @@ +/* Story Files Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_StoryFiles.h" +#include "Pokemon_StoryFiles_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// A checkpoint file of the test game: {"id", "title", "execution"}, its +// execution the shared fields and the game's own "note". 00.00 is its new +// game, which starts without a save. +std::string file_text(std::string_view id, std::string_view execution, std::string_view title = "Row"){ + return std::format(R"({{"id": "{}", "title": "{}", "execution": {}}})", id, title, execution); +} + +StoryFileRow read_test_file(std::string_view text, std::string_view source){ + const JsonValue value = parse_json(std::string(text)); + const JsonObject& object = value.to_object_throw(std::string(source)); + StoryFileRow row; + row.checkpoint.id = object.get_string_throw("id", std::string(source)); + row.checkpoint.title = object.get_string_throw("title", std::string(source)); + row.execution = read_story_row_execution(object.get_object_throw("execution", std::string(source)), source, {"note"}); + return row; +} + +const StoryFileReader TEST_READER{ + .read = read_test_file, + .starts_without_save = [](const StoryCheckpoint& checkpoint){ + return checkpoint.id == "00.00"; + }, +}; + +// "a b": the strings, space-separated. +std::string joined(const std::vector& texts){ + std::string text; + for (const std::string& part : texts){ + text += (text.empty() ? "" : " ") + part; + } + return text; +} +std::string joined(const std::set>& texts){ + return joined(std::vector(texts.begin(), texts.end())); +} + +std::vector ids(const std::vector& rows){ + std::vector result; + for (const StoryCheckpoint& row : rows){ + result.push_back(row.id); + } + return result; +} + +// "rows 01.00 01.01 | titles Row Row | autosave 01.00 | unverified | chained 01.01 | always " +std::string summary(const StoryData& data){ + std::vector titles; + for (const StoryCheckpoint& row : data.checkpoints){ + titles.push_back(row.title); + } + return std::format( + "rows {} | titles {} | autosave {} | unverified {} | chained {} | always {}", + joined(ids(data.checkpoints)), joined(titles), joined(data.autosaves), joined(data.unverified_autosaves), + joined(data.reload_when_chained), joined(data.reload_always) + ); +} + + +struct LoadCase{ + std::string name; + struct Input{ + std::vector builtin; + }; + Input input; + struct Expectation{ + // summary() of the story read; none when it fails. + std::optional summary = std::nullopt; + // What the ParseException's message contains when it fails. + std::string error = {}; + }; + Expectation expectation; +}; + +const EmbeddedJsonFile ROW_0 = {"test-01.00.plan", file_text("01.00", R"({"save": "autosave"})")}; +const EmbeddedJsonFile ROW_1 = {"test-01.01.plan", file_text("01.01", R"({"reload_when_chained": true, "note": 1})")}; +const EmbeddedJsonFile ROW_2 = {"test-01.02.plan", file_text("01.02", R"({"save": "unverified"})")}; + +const LoadCase LOAD_CASES[] = { + { + .name = "built-in files in order, their shared execution fields read", + .input = {.builtin = {ROW_0, ROW_1, ROW_2}}, + .expectation = {.summary = "rows 01.00 01.01 01.02 | titles Row Row Row | autosave 01.00 | unverified 01.02 | chained 01.01 | always "}, + }, + { + .name = "reload_when_chained always", + .input = {.builtin = {ROW_0, {"test-01.01.plan", file_text("01.01", R"({"reload_when_chained": "always"})")}}}, + .expectation = {.summary = "rows 01.00 01.01 | titles Row Row | autosave 01.00 | unverified | chained 01.01 | always 01.01"}, + }, + { + .name = "an unknown execution field fails", + .input = {.builtin = {{"test-01.00.plan", file_text("01.00", R"({"dev_mode": true})")}}}, + .expectation = {.error = "unknown execution field dev_mode"}, + }, + { + .name = "save autosave", + .input = {.builtin = {ROW_0}}, + .expectation = {.summary = "rows 01.00 | titles Row | autosave 01.00 | unverified | chained | always "}, + }, + { + .name = "save unverified", + .input = {.builtin = {{"test-01.00.plan", file_text("01.00", R"({"save": "unverified"})")}}}, + .expectation = {.summary = "rows 01.00 | titles Row | autosave | unverified 01.00 | chained | always "}, + }, + { + .name = "save left out", + .input = {.builtin = {{"test-01.00.plan", file_text("01.00", "{}")}}}, + .expectation = {.summary = "rows 01.00 | titles Row | autosave | unverified | chained | always "}, + }, + { + .name = "save menu fails", + .input = {.builtin = {{"test-01.00.plan", file_text("01.00", R"({"save": "menu"})")}}}, + .expectation = {.error = "save is \"autosave\", \"unverified\" or left out"}, + }, + { + .name = "a save other than autosave or unverified fails", + .input = {.builtin = {{"test-01.00.plan", file_text("01.00", R"({"save": "card"})")}}}, + .expectation = {.error = "save is \"autosave\", \"unverified\" or left out"}, + }, + { + .name = "reload_when_chained false fails", + .input = {.builtin = {ROW_0, {"test-01.01.plan", file_text("01.01", R"({"reload_when_chained": false})")}}}, + .expectation = {.error = "reload_when_chained is true, \"always\" or left out"}, + }, + { + .name = "reload_when_chained after a row that does not autosave fails", + .input = {.builtin = {{"test-01.00.plan", file_text("01.00", "{}")}, ROW_1}}, + .expectation = {.error = "test-01.01.plan: reload_when_chained after a checkpoint that does not end on the game's autosave"}, + }, + { + .name = "reload_when_chained after an unverified autosave fails", + .input = {.builtin = {{"test-01.00.plan", file_text("01.00", R"({"save": "unverified"})")}, ROW_1}}, + .expectation = {.error = "test-01.01.plan: reload_when_chained after a checkpoint that does not end on the game's autosave"}, + }, + { + .name = "reload_when_chained on the first row fails", + .input = {.builtin = {ROW_1}}, + .expectation = {.error = "does not end on the game's autosave"}, + }, + { + .name = "reload_when_chained on the new game fails", + .input = {.builtin = {ROW_0, {"test-00.00.plan", file_text("00.00", R"({"reload_when_chained": true})")}}}, + .expectation = {.error = "test-00.00.plan: reload_when_chained on a checkpoint with no save to reload"}, + }, +}; + +UnitTestResult check_load(const LoadCase& test){ + std::string got; + std::string error; + try{ + got = summary(load_story_data(test.input.builtin, TEST_READER)); + }catch (const ParseException& e){ + error = e.message(); + } + if (test.expectation.summary){ + if (!error.empty()){ + return std::format("expected \"{}\", failed: {}", *test.expectation.summary, error); + } + if (got != *test.expectation.summary){ + return std::format("expected \"{}\", got \"{}\"", *test.expectation.summary, got); + } + return true; + } + if (error.find(test.expectation.error) == std::string::npos){ + return std::format("expected a failure with \"{}\", got \"{}\"", test.expectation.error, error.empty() ? got : error); + } + return true; +} + + +struct RowsCase{ + std::string name; + struct Input{ + size_t first = 0; + size_t last = 0; + }; + Input input; + struct Expectation{ + std::string rows = {}; + }; + Expectation expectation; +}; + +// 01.00, 01.01, 01.02. +const RowsCase ROWS_CASES[] = { + {.name = "every row", .input = {.first = 0, .last = 2}, .expectation = {.rows = "01.00 01.01 01.02"}}, + {.name = "a run from one row to a later one", .input = {.first = 1, .last = 2}, .expectation = {.rows = "01.01 01.02"}}, + {.name = "no rows for a start after the end", .input = {.first = 2, .last = 1}, .expectation = {.rows = ""}}, + {.name = "no rows for an end past the table", .input = {.first = 0, .last = 3}, .expectation = {.rows = ""}}, +}; + +UnitTestResult check_rows(const RowsCase& test){ + std::vector rows; + for (std::string_view id : {"01.00", "01.01", "01.02"}){ + StoryCheckpoint row; + row.id = std::string(id); + rows.push_back(std::move(row)); + } + const std::string got = joined(ids(story_run_rows(rows, test.input.first, test.input.last))); + if (got != test.expectation.rows){ + return std::format("expected \"{}\", got \"{}\"", test.expectation.rows, got); + } + return true; +} + + +template +class StoryFilesTest : public UnitTest{ +public: + using Check = UnitTestResult (*)(const Case&); + + StoryFilesTest(std::string_view suite, Case test_case, Check check) + : UnitTest(std::format("Pokemon::StoryFiles - {}: {}", suite, test_case.name)) + , m_case(std::move(test_case)) + , m_check(check) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_check(m_case); + } + +private: + Case m_case; + Check m_check; +}; + +} // namespace + + +void add_tests_StoryFiles(UnitTestDatabase& database){ + for (const LoadCase& test : LOAD_CASES){ + database.add>("load", test, check_load); + } + for (const RowsCase& test : ROWS_CASES){ + database.add>("rows", test, check_rows); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.h new file mode 100644 index 0000000000..5f0804951a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.h @@ -0,0 +1,24 @@ +/* Story Files Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryFiles_Tests_H +#define PokemonAutomation_Pokemon_StoryFiles_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers the tests of a story read from built-in and dev checkpoint +// files, and of the shared execution fields. +void add_tests_StoryFiles(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.cpp new file mode 100644 index 0000000000..2938d00089 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.cpp @@ -0,0 +1,90 @@ +/* Story Row Execution + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon_StoryRowExecution.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +constexpr std::string_view SHARED_FIELDS[] = {"save", "reload_when_chained"}; + +bool is_known_field(std::string_view key, std::initializer_list game_fields){ + for (std::string_view field : SHARED_FIELDS){ + if (key == field){ + return true; + } + } + for (std::string_view field : game_fields){ + if (key == field){ + return true; + } + } + return false; +} + +// Whether `value` is JSON true. +bool is_true(const JsonValue& value){ + return value.is_boolean() && value.to_boolean_default(); +} + +StoryRowSave read_save(const JsonObject& execution, std::string_view where){ + const JsonValue* save = execution.get_value("save"); + if (save == nullptr){ + return StoryRowSave::NONE; + } + const std::string* text = save->to_string(); + if (text != nullptr && *text == "autosave"){ + return StoryRowSave::AUTOSAVE; + } + if (text != nullptr && *text == "unverified"){ + return StoryRowSave::UNVERIFIED; + } + throw ParseException(std::format("{}: save is \"autosave\", \"unverified\" or left out", where)); +} + +StoryReload read_reload(const JsonObject& execution, std::string_view where){ + const JsonValue* reload = execution.get_value("reload_when_chained"); + if (reload == nullptr){ + return StoryReload::NEVER; + } + if (is_true(*reload)){ + return StoryReload::WHEN_CHAINED; + } + const std::string* text = reload->to_string(); + if (text != nullptr && *text == "always"){ + return StoryReload::ALWAYS; + } + throw ParseException(std::format("{}: reload_when_chained is true, \"always\" or left out", where)); +} + +} // namespace + + +StoryRowExecution read_story_row_execution( + const JsonObject& execution, std::string_view where, std::initializer_list game_fields +){ + for (const auto& [key, value] : execution){ + if (!is_known_field(key, game_fields)){ + throw ParseException(std::format("{}: unknown execution field {}", where, key)); + } + } + return StoryRowExecution{ + .save = read_save(execution, where), + .reload = read_reload(execution, where), + }; +} + + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.h new file mode 100644 index 0000000000..12e1f2585f --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.h @@ -0,0 +1,86 @@ +/* Story Row Execution + * + * From: https://github.com/PokemonAutomation/ + * + * The execution fields of a checkpoint file (its JSON "execution") that + * every game reads the same way, and the sets of rows they mark: which + * rows end on the game's own autosave and which a run reloads before, and + * a game's story: its checkpoints and those rows. The game reads its other execution fields itself + * (Pokemon_AuthoredCheckpointJson.h); Pokemon_StoryFiles.h loads a story + * from its files. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRowExecution_H +#define PokemonAutomation_Pokemon_StoryRowExecution_H + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonObject.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// When a run reloads the row's save before it, having played the row +// before it too ("reload_when_chained"). +enum class StoryReload{ + NEVER, // left out: the row runs on from where the row before left + WHEN_CHAINED, // true: at plan boundaries + ALWAYS, // "always": even straight through; only its save starts its walk +}; + +// What a row's "save" says about the game's own save at its end. The +// program never saves for a row. +enum class StoryRowSave{ + NONE, // left out: the game does not save at the row's end + AUTOSAVE, // "autosave": a run's log showed the game autosave there + UNVERIFIED, // "unverified": believed to autosave there, not yet seen in a run's log; a reload does not count on it +}; + +// What a checkpoint file's shared execution fields say. +struct StoryRowExecution{ + StoryRowSave save = StoryRowSave::NONE; + StoryReload reload = StoryReload::NEVER; +}; + +// The shared fields of `execution`: "save" and "reload_when_chained", each +// optional. Throws ParseException naming `where` for a +// malformed one, and for a field that is neither shared nor one of +// `game_fields`, which the game reads itself. +StoryRowExecution read_story_row_execution( + const JsonObject& execution, std::string_view where, std::initializer_list game_fields +); + + +// The rows of a story the shared execution fields mark, by id. +struct StoryRows{ + std::set> autosaves; + // The StoryRowSave::UNVERIFIED rows, for a run to report the autosave + // it sees there. + std::set> unverified_autosaves; + // WHEN_CHAINED and ALWAYS rows; each comes after an autosave row, + // whose autosave is its start save. + std::set> reload_when_chained; + // The ALWAYS rows of reload_when_chained. + std::set> reload_always; +}; + +// A game's story: its checkpoints in the order it plays them, and the rows +// their execution fields mark. +template +struct StoryData : StoryRows{ + std::vector checkpoints; +}; + + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp new file mode 100644 index 0000000000..ad64e76ee1 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp @@ -0,0 +1,259 @@ +/* Story Step JSON + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon_StoryStepJson.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// The wire names of the step kinds. They are not story_step_kind_name()'s +// log names: the JSON names a MASH step "scene" and a GAME step +// "game_action", after what the story author writes. +constexpr std::array, 15> KINDS{{ + {StoryStepKind::NEW_GAME, "new_game"}, + {StoryStepKind::OPTIONS, "options"}, + {StoryStepKind::ROUTE, "route"}, + {StoryStepKind::LEGS, "legs"}, + {StoryStepKind::STEP, "step"}, + {StoryStepKind::TALK, "talk"}, + {StoryStepKind::ANSWER, "answer"}, + {StoryStepKind::MASH, "scene"}, + {StoryStepKind::BATTLE, "battle"}, + {StoryStepKind::TRAIN, "train"}, + {StoryStepKind::HEAL, "heal"}, + {StoryStepKind::SHOP, "shop"}, + {StoryStepKind::SAVE, "save"}, + {StoryStepKind::READY, "ready"}, + {StoryStepKind::GAME, "game_action"}, +}}; + + + +// `value` as an object with no field outside `keys`. +const JsonObject& fields(const JsonValue& value, std::initializer_list keys, std::string_view source){ + const JsonObject& object = value.to_object_throw(std::string(source)); + for (const auto& [key, unused] : object){ + bool known = false; + for (std::string_view allowed : keys){ + known |= key == allowed; + } + if (!known){ + throw ParseException(std::format("{}: unsupported field {}", source, key)); + } + } + return object; +} + +template +Enum read_enum(const std::array, N>& names, std::string_view name, std::string_view source){ + for (const auto& [value, label] : names){ + if (label == name){ + return value; + } + } + throw ParseException(std::format("{}: unsupported value {}", source, name)); +} + +int integer(const JsonValue& value, std::string_view source){ + const int64_t number = value.to_integer_throw(std::string(source)); + if (number < std::numeric_limits::min() || number > std::numeric_limits::max()){ + throw ParseException(std::format("{}: coordinate exceeds native int", source)); + } + return (int)number; +} + +std::vector read_strings(const JsonValue& value, std::string_view source){ + std::vector result; + for (const JsonValue& item : value.to_array_throw(std::string(source))){ + result.push_back(item.to_string_throw(std::string(source))); + } + return result; +} + +std::vector> read_integer_rows(const JsonValue& value, std::string_view source){ + std::vector> result; + for (const JsonValue& item : value.to_array_throw(std::string(source))){ + std::vector row; + for (const JsonValue& number : item.to_array_throw(std::string(source))){ + row.push_back(number.to_integer_throw(std::string(source))); + } + result.push_back(std::move(row)); + } + return result; +} + +std::vector read_timed_legs(const JsonValue& value, std::string_view source){ + std::vector result; + for (const JsonValue& item : value.to_array_throw(std::string(source))){ + const JsonArray& pair = item.to_array_throw(std::string(source)); + if (pair.size() != 2){ + throw ParseException(std::format("{}: a timed leg is [turn degrees, ms]", source)); + } + result.push_back({.turn = integer(pair[0], source), .ms = integer(pair[1], source)}); + } + return result; +} + +// One arg's value read as `type`. +StoryArgValue read_arg(const JsonValue& value, StoryArgType type, std::string_view source){ + switch (type){ + case StoryArgType::BOOLEAN: + return value.to_boolean_throw(std::string(source)); + case StoryArgType::INTEGER: + return value.to_integer_throw(std::string(source)); + case StoryArgType::WORD: + return value.to_string_throw(std::string(source)); + case StoryArgType::WORDS: + return read_strings(value, source); + case StoryArgType::INTEGER_ROWS: + return read_integer_rows(value, source); + case StoryArgType::TIMED_LEGS: + return read_timed_legs(value, source); + } + throw ParseException(std::format("{}: unsupported story arg type", source)); +} + +// The step's action among `actions`: the named one, or the kind's default. +// Null for a kind with no action that names none. +const StoryActionSpec* step_action( + const StoryStep& step, std::span actions, std::string_view source +){ + if (step.kind == StoryStepKind::GAME && step.action.empty()){ + throw ParseException(std::format("{}: game_action step {} names no action", source, step.name)); + } + const StoryActionSpec* spec = find_story_action(actions, step.kind, step.action); + if (spec == nullptr && !step.action.empty()){ + throw ParseException(std::format("{}: step {}: unknown action {}", source, step.name, step.action)); + } + return spec; +} + +// The step's args, read against its action's spec, with the fallbacks +// filled in. +StoryActionArgs read_args( + const JsonValue* value, const StoryActionSpec* spec, const StoryStep& step, std::string_view source +){ + const StoryActionSpec none{.kind = step.kind, .name = "", .args = {}}; + const StoryActionSpec& action = spec ? *spec : none; + StoryActionArgs result; + if (value != nullptr){ + for (const auto& [key, item] : value->to_object_throw(std::string(source))){ + const auto arg = std::find_if(action.args.begin(), action.args.end(), [&](const StoryArgSpec& candidate){ + return candidate.key == key; + }); + if (arg == action.args.end()){ + throw ParseException(std::format("{}: step {}: unknown argument \"{}\"", source, step.name, key)); + } + result[key] = read_arg(item, arg->type, source); + } + } + const std::vector errors = story_args_errors(action, result); + if (!errors.empty()){ + throw ParseException(std::format("{}: step {}: {}", source, step.name, errors.front())); + } + return with_fallbacks(action, std::move(result)); +} + + +// Reads "metadata" into `checkpoint`. A missing phase is testing. +void read_metadata(const JsonValue& value, std::string_view source, StoryCheckpoint& checkpoint){ + const JsonObject& root = fields(value, {"phase", "source"}, source); + if (const JsonValue* field = root.get_value("phase")){ + const std::string name = field->to_string_throw(); + const std::optional phase = read_story_phase(name); + if (!phase){ + throw ParseException(std::format("{}: unknown phase {}", source, name)); + } + checkpoint.metadata.phase = *phase; + } + if (const JsonValue* field = root.get_value("source")){ + checkpoint.metadata.source = field->to_string_throw(); + } +} + + +} // namespace + + +DeclaredPose read_declared_pose(const JsonValue& value, std::string_view source){ + const JsonObject& root = fields(value, {"place", "spot", "heading"}, source); + ZoneDeclared result; + result.place = root.get_string_throw("place"); + if (const JsonValue* field = root.get_value("spot")){ + result.spot = field->to_string_throw(std::string(source)); + } + if (const JsonValue* field = root.get_value("heading")){ + result.heading = integer(*field, source); + } + return result; +} + +StoryStep read_story_step(const JsonValue& value, std::string_view source, std::span actions){ + const JsonObject& root = fields( + value, {"id", "kind", "why", "action", "args"}, source + ); + StoryStep result; + result.name = root.get_string_throw("id"); + if (result.name.empty()){ + throw ParseException("Empty story step id."); + } + result.kind = read_enum(KINDS, root.get_string_throw("kind"), source); + if (const JsonValue* field = root.get_value("why")){ + result.why = field->to_string_throw(); + } + if (const JsonValue* field = root.get_value("action")){ + result.action = field->to_string_throw(); + } + result.args = read_args(root.get_value("args"), step_action(result, actions, source), result, source); + return result; +} + +StoryCheckpoint read_story_checkpoint(const JsonValue& value, std::string_view source, std::span actions){ + const JsonObject& root = fields(value, {"id", "title", "start", "events", "metadata"}, source); + StoryCheckpoint result; + result.id = root.get_string_throw("id"); + if (result.id.empty()){ + throw ParseException("Empty story checkpoint id."); + } + result.title = root.get_string_throw("title"); + if (const JsonValue* start = root.get_value("start")){ + result.start = read_declared_pose(*start, source); + } + std::set names; + for (const JsonValue& event : root.get_array_throw("events")){ + StoryStep step = read_story_step(event, source, actions); + if (step.name.empty() || !names.insert(step.name).second){ + throw ParseException("Empty or duplicate story event id."); + } + result.steps.push_back(std::move(step)); + } + if (const JsonValue* metadata = root.get_value("metadata")){ + read_metadata(*metadata, source, result); + } + return result; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h new file mode 100644 index 0000000000..ecd7ab58de --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h @@ -0,0 +1,51 @@ +/* Story Step JSON + * + * From: https://github.com/PokemonAutomation/ + * + * Readers of the shared JSON wire form of the story data types (Types/): + * poses, steps and checkpoints, read strictly. This is + * the only layer that reads story JSON: a step comes out with its args + * typed and checked, and nothing after it parses. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStepJson_H +#define PokemonAutomation_Pokemon_StoryStepJson_H + +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryStep.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Read a declared pose (a checkpoint's "start"): a zone one, +// {"place": "LumioseCity", "spot": "HotelZ", "heading": 90} (spot and +// heading optional). Malformed and unknown fields fail. +DeclaredPose read_declared_pose(const JsonValue& value, std::string_view source); + + +// Read a step, its args parsed against its action among `actions` (the +// game's) and their fallbacks filled in. Unknown fields, kinds, actions and args, mistyped +// values and missing required args fail. +StoryStep read_story_step( + const JsonValue& value, std::string_view source, + std::span actions +); + + +// Read the common checkpoint, its steps read as read_story_step() does. +StoryCheckpoint read_story_checkpoint( + const JsonValue& value, std::string_view source, + std::span actions +); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp new file mode 100644 index 0000000000..2d25f08ff5 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp @@ -0,0 +1,215 @@ +/* Story Step JSON Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Each case reads a record from JSON: accepted cases check the values + * read, rejected cases check that the read fails. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon/AutoStory/Types/Pokemon_DeclaredPose.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h" +#include "Pokemon_StoryStepJson.h" +#include "Pokemon_StoryStepJson_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// Which record a case reads. +enum class Record{ + DECLARED, + STEP, + CHECKPOINT, +}; + +// What a read gives. +using ReadRecord = std::variant; + +// "" when the record read is as expected, else what differs. +using ReadCheck = std::string (*)(const ReadRecord& record); + +struct WireCase{ + // A record to read, and which kind it is. + std::string_view name; + struct Input{ + Record record = Record::STEP; + std::string_view json; + }; + + // What reading it gives: a record the check accepts, or a rejection. + struct Expectation{ + ReadCheck check = nullptr; + bool rejected = false; + }; + + Input input; + Expectation expectation; +}; + +std::string expect(bool ok, std::string_view what){ + return ok ? "" : std::format("Expected {}.", what); +} + +const StoryStep& step_of(const ReadRecord& record){ + return std::get(record); +} + +const WireCase CASES[] = { + {.name = "no args", .input = {.json = R"({"id":"talk","kind":"talk"})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryStep& step = step_of(record); + return expect(step.name == "talk" && step.kind == StoryStepKind::TALK && step.args.empty(), "a bare talk step"); + }}}, + {.name = "game args", .input = {.json = R"({"id":"buy","kind":"game_action","action":"mart","args":{"map":"CeruleanCity_Mart","budget":3000,"if_present":true}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"budget", int64_t(3000)}, {"if_present", true}, {"map", std::string("CeruleanCity_Mart")}}; + return expect(step_of(record).args == expected, "the Mart args"); + }}}, + {.name = "game words", .input = {.json = R"({"id":"buy","kind":"game_action","action":"mart","args":{"map":"M","budget":1,"skip":["a","b"]}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"budget", int64_t(1)}, {"if_present", false}, {"map", std::string("M")}, {"skip", std::vector{"a", "b"}}}; + return expect(step_of(record).args == expected, "the words and if_present false"); + }}}, + {.name = "game integer rows", .input = {.json = R"({"id":"w","kind":"game_action","action":"walk","args":{"legs":[[0,4500],[-90,0],[]]}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"legs", std::vector>{{0, 4500}, {-90, 0}, {}}}}; + return expect(step_of(record).args == expected, "three rows, the last empty"); + }}}, + {.name = "timed legs", .input = {.json = R"({"id":"w","kind":"game_action","action":"timed_walk","args":{"legs":[[0,4500],[-90,1200]]}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"legs", std::vector{{.turn = 0, .ms = 4500}, {.turn = -90, .ms = 1200}}}}; + return expect(step_of(record).args == expected, "two timed legs"); + }}}, + {.name = "declared place", .input = {.record = Record::DECLARED, .json = R"({"place":"LumioseCity","spot":"HotelZ","heading":90})"}, .expectation = {.check = [](const ReadRecord& record){ + const DeclaredPose expected = ZoneDeclared{.place = "LumioseCity", .spot = "HotelZ", .heading = 90}; + return expect(std::get(record) == expected, "a zone pose with spot and heading"); + }}}, + {.name = "declared place alone", .input = {.record = Record::DECLARED, .json = R"({"place":"HotelZ"})"}, .expectation = {.check = [](const ReadRecord& record){ + const DeclaredPose expected = ZoneDeclared{.place = "HotelZ", .spot = std::nullopt, .heading = std::nullopt}; + return expect(std::get(record) == expected, "a zone pose alone"); + }}}, + {.name = "checkpoint starting at a place", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"03.01","title":"Lobby","start":{"place":"HotelZ"},"events":[{"id":"down","kind":"scene"}]})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + const DeclaredPose start = ZoneDeclared{.place = "HotelZ", .spot = std::nullopt, .heading = std::nullopt}; + return expect(checkpoint.start == start && checkpoint.steps.size() == 1 && checkpoint.steps[0].kind == StoryStepKind::MASH, "a zone start and one scene"); + }}}, + {.name = "ordered checkpoint", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"00.05","title":"Parcel","events":[ {"id":"first","kind":"talk"}, {"id":"second","kind":"scene"} ]})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + return expect(checkpoint.id == "00.05" && checkpoint.title == "Parcel" && !checkpoint.start && checkpoint.steps.size() == 2 + && checkpoint.steps[0].name == "first" && checkpoint.steps[1].name == "second", "two steps in order"); + }}}, + {.name = "checkpoint without metadata is testing", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[]})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + return expect(checkpoint.metadata.phase == StoryPhase::TESTING, "the testing phase"); + }}}, + {.name = "integer rows, not rows", .input = {.json = R"({"id":"w","kind":"game_action","action":"walk","args":{"legs":[0,4500]}})"}, .expectation = {.rejected = true}}, + {.name = "integer rows, fraction", .input = {.json = R"({"id":"w","kind":"game_action","action":"walk","args":{"legs":[[0,4.5]]}})"}, .expectation = {.rejected = true}}, + {.name = "timed leg of three numbers", .input = {.json = R"({"id":"w","kind":"game_action","action":"timed_walk","args":{"legs":[[0,4500,1]]}})"}, .expectation = {.rejected = true}}, + {.name = "unknown arg", .input = {.json = R"({"id":"a","kind":"game_action","action":"mart","args":{"map":"M","budget":1,"budgte":1}})"}, .expectation = {.rejected = true}}, + {.name = "missing required arg", .input = {.json = R"({"id":"a","kind":"game_action","action":"mart","args":{"map":"M"}})"}, .expectation = {.rejected = true}}, + {.name = "args on a kind with none", .input = {.json = R"({"id":"a","kind":"talk","args":{"yes":true}})"}, .expectation = {.rejected = true}}, + {.name = "game step without action", .input = {.json = R"({"id":"a","kind":"game_action"})"}, .expectation = {.rejected = true}}, + {.name = "unknown action name", .input = {.json = R"({"id":"a","kind":"game_action","action":"dance"})"}, .expectation = {.rejected = true}}, + {.name = "fractional arg", .input = {.json = R"({"id":"a","kind":"game_action","action":"mart","args":{"map":"M","budget":1.5}})"}, .expectation = {.rejected = true}}, + {.name = "args not an object", .input = {.json = R"({"id":"a","kind":"game_action","action":"mart","args":["map"]})"}, .expectation = {.rejected = true}}, + {.name = "may_lose outside args", .input = {.json = R"({"id":"a","kind":"battle","may_lose":true})"}, .expectation = {.rejected = true}}, + {.name = "variant instead of action", .input = {.json = R"({"id":"a","kind":"game_action","variant":"mart"})"}, .expectation = {.rejected = true}}, + {.name = "unknown field", .input = {.json = R"({"id":"a","kind":"talk","mystery":0})"}, .expectation = {.rejected = true}}, + {.name = "unknown kind", .input = {.json = R"({"id":"a","kind":"magic"})"}, .expectation = {.rejected = true}}, + {.name = "declared place with tiles", .input = {.record = Record::DECLARED, .json = R"({"place":"HotelZ","tiles":[[1,2]]})"}, .expectation = {.rejected = true}}, + {.name = "declared neither", .input = {.record = Record::DECLARED, .json = R"({"spot":"Lobby"})"}, .expectation = {.rejected = true}}, + {.name = "unknown phase", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[],"metadata":{"phase":"tested"}})"}, .expectation = {.rejected = true}}, + {.name = "unknown metadata field", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[],"metadata":{"phase":"testing","runs":3}})"}, .expectation = {.rejected = true}}, + {.name = "duplicate events", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[{"id":"a","kind":"talk"},{"id":"a","kind":"talk"}]})"}, .expectation = {.rejected = true}}, +}; + + +// A game's actions: a Mart step (GAME "mart"), walks and a profile check +// that takes no args. +std::vector test_actions(){ + std::vector actions; + actions.push_back({.kind = StoryStepKind::GAME, .name = "mart", .args = { + {.key = "map", .type = StoryArgType::WORD, .required = true, .fallback = std::nullopt, .why = "the Mart's map"}, + {.key = "budget", .type = StoryArgType::INTEGER, .required = true, .fallback = std::nullopt, .why = "money to spend"}, + {.key = "if_present", .type = StoryArgType::BOOLEAN, .required = false, .fallback = false, .why = ""}, + {.key = "skip", .type = StoryArgType::WORDS, .required = false, .fallback = std::nullopt, .why = ""}, + }}); + actions.push_back({.kind = StoryStepKind::GAME, .name = "walk", .args = { + {.key = "legs", .type = StoryArgType::INTEGER_ROWS, .required = true, .fallback = std::nullopt, .why = "rows of numbers"}, + }}); + actions.push_back({.kind = StoryStepKind::GAME, .name = "timed_walk", .args = { + {.key = "legs", .type = StoryArgType::TIMED_LEGS, .required = true, .fallback = std::nullopt, .why = "[turn degrees, ms] legs"}, + }}); + actions.push_back({.kind = StoryStepKind::GAME, .name = "profile", .args = {}}); + return actions; +} + + +// `input` read, with `source` naming it in parse errors. +ReadRecord read_record(const WireCase::Input& input, std::string_view source){ + static const std::vector actions = test_actions(); + const JsonValue value = parse_json(std::string(input.json)); + switch (input.record){ + case Record::DECLARED: + return read_declared_pose(value, source); + case Record::STEP: + return read_story_step(value, source, actions); + case Record::CHECKPOINT: + return read_story_checkpoint(value, source, actions); + } + throw ParseException("Unknown test record."); +} + +// "" when `test` reads as expected, else what differs. +std::string check_case(const WireCase& test){ + try{ + const ReadRecord record = read_record(test.input, test.name); + if (test.expectation.rejected){ + return "Expected rejection, read accepted record."; + } + return test.expectation.check(record); + }catch (const ParseException& error){ + return test.expectation.rejected ? "" : std::format("Unexpected parse failure: {}", error.message()); + } +} + + +class StoryJsonTest : public UnitTest{ +public: + explicit StoryJsonTest(WireCase test) + : UnitTest(std::format("Pokemon::StoryStepJson - {}", test.name)) + , m_case(test) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string error = check_case(m_case); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } + +private: + WireCase m_case; +}; + + +} // namespace + + +void add_tests_StoryStepJson(UnitTestDatabase& database){ + for (const WireCase& test : CASES){ + database.add(test); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h new file mode 100644 index 0000000000..9c4f9565ad --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h @@ -0,0 +1,23 @@ +/* Story Step JSON Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStepJson_Tests_H +#define PokemonAutomation_Pokemon_StoryStepJson_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the lossless shared story-data wire contract. +void add_tests_StoryStepJson(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.cpp new file mode 100644 index 0000000000..9f32440e80 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.cpp @@ -0,0 +1,26 @@ +/* Zone Pose + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Pokemon_ZonePose.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +bool pose_matches(const ZonePose& actual, const ZonePose& target){ + return target.zone.empty() || actual.zone == target.zone; +} + +std::string pose_text(const ZonePose& pose){ + return std::format("zone {}", (pose.zone.empty() ? std::string("unknown") : pose.zone)); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.h new file mode 100644 index 0000000000..b871c6b331 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.h @@ -0,0 +1,37 @@ +/* Zone Pose + * + * From: https://github.com/PokemonAutomation/ + * + * The pose of a game with no tile grid (PLZA): the zone the player is in, + * by name, until the game has a reader of its position. + * + */ + +#ifndef PokemonAutomation_Pokemon_ZonePose_H +#define PokemonAutomation_Pokemon_ZonePose_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Where the player is: a zone, "LumioseCity" or "HotelZ". +struct ZonePose{ + std::string zone = {}; + + bool operator==(const ZonePose& other) const = default; +}; + +// Whether `actual` is in `target`'s zone; any zone when `target` names none. +bool pose_matches(const ZonePose& actual, const ZonePose& target); + +// "zone LumioseCity". +std::string pose_text(const ZonePose& pose); + + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h new file mode 100644 index 0000000000..4827c66e81 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -0,0 +1,38 @@ +/* AutoStory Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The unit tests of the pieces every AutoStory program shares, story + * engine or not. add_tests_AutoStory() is the one entry point the unit + * test runner calls; a new shared AutoStory suite registers there. + * + */ + +#ifndef PokemonAutomation_Pokemon_AutoStory_Tests_H +#define PokemonAutomation_Pokemon_AutoStory_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Data/Pokemon_AuthoredCheckpointJson_Tests.h" +#include "Data/Pokemon_StoryFiles_Tests.h" +#include "Data/Pokemon_StoryStepJson_Tests.h" +#include "Pokemon_StoryLog_Tests.h" +#include "Types/Pokemon_StoryActionArg_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers every shared AutoStory suite, for the unit test runner. +inline void add_tests_AutoStory(UnitTestDatabase& database){ + add_tests_StoryActionArg(database); + add_tests_StoryLog(database); + add_tests_StoryStepJson(database); + add_tests_AuthoredCheckpointJson(database); + add_tests_StoryFiles(database); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_MapUtil.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_MapUtil.h new file mode 100644 index 0000000000..f9be88108b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_MapUtil.h @@ -0,0 +1,44 @@ +/* Map Util + * + * From: https://github.com/PokemonAutomation/ + * + * Lookups in a map through the iterator find() returned, so a call site + * says which lookup it does and never copies the value by accident: + * const int64_t* budget = value_if_at_it(args, args.find("budget")); + * + */ + +#ifndef PokemonAutomation_Pokemon_MapUtil_H +#define PokemonAutomation_Pokemon_MapUtil_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The value at `it`, or null when `it` is `map`'s end. +template +const typename Map::mapped_type* value_at_it(const Map& map, typename Map::const_iterator it); + +// The `Type` alternative of the variant at `it`, or null when `it` is +// `map`'s end or the variant holds another type. +template +const Type* value_if_at_it(const Map& map, typename Map::const_iterator it); + + +template +const typename Map::mapped_type* value_at_it(const Map& map, typename Map::const_iterator it){ + return it == map.end() ? nullptr : &it->second; +} + +template +const Type* value_if_at_it(const Map& map, typename Map::const_iterator it){ + return it == map.end() ? nullptr : std::get_if(&it->second); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp new file mode 100644 index 0000000000..91b35e5257 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp @@ -0,0 +1,85 @@ +/* Story Log + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryLog.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +std::string resets_text(size_t attempt){ + if (attempt <= 1){ + return "one-shot"; + } + return std::format("{} reset{}", attempt - 1, attempt == 2 ? "" : "s"); +} + +// "[Checkpoint] 00.04", or the game's own checkpoint text unchanged. +std::string checkpoint_prefix(std::string_view checkpoint, CheckpointPrefix prefix_kind){ + if (prefix_kind == CheckpointPrefix::AS_GIVEN){ + return std::string(checkpoint); + } + return std::format("[Checkpoint] {}", checkpoint); +} + +} // namespace + + +std::string checkpoint_start_line( + std::string_view checkpoint, std::optional events, CheckpointPrefix prefix_kind +){ + const std::string prefix = checkpoint_prefix(checkpoint, prefix_kind); + if (!events){ + return std::format("{}: start", prefix); + } + return std::format("{}: start, {} events", prefix, *events); +} + +std::string checkpoint_attempt_line( + std::string_view checkpoint, size_t attempt, std::optional attempts, CheckpointPrefix prefix_kind +){ + const std::string prefix = checkpoint_prefix(checkpoint, prefix_kind); + if (!attempts){ + return std::format("{}: attempt {}", prefix, attempt); + } + return std::format("{}: attempt {}/{}", prefix, attempt, *attempts); +} + +std::string checkpoint_pass_line(std::string_view checkpoint, size_t attempt, CheckpointPrefix prefix_kind){ + return std::format( + "{}: passed on attempt {} ({})", + checkpoint_prefix(checkpoint, prefix_kind), attempt, resets_text(attempt) + ); +} + +std::string checkpoint_reset_line( + std::string_view checkpoint, size_t next_attempt, std::optional attempts, CheckpointPrefix prefix_kind +){ + const std::string prefix = checkpoint_prefix(checkpoint, prefix_kind); + if (!attempts){ + return std::format("{}: failed, resetting for attempt {}", prefix, next_attempt); + } + return std::format("{}: failed, resetting for attempt {}/{}", prefix, next_attempt, *attempts); +} + +std::string story_short_line(std::string_view line){ + if (!line.starts_with('[')){ + return std::string(line); + } + const size_t end = line.find("] "); + if (end == std::string_view::npos){ + return std::string(line); + } + return std::string(line.substr(end + 2)); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h new file mode 100644 index 0000000000..b19a638cc0 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h @@ -0,0 +1,89 @@ +/* Story Log + * + * From: https://github.com/PokemonAutomation/ + * + * A story is split at three levels: a segment is a chapter of + * checkpoints, a checkpoint is the stretch between two saves and the unit + * a run retries, and an event is one step inside a checkpoint. This file + * writes the checkpoint lines: start, attempt, reset and pass, in one + * format for every game, so the program developer and user find each + * checkpoint's attempts the same way in any game's log. Nothing here runs + * a story. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryLog_H +#define PokemonAutomation_Pokemon_StoryLog_H + +#include +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The lines below start with "[Checkpoint] " and then `checkpoint`. A game +// whose checkpoint text already says it is a checkpoint (SV's +// "Checkpoint:: 004 - 02 ...") passes that text as `checkpoint` with +// AS_GIVEN, and the line starts with the text alone: +// Checkpoint:: 004 - 02 ...: start +enum class CheckpointPrefix{ + ADD, + AS_GIVEN, +}; + +// A checkpoint starts; the story engine also says it has `events` events: +// [Checkpoint] 00.04: start +// [Checkpoint] 00.04: start, 3 events +std::string checkpoint_start_line( + std::string_view checkpoint, + std::optional events = std::nullopt, + CheckpointPrefix prefix_kind = CheckpointPrefix::ADD +); + +// An attempt at a checkpoint starts, counting from 1, out of the +// program's limit of `attempts` if it has one: +// [Checkpoint] 00.04: attempt 2 +// [Checkpoint] 00.04: attempt 2/3 +std::string checkpoint_attempt_line( + std::string_view checkpoint, + size_t attempt, + std::optional attempts = std::nullopt, + CheckpointPrefix prefix_kind = CheckpointPrefix::ADD +); + +// A checkpoint passed on attempt `attempt`, counting from 1; every attempt +// before it ended in a reset: +// [Checkpoint] 00.03: passed on attempt 1 (one-shot) +// [Checkpoint] 00.04: passed on attempt 3 (2 resets) +std::string checkpoint_pass_line( + std::string_view checkpoint, + size_t attempt, + CheckpointPrefix prefix_kind = CheckpointPrefix::ADD +); + +// An attempt failed and the game resets to the checkpoint's save for +// attempt `next_attempt`, out of the limit of `attempts` if it has one: +// [Checkpoint] 00.04: failed, resetting for attempt 2 +// [Checkpoint] 00.04: failed, resetting for attempt 2/3 +std::string checkpoint_reset_line( + std::string_view checkpoint, + size_t next_attempt, + std::optional attempts = std::nullopt, + CheckpointPrefix prefix_kind = CheckpointPrefix::ADD +); + +// The full lines above go to the log. The video overlay, which wraps its +// lines, shows each one short, without its leading "[Tag] ": +// [Checkpoint] 12.03: start, 18 events -> 12.03: start, 18 events +// Any line with a leading "[Tag] " is shortened the same way. A line +// without a tag, like SV's checkpoint text, is returned unchanged. +std::string story_short_line(std::string_view line); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp new file mode 100644 index 0000000000..e30ad0dc62 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp @@ -0,0 +1,168 @@ +/* Story Log Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_StoryLog.h" +#include "Pokemon_StoryLog_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +// One formatter call and the line it must make. +struct StoryLogTestCase{ + // The formatter call, made when the test runs. + struct Input{ + std::string (*format)(); + }; + + // The exact line: log readers and the engine tests match these. + struct Expectation{ + std::string line; + }; + + std::string name; + Input input; + Expectation expectation; +}; + +class Test_StoryLog : public UnitTest{ +public: + Test_StoryLog(StoryLogTestCase test_case) + : UnitTest(std::format("Pokemon::StoryLog - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string line = m_case.input.format(); + if (line != m_case.expectation.line){ + return std::format("Expected \"{}\", got \"{}\"", m_case.expectation.line, line); + } + return true; + } + +private: + const StoryLogTestCase m_case; +}; + +// SV's text for a checkpoint, which already says "Checkpoint::". +constexpr std::string_view SV_TEXT = "Checkpoint:: 004 - 02. Start point: X"; + +const StoryLogTestCase STORY_LOG_CASES[] = { + { + .name = "checkpoint start", + .input = {.format = []{ return checkpoint_start_line("00.04"); }}, + .expectation = {.line = "[Checkpoint] 00.04: start"}, + }, + { + .name = "checkpoint start with its events", + .input = {.format = []{ return checkpoint_start_line("00.04", /*events=*/3); }}, + .expectation = {.line = "[Checkpoint] 00.04: start, 3 events"}, + }, + { + .name = "attempt", + .input = {.format = []{ return checkpoint_attempt_line("00.04", 2); }}, + .expectation = {.line = "[Checkpoint] 00.04: attempt 2"}, + }, + { + .name = "attempt out of a limit", + .input = {.format = []{ return checkpoint_attempt_line("00.04", 2, /*attempts=*/3); }}, + .expectation = {.line = "[Checkpoint] 00.04: attempt 2/3"}, + }, + { + .name = "one-shot pass", + .input = {.format = []{ return checkpoint_pass_line("00.03", 1); }}, + .expectation = {.line = "[Checkpoint] 00.03: passed on attempt 1 (one-shot)"}, + }, + { + .name = "pass after one reset", + .input = {.format = []{ return checkpoint_pass_line("00.04", 2); }}, + .expectation = {.line = "[Checkpoint] 00.04: passed on attempt 2 (1 reset)"}, + }, + { + .name = "pass after resets", + .input = {.format = []{ return checkpoint_pass_line("00.04", 3); }}, + .expectation = {.line = "[Checkpoint] 00.04: passed on attempt 3 (2 resets)"}, + }, + { + .name = "reset", + .input = {.format = []{ return checkpoint_reset_line("00.04", 2); }}, + .expectation = {.line = "[Checkpoint] 00.04: failed, resetting for attempt 2"}, + }, + { + .name = "reset out of a limit", + .input = {.format = []{ return checkpoint_reset_line("00.04", 2, /*attempts=*/3); }}, + .expectation = {.line = "[Checkpoint] 00.04: failed, resetting for attempt 2/3"}, + }, + { + .name = "start without the checkpoint prefix", + .input = {.format = []{ return checkpoint_start_line(SV_TEXT, /*events=*/std::nullopt, CheckpointPrefix::AS_GIVEN); }}, + .expectation = {.line = "Checkpoint:: 004 - 02. Start point: X: start"}, + }, + { + .name = "attempt without the checkpoint prefix", + .input = {.format = []{ return checkpoint_attempt_line(SV_TEXT, 2, /*attempts=*/100, CheckpointPrefix::AS_GIVEN); }}, + .expectation = {.line = "Checkpoint:: 004 - 02. Start point: X: attempt 2/100"}, + }, + { + .name = "pass without the checkpoint prefix", + .input = {.format = []{ return checkpoint_pass_line(SV_TEXT, 2, CheckpointPrefix::AS_GIVEN); }}, + .expectation = {.line = "Checkpoint:: 004 - 02. Start point: X: passed on attempt 2 (1 reset)"}, + }, + { + .name = "reset without the checkpoint prefix", + .input = {.format = []{ return checkpoint_reset_line(SV_TEXT, 2, /*attempts=*/std::nullopt, CheckpointPrefix::AS_GIVEN); }}, + .expectation = {.line = "Checkpoint:: 004 - 02. Start point: X: failed, resetting for attempt 2"}, + }, + { + .name = "short checkpoint start", + .input = {.format = []{ return story_short_line("[Checkpoint] 12.03: start, 18 events"); }}, + .expectation = {.line = "12.03: start, 18 events"}, + }, + { + .name = "short line with another tag", + .input = {.format = []{ return story_short_line("[Tag] 12.03: some text"); }}, + .expectation = {.line = "12.03: some text"}, + }, + { + .name = "short line without the checkpoint prefix", + .input = {.format = []{ return story_short_line( + checkpoint_start_line(SV_TEXT, /*events=*/std::nullopt, CheckpointPrefix::AS_GIVEN) + ); }}, + .expectation = {.line = "Checkpoint:: 004 - 02. Start point: X: start"}, + }, + { + .name = "short line with an unclosed tag", + .input = {.format = []{ return story_short_line("[Tag 12.03"); }}, + .expectation = {.line = "[Tag 12.03"}, + }, + { + .name = "short empty line", + .input = {.format = []{ return story_short_line(""); }}, + .expectation = {.line = ""}, + }, +}; + + +} // namespace + + +void add_tests_StoryLog(UnitTestDatabase& database){ + for (const StoryLogTestCase& test_case : STORY_LOG_CASES){ + database.add(test_case); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.h new file mode 100644 index 0000000000..822a222b31 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.h @@ -0,0 +1,23 @@ +/* Story Log Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryLog_Tests_H +#define PokemonAutomation_Pokemon_StoryLog_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the shared checkpoint log lines. +void add_tests_StoryLog(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcome.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcome.cpp new file mode 100644 index 0000000000..62c45b72b0 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcome.cpp @@ -0,0 +1,49 @@ +/* Story Outcome + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Pokemon_StoryOutcome.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +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){ + Outcome outcome; + outcome.failure = std::move(failure); + outcome.detail = std::move(detail); + 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"); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcome.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcome.h new file mode 100644 index 0000000000..c572b118dc --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcome.h @@ -0,0 +1,62 @@ +/* Story Outcome + * + * From: https://github.com/PokemonAutomation/ + * + * How a story action or check ended: success, or a named failure, and the + * pose the action left the player in when it knows it. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryOutcome_H +#define PokemonAutomation_Pokemon_StoryOutcome_H + +#include +#include +#include +#include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon_StoryPose.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How an action or a check ended: empty `failure` is success; otherwise a +// name that recoveries match (e.g. "probe_exhausted"). A succeeded action +// that knows where it left the player sets `pose`; the runner writes it +// into the run before the event's expects are checked. +struct Outcome{ + std::string failure; + std::string detail; + std::optional pose; + // A succeeded action that left the game as it found it: a read, a + // check, a TM the lead already knows. A reload of the same save undoes + // nothing it did. + bool changed_nothing = false; + + bool succeeded() const; +}; +// Success; with a pose, the runner moves the run's pose to it. +Outcome outcome_ok(std::optional pose = std::nullopt); +// outcome_ok() with `changed_nothing`. +Outcome outcome_unchanged(); +// A failure named `failure`, with what was seen in `detail`. +Outcome outcome_failed(std::string failure, std::string detail = ""); +// "probe_exhausted: 4 rows": the failure and its detail, if any. +std::string to_string(const Outcome& outcome); + +// The failure of a step that found the Switch's HOME menu instead of the +// game. Nothing in the story can answer it, as every press goes to the +// console's menus: no recovery runs and no reload, the run stops. +inline constexpr std::string_view GAME_NOT_RUNNING = "game_not_running"; +// GAME_NOT_RUNNING, saying so for the run log. +Outcome outcome_game_not_running(); + + +// What an event does; it may move the run's pose. +using Act = MoveOnlyFunction; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.cpp new file mode 100644 index 0000000000..d075cf4e40 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.cpp @@ -0,0 +1,59 @@ +/* Story Pose + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryPose.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +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)); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h new file mode 100644 index 0000000000..7ea985629b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h @@ -0,0 +1,73 @@ +/* Story Pose + * + * From: https://github.com/PokemonAutomation/ + * + * Where the player is believed to be, and how sure the run is of it. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryPose_H +#define PokemonAutomation_Pokemon_StoryPose_H + +#include +#include +#include + +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 the positions the pose holds. +enum class PoseCertainty{ + TILE, + COLUMN, + ROW, + SET, + UNKNOWN, +}; +// "tile", "column", ...: for log lines. +std::string 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 on a map the player is, in the game's own terms: tiles and a +// facing in a 2D game, a map point or a fly point in +// an open-world one. The engine only carries and prints it; the game's +// actions read it back. +struct Position{ + virtual ~Position() = default; + // The text after the map in a log line, e.g. "(10, 20) facing north"; + // none for a game that has nothing to say beyond the map. + virtual std::string describe() const{ + return ""; + } +}; + +// 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. `where` is null until the game learns a position and after +// the pose is lost; it is shared because poses are copied (an event's +// learned pose into the run) and never changed in place. +struct Pose{ + std::string map; + PoseCertainty certainty = PoseCertainty::UNKNOWN; + std::shared_ptr where; +}; +// "Route 201 (10, 20) facing north (tile)": for log lines. +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; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_DeclaredPose.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_DeclaredPose.h new file mode 100644 index 0000000000..fb05ec1055 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_DeclaredPose.h @@ -0,0 +1,40 @@ +/* Declared Pose + * + * From: https://github.com/PokemonAutomation/ + * + * A pose a checkpoint declares in its data (its start), as plain data. A + * game with no tile grid (PLZA) declares a place, a spot in it and a + * heading. + * + */ + +#ifndef PokemonAutomation_Pokemon_DeclaredPose_H +#define PokemonAutomation_Pokemon_DeclaredPose_H + +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// In `place` ("LumioseCity"), at `spot` in it if set, heading `heading` +// degrees if set. +struct ZoneDeclared{ + std::string place; + std::optional spot; + std::optional heading; + + bool operator==(const ZoneDeclared& other) const = default; +}; + +// Where a checkpoint declares the player to be. Only the zone kind so far: +// a game with tiles adds its own alternative. +using DeclaredPose = std::variant; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.cpp new file mode 100644 index 0000000000..8c5fb9b949 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.cpp @@ -0,0 +1,22 @@ +/* Story Action Arg + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryActionArg.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +StoryArgType story_arg_type(const StoryArgValue& value){ + // The alternatives are declared in StoryArgType's order. A variant left + // valueless by an exception would give variant_npos; none is kept. + return static_cast(value.index()); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h new file mode 100644 index 0000000000..2d1403942a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h @@ -0,0 +1,89 @@ +/* Story Action Arg + * + * From: https://github.com/PokemonAutomation/ + * + * A step's action and its arguments (StoryStep::action, StoryStep::args), + * e.g. a walk's {"legs": [[0, 4500], [90, 10000]], "end": "fade_white"}. Each + * action declares the arguments it takes (Pokemon_StoryActionSpec.h), with their + * types and defaults; the JSON reader (Data/Pokemon_StoryStepJson.h) + * parses a step's args against them and fills in the defaults, so a typo + * fails at load instead of mid-run and nothing after it reads JSON. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryActionArg_H +#define PokemonAutomation_Pokemon_StoryActionArg_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon/AutoStory/Pokemon_MapUtil.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A leg of a timed walk in a game with no tiles: turn `turn` degrees +// (clockwise, from the way the player faces), then walk for `ms`. +struct StoryTimedLeg{ + int turn = 0; + int ms = 0; + + bool operator==(const StoryTimedLeg& other) const = default; +}; + + +// The type an action declares for an argument, in StoryArgValue's order. +enum class StoryArgType{ + BOOLEAN, + INTEGER, + WORD, + WORDS, + INTEGER_ROWS, + TIMED_LEGS, +}; + +// One argument's value; the index is its StoryArgType. +using StoryArgValue = std::variant< + bool, int64_t, std::string, // BOOLEAN, INTEGER, WORD + std::vector, // WORDS + std::vector>, // INTEGER_ROWS: rows of any length, [[12, 7], [3, 9, 1], []] + std::vector // TIMED_LEGS: [turn degrees, ms] pairs, [[0, 4500], [90, 1200]] +>; +static_assert(std::variant_size_v == (size_t)StoryArgType::TIMED_LEGS + 1, "one StoryArgType per StoryArgValue type"); + +// A step's arguments by key. +using StoryActionArgs = std::map>; + +// The type `value` holds. +StoryArgType story_arg_type(const StoryArgValue& value); + +// The value of arg `key`, which the step's action requires or gives a +// fallback, so the loaded step has it. Throws InternalProgramError when it +// is missing or of another type: a step built without its action's spec. +template +const Type& story_arg(const StoryActionArgs& args, std::string_view key); + + + +template +const Type& story_arg(const StoryActionArgs& args, std::string_view key){ + const Type* value = value_if_at_it(args, args.find(key)); + if (value == nullptr){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("Missing or mistyped story arg: {}", key)); + } + return *value; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp new file mode 100644 index 0000000000..8bd661bd69 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp @@ -0,0 +1,117 @@ +/* Story Action Arg Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Checking a step's args against an action's spec and filling in its + * fallbacks. + * + */ + +#include +#include +#include +#include +#include "Pokemon_StoryActionSpec.h" +#include "Pokemon_StoryActionArg.h" +#include "Pokemon_StoryActionArg_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// The args a Mart step takes, as a game declares them. +const StoryActionSpec& mart_spec(){ + static const StoryActionSpec spec{.kind = StoryStepKind::GAME, .name = "mart", .args = { + {.key = "map", .type = StoryArgType::WORD, .required = true, .fallback = std::nullopt, .why = "the Mart's map"}, + {.key = "budget", .type = StoryArgType::INTEGER, .required = true, .fallback = std::nullopt, .why = ""}, + {.key = "floor", .type = StoryArgType::INTEGER, .required = false, .fallback = int64_t(0), .why = ""}, + {.key = "if_present", .type = StoryArgType::BOOLEAN, .required = false, .fallback = std::nullopt, .why = ""}, + }}; + return spec; +} + +struct ArgsCase{ + // Args checked against the Mart's spec, then filled in. + std::string_view name; + struct Input{ + StoryActionArgs args; + }; + + // The errors joined by "; ", and the args with their fallbacks. + struct Expectation{ + std::string_view error = {}; + StoryActionArgs filled = {}; + }; + + Input input; + Expectation expectation; +}; + +const ArgsCase CASES[] = { + {.name = "mart", .input = {.args = {{"map", std::string("M")}, {"budget", int64_t(1500)}, {"if_present", true}}}, + .expectation = {.filled = {{"map", std::string("M")}, {"budget", int64_t(1500)}, {"floor", int64_t(0)}, {"if_present", true}}}}, + {.name = "fallback does not override", .input = {.args = {{"map", std::string("M")}, {"budget", int64_t(1)}, {"floor", int64_t(2)}}}, + .expectation = {.filled = {{"map", std::string("M")}, {"budget", int64_t(1)}, {"floor", int64_t(2)}}}}, + {.name = "unknown key", .input = {.args = {{"map", std::string("M")}, {"budget", int64_t(1)}, {"budgte", int64_t(1)}}}, + .expectation = {.error = "unknown argument \"budgte\"", .filled = {{"map", std::string("M")}, {"budget", int64_t(1)}, {"budgte", int64_t(1)}, {"floor", int64_t(0)}}}}, + {.name = "wrong type", .input = {.args = {{"map", std::string("M")}, {"budget", std::string("lots")}}}, + .expectation = {.error = "argument \"budget\" has the wrong type", .filled = {{"map", std::string("M")}, {"budget", std::string("lots")}, {"floor", int64_t(0)}}}}, + {.name = "missing required", .input = {.args = {{"budget", int64_t(1)}}}, + .expectation = {.error = "missing argument \"map\" (the Mart's map)", .filled = {{"budget", int64_t(1)}, {"floor", int64_t(0)}}}}, +}; + + +// What differs from the expectation, if anything. +std::optional check_case(const ArgsCase& test){ + std::string error; + for (const std::string& each : story_args_errors(mart_spec(), test.input.args)){ + error += (error.empty() ? "" : "; ") + each; + } + if (error != test.expectation.error){ + return std::format("expected error \"{}\", got \"{}\"", test.expectation.error, error); + } + if (with_fallbacks(mart_spec(), test.input.args) != test.expectation.filled){ + return "filled in other args"; + } + const StoryActionArgs& args = test.expectation.filled; + const int64_t* floor = value_if_at_it(args, args.find("floor")); + if (floor == nullptr || *floor != story_arg(args, "floor")){ + return "reads floor otherwise"; + } + return std::nullopt; +} + + +class StoryActionArgTest : public UnitTest{ +public: + explicit StoryActionArgTest(ArgsCase test) + : UnitTest(std::format("Pokemon::StoryActionArg - {}", test.name)) + , m_case(test) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::optional error = check_case(m_case); + return error ? UnitTestResult(*error) : UnitTestResult(true); + } + +private: + ArgsCase m_case; +}; + + +} // namespace + + +void add_tests_StoryActionArg(UnitTestDatabase& database){ + for (const ArgsCase& test : CASES){ + database.add(test); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.h new file mode 100644 index 0000000000..d20848c4c2 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.h @@ -0,0 +1,23 @@ +/* Story Action Arg Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryActionArg_Tests_H +#define PokemonAutomation_Pokemon_StoryActionArg_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for step args: checking them against an action's spec. +void add_tests_StoryActionArg(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.cpp new file mode 100644 index 0000000000..91029f4090 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.cpp @@ -0,0 +1,71 @@ +/* Story Action Spec + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Pokemon_StoryActionSpec.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +const StoryArgSpec* find_spec(const StoryActionSpec& action, std::string_view key){ + for (const StoryArgSpec& spec : action.args){ + if (spec.key == key){ + return &spec; + } + } + return nullptr; +} + + +} // namespace + + +std::vector story_args_errors(const StoryActionSpec& spec, const StoryActionArgs& args){ + std::vector errors; + for (const auto& [key, value] : args){ + const StoryArgSpec* arg = find_spec(spec, key); + if (arg == nullptr){ + errors.emplace_back(std::format("unknown argument \"{}\"", key)); + }else if (story_arg_type(value) != arg->type){ + errors.emplace_back(std::format("argument \"{}\" has the wrong type", key)); + } + } + for (const StoryArgSpec& arg : spec.args){ + if (arg.required && args.find(arg.key) == args.end()){ + errors.emplace_back(std::format("missing argument \"{}\"{}", arg.key, arg.why.empty() ? "" : std::format(" ({})", arg.why))); + } + } + return errors; +} + +StoryActionArgs with_fallbacks(const StoryActionSpec& spec, StoryActionArgs args){ + for (const StoryArgSpec& arg : spec.args){ + if (arg.fallback){ + args.try_emplace(arg.key, *arg.fallback); + } + } + return args; +} + +const StoryActionSpec* find_story_action(std::span actions, StoryStepKind kind, std::string_view name){ + for (const StoryActionSpec& action : actions){ + if (action.kind == kind && (name.empty() || action.name == name)){ + return &action; + } + } + return nullptr; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h new file mode 100644 index 0000000000..9940d38441 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h @@ -0,0 +1,62 @@ +/* Story Action Spec + * + * From: https://github.com/PokemonAutomation/ + * + * What an action declares: the kind of step it does, its name and the + * args it takes, with their types and fallbacks (Pokemon_StoryActionArg.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryActionSpec_H +#define PokemonAutomation_Pokemon_StoryActionSpec_H + +#include +#include +#include +#include +#include +#include "Pokemon_StoryActionArg.h" +#include "Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// One argument an action takes. A missing optional one reads as `fallback` +// when it has one. +struct StoryArgSpec{ + std::string key; + StoryArgType type = StoryArgType::WORD; + bool required = false; + std::optional fallback; + // What it is for, shown in lint errors. + std::string why; +}; + +// An action: the kind of step it does, its name and the args it takes. +struct StoryActionSpec{ + StoryStepKind kind = StoryStepKind::GAME; + std::string name; + std::vector args; + // It reads or presses through screens only a console shows (menus, a + // keyboard, a battle AI): the engine refuses it on any other backend + // (StoryBackendKind) with the failure "console_only". + bool console_only = false; +}; + +// Each way `args` don't fit `spec`: a key it doesn't name, a value of +// another type, a required one missing. Empty when they fit. +std::vector story_args_errors(const StoryActionSpec& spec, const StoryActionArgs& args); + +// `args` with each missing optional arg of `spec` set to its fallback. +StoryActionArgs with_fallbacks(const StoryActionSpec& spec, StoryActionArgs args); + +// The action of `kind` named `name` among `actions`; for an empty name, the +// kind's first. Null when there is none. +const StoryActionSpec* find_story_action(std::span actions, StoryStepKind kind, std::string_view name); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h new file mode 100644 index 0000000000..d1dc18b0e4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h @@ -0,0 +1,40 @@ +/* Story Checkpoint + * + * From: https://github.com/PokemonAutomation/ + * + * A checkpoint of a game's story table as plain data: where its save + * leaves the player and its steps in order. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryCheckpoint_H +#define PokemonAutomation_Pokemon_StoryCheckpoint_H + +#include +#include +#include +#include "Pokemon_DeclaredPose.h" +#include "Pokemon_StoryCheckpointMetadata.h" +#include "Pokemon_StoryStep.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Milestone row in the story table grouping related steps and starting pose. +struct StoryCheckpoint{ + std::string id; + std::string title; + // Where its starting save leaves the player; none for a new game. + std::optional start; + std::vector steps; + // Its phase and verification (JSON "metadata"), which decide when a + // run of it may save. + StoryCheckpointMetadata metadata = {}; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.cpp new file mode 100644 index 0000000000..fb6eac85fd --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.cpp @@ -0,0 +1,37 @@ +/* Story Checkpoint Metadata + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryCheckpointMetadata.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string story_phase_name(StoryPhase phase){ + switch (phase){ + case StoryPhase::TESTING: + return "testing"; + case StoryPhase::VERIFICATION: + return "verification"; + case StoryPhase::REPRODUCTION: + return "reproduction"; + } + return "?"; +} + +std::optional read_story_phase(std::string_view name){ + for (StoryPhase phase : {StoryPhase::TESTING, StoryPhase::VERIFICATION, StoryPhase::REPRODUCTION}){ + if (story_phase_name(phase) == name){ + return phase; + } + } + return std::nullopt; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h new file mode 100644 index 0000000000..672c87e88c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h @@ -0,0 +1,52 @@ +/* Story Checkpoint Metadata + * + * From: https://github.com/PokemonAutomation/ + * + * What a checkpoint's JSON says about the checkpoint rather than how to + * play it: its phase (testing, verification or reproduction, below) and + * where it came from. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryCheckpointMetadata_H +#define PokemonAutomation_Pokemon_StoryCheckpointMetadata_H + +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Where a checkpoint stands. It moves forward only on passes; a change to +// its steps moves it back to TESTING. +enum class StoryPhase{ + // New or changed: one run, never saves. + TESTING, + // Passed its test: 2-3 runs from the same start save, then one save. + VERIFICATION, + // Verified: a playthrough saves at its end. + REPRODUCTION, +}; + +// The wire and log name of a phase: "testing", "verification", "reproduction". +std::string story_phase_name(StoryPhase phase); + +// The phase named `name`; none for another name. +std::optional read_story_phase(std::string_view name); + +// A checkpoint's "metadata" object. +struct StoryCheckpointMetadata{ + StoryPhase phase = StoryPhase::TESTING; + // Where the steps came from: a walkthrough, a console recording. + std::string source = {}; + + bool operator==(const StoryCheckpointMetadata& other) const = default; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h new file mode 100644 index 0000000000..228b7ca058 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h @@ -0,0 +1,41 @@ +/* Story Step + * + * From: https://github.com/PokemonAutomation/ + * + * One step of a game's story as plain data: its kind, the action that does + * it and the action's args. The shared JSON reader reads it + * (Data/Pokemon_StoryStepJson.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStep_H +#define PokemonAutomation_Pokemon_StoryStep_H + +#include +#include "Pokemon_StoryActionArg.h" +#include "Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// One step of a checkpoint: an action and its args. +struct StoryStep{ + StoryStepKind kind = StoryStepKind::TALK; + std::string name; + std::string why; + + // How the step does its kind: one of the game's actions; for a GAME + // step, the game's action. Empty is the kind's default action. + std::string action; + // The arguments the action reads, parsed against its spec when the + // game loads the step, with the spec's fallbacks filled in. + StoryActionArgs args; + +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp new file mode 100644 index 0000000000..28b755779b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp @@ -0,0 +1,52 @@ +/* Story Step Kind + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string story_step_kind_name(StoryStepKind kind){ + switch (kind){ + case StoryStepKind::NEW_GAME: + return "NEW_GAME"; + case StoryStepKind::OPTIONS: + return "OPTIONS"; + case StoryStepKind::ROUTE: + return "ROUTE"; + case StoryStepKind::LEGS: + return "LEGS"; + case StoryStepKind::STEP: + return "STEP"; + case StoryStepKind::TALK: + return "TALK"; + case StoryStepKind::ANSWER: + return "ANSWER"; + case StoryStepKind::MASH: + return "MASH"; + case StoryStepKind::BATTLE: + return "BATTLE"; + case StoryStepKind::TRAIN: + return "TRAIN"; + case StoryStepKind::HEAL: + return "HEAL"; + case StoryStepKind::SHOP: + return "SHOP"; + case StoryStepKind::SAVE: + return "SAVE"; + case StoryStepKind::READY: + return "READY"; + case StoryStepKind::GAME: + return "GAME"; + } + return "?"; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h new file mode 100644 index 0000000000..e3c2905bbb --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h @@ -0,0 +1,45 @@ +/* Story Step Kind + * + * From: https://github.com/PokemonAutomation/ + * + * The kinds of story step the games share. A game does each kind its own + * way, with its own actions. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStepKind_H +#define PokemonAutomation_Pokemon_StoryStepKind_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Action category classification for individual story steps. +enum class StoryStepKind{ + NEW_GAME, // title screen (no save) to the first room + OPTIONS, // the game's options as the story needs them + ROUTE, // plan and walk to `target` + LEGS, // walk `legs` as given + STEP, // one step `direction`: onto a trigger, into a door + TALK, // A at what the player faces + ANSWER, // text to a YES/NO, then `yes` + MASH, // text until the overworld is back: a scene + BATTLE, // text into a battle, fight it, text to the overworld + TRAIN, // fight `battles` wild battles where the player stands + HEAL, // the nurse, from in front of her or of the Center's door + SHOP, // `items` from a shop + SAVE, // save the game where the player stands + READY, // before a big battle: items, and the nurse at `target` if they can't + GAME, // a step only this game has, named by `action` +}; + +// Returns the readable string representation of a story step kind. +std::string story_step_kind_name(StoryStepKind kind); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index a8c5e2d9a5..2392ff29ae 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1483,6 +1483,45 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_AutoStorySelect.h Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.cpp Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h + Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp +Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.h +Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp +Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h +Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.cpp +Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.h +Pokemon/AutoStory/Data/Pokemon_StoryFiles.cpp +Pokemon/AutoStory/Data/Pokemon_StoryFiles.h +Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.cpp +Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.h +Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp +Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h +Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp +Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h +Pokemon/AutoStory/Engine/Pokemon_ZonePose.cpp +Pokemon/AutoStory/Engine/Pokemon_ZonePose.h +Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +Pokemon/AutoStory/Pokemon_MapUtil.h +Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp +Pokemon/AutoStory/Pokemon_StoryLog_Tests.h +Pokemon/AutoStory/Pokemon_StoryLog.cpp +Pokemon/AutoStory/Pokemon_StoryLog.h +Pokemon/AutoStory/Pokemon_StoryOutcome.cpp +Pokemon/AutoStory/Pokemon_StoryOutcome.h +Pokemon/AutoStory/Pokemon_StoryPose.cpp +Pokemon/AutoStory/Pokemon_StoryPose.h +Pokemon/AutoStory/Types/Pokemon_DeclaredPose.h +Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp +Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.h +Pokemon/AutoStory/Types/Pokemon_StoryActionArg.cpp +Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h +Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.cpp +Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h +Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h +Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.cpp +Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h +Pokemon/AutoStory/Types/Pokemon_StoryStep.h +Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp +Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h Source/Pokemon/Pokemon_AdvRng.cpp Source/Pokemon/Pokemon_AdvRng.h Source/Pokemon/Pokemon_BdspRng.cpp From cb2689cc569220b06016be732509622dee45cada Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 13:11:12 -0800 Subject: [PATCH 2/4] AutoStory: list the story data files one per line in SourceFiles.cmake --- .../ComputerPrograms_UnitTestRunner.cpp | 2 + .../AutoStory/Pokemon_AutoStory_Tests.h | 84 ++++++++++--------- SerialPrograms/cmake/SourceFiles.cmake | 78 ++++++++--------- 3 files changed, 87 insertions(+), 77 deletions(-) diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 4be358605a..64d2008712 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -27,6 +27,7 @@ #include "CommonFramework/Tools/GlobalThreadPools.h" #include "CommonTools/VisualDetectors/BlackBorderDetector.h" #include "CommonTools/OCR/OCR_Tests.h" +#include "CommonTools/ScreenEvents/ScreenEvents_Tests.h" #include "NintendoSwitch/Inference/NintendoSwitch_CheckOnlineDetector.h" #include "NintendoSwitch/Inference/NintendoSwitch_FailedToConnectDetector.h" @@ -75,6 +76,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Kernels::add_tests(ret); Pokemon::add_tests_AutoStorySelect(ret); Pokemon::add_tests_AutoStory(ret); + add_tests_ScreenEvents(ret); Pokemon::add_tests_StoryRangeOptions(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 4827c66e81..25f400bd18 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -1,38 +1,46 @@ -/* AutoStory Tests - * - * From: https://github.com/PokemonAutomation/ - * - * The unit tests of the pieces every AutoStory program shares, story - * engine or not. add_tests_AutoStory() is the one entry point the unit - * test runner calls; a new shared AutoStory suite registers there. - * - */ - -#ifndef PokemonAutomation_Pokemon_AutoStory_Tests_H -#define PokemonAutomation_Pokemon_AutoStory_Tests_H - -#include "Common/Cpp/TestRunners/UnitTestDatabase.h" -#include "Data/Pokemon_AuthoredCheckpointJson_Tests.h" -#include "Data/Pokemon_StoryFiles_Tests.h" -#include "Data/Pokemon_StoryStepJson_Tests.h" -#include "Pokemon_StoryLog_Tests.h" -#include "Types/Pokemon_StoryActionArg_Tests.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -// Registers every shared AutoStory suite, for the unit test runner. -inline void add_tests_AutoStory(UnitTestDatabase& database){ - add_tests_StoryActionArg(database); - add_tests_StoryLog(database); - add_tests_StoryStepJson(database); - add_tests_AuthoredCheckpointJson(database); - add_tests_StoryFiles(database); -} - - - -} // namespace Pokemon -} // namespace PokemonAutomation -#endif +/* AutoStory Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The unit tests of the pieces every AutoStory program shares, story + * engine or not. add_tests_AutoStory() is the one entry point the unit + * test runner calls; a new shared AutoStory suite registers there. + * + */ + +#ifndef PokemonAutomation_Pokemon_AutoStory_Tests_H +#define PokemonAutomation_Pokemon_AutoStory_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Data/Pokemon_AuthoredCheckpointJson_Tests.h" +#include "Data/Pokemon_StoryFiles_Tests.h" +#include "Data/Pokemon_StoryStepJson_Tests.h" +#include "Engine/Pokemon_StoryBackend_Tests.h" +#include "Engine/Pokemon_StoryEngine_Tests.h" +#include "Pokemon_CheckpointAttempts_Tests.h" +#include "Pokemon_StoryEvents_Tests.h" +#include "Pokemon_StoryLog_Tests.h" +#include "Types/Pokemon_StoryActionArg_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers every shared AutoStory suite, for the unit test runner. +inline void add_tests_AutoStory(UnitTestDatabase& database){ + add_tests_StoryActionArg(database); + add_tests_StoryLog(database); + add_tests_StoryStepJson(database); + add_tests_AuthoredCheckpointJson(database); + add_tests_StoryFiles(database); + add_tests_StoryBackend(database); + add_tests_CheckpointAttempts(database); + add_tests_StoryEvents(database); + add_tests_StoryEngine(database); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 2392ff29ae..e16e53e9b1 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1483,45 +1483,45 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_AutoStorySelect.h Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.cpp Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h - Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp -Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.h -Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp -Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h -Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.cpp -Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.h -Pokemon/AutoStory/Data/Pokemon_StoryFiles.cpp -Pokemon/AutoStory/Data/Pokemon_StoryFiles.h -Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.cpp -Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.h -Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp -Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h -Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp -Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h -Pokemon/AutoStory/Engine/Pokemon_ZonePose.cpp -Pokemon/AutoStory/Engine/Pokemon_ZonePose.h -Pokemon/AutoStory/Pokemon_AutoStory_Tests.h -Pokemon/AutoStory/Pokemon_MapUtil.h -Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp -Pokemon/AutoStory/Pokemon_StoryLog_Tests.h -Pokemon/AutoStory/Pokemon_StoryLog.cpp -Pokemon/AutoStory/Pokemon_StoryLog.h -Pokemon/AutoStory/Pokemon_StoryOutcome.cpp -Pokemon/AutoStory/Pokemon_StoryOutcome.h -Pokemon/AutoStory/Pokemon_StoryPose.cpp -Pokemon/AutoStory/Pokemon_StoryPose.h -Pokemon/AutoStory/Types/Pokemon_DeclaredPose.h -Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp -Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.h -Pokemon/AutoStory/Types/Pokemon_StoryActionArg.cpp -Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h -Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.cpp -Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h -Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h -Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.cpp -Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h -Pokemon/AutoStory/Types/Pokemon_StoryStep.h -Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp -Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h + Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp + Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h + Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp + Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.h + Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.cpp + Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.h + Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.cpp + Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.h + Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.cpp + Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.h + Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp + Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h + Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp + Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h + Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.cpp + Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.h + Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h + Source/Pokemon/AutoStory/Pokemon_MapUtil.h + Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp + Source/Pokemon/AutoStory/Pokemon_StoryLog.h + Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.h + Source/Pokemon/AutoStory/Pokemon_StoryOutcome.cpp + Source/Pokemon/AutoStory/Pokemon_StoryOutcome.h + Source/Pokemon/AutoStory/Pokemon_StoryPose.cpp + Source/Pokemon/AutoStory/Pokemon_StoryPose.h + Source/Pokemon/AutoStory/Types/Pokemon_DeclaredPose.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h Source/Pokemon/Pokemon_AdvRng.cpp Source/Pokemon/Pokemon_AdvRng.h Source/Pokemon/Pokemon_BdspRng.cpp From 279e65b367ed4659257273d6df9488f55f84952a Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 13:11:22 -0800 Subject: [PATCH 3/4] AutoStory: keep the test registration of B's suites only --- .../ComputerPrograms_UnitTestRunner.cpp | 2 - .../AutoStory/Pokemon_AutoStory_Tests.h | 84 +++++++++---------- 2 files changed, 38 insertions(+), 48 deletions(-) diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 64d2008712..4be358605a 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -27,7 +27,6 @@ #include "CommonFramework/Tools/GlobalThreadPools.h" #include "CommonTools/VisualDetectors/BlackBorderDetector.h" #include "CommonTools/OCR/OCR_Tests.h" -#include "CommonTools/ScreenEvents/ScreenEvents_Tests.h" #include "NintendoSwitch/Inference/NintendoSwitch_CheckOnlineDetector.h" #include "NintendoSwitch/Inference/NintendoSwitch_FailedToConnectDetector.h" @@ -76,7 +75,6 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Kernels::add_tests(ret); Pokemon::add_tests_AutoStorySelect(ret); Pokemon::add_tests_AutoStory(ret); - add_tests_ScreenEvents(ret); Pokemon::add_tests_StoryRangeOptions(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 25f400bd18..4827c66e81 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -1,46 +1,38 @@ -/* AutoStory Tests - * - * From: https://github.com/PokemonAutomation/ - * - * The unit tests of the pieces every AutoStory program shares, story - * engine or not. add_tests_AutoStory() is the one entry point the unit - * test runner calls; a new shared AutoStory suite registers there. - * - */ - -#ifndef PokemonAutomation_Pokemon_AutoStory_Tests_H -#define PokemonAutomation_Pokemon_AutoStory_Tests_H - -#include "Common/Cpp/TestRunners/UnitTestDatabase.h" -#include "Data/Pokemon_AuthoredCheckpointJson_Tests.h" -#include "Data/Pokemon_StoryFiles_Tests.h" -#include "Data/Pokemon_StoryStepJson_Tests.h" -#include "Engine/Pokemon_StoryBackend_Tests.h" -#include "Engine/Pokemon_StoryEngine_Tests.h" -#include "Pokemon_CheckpointAttempts_Tests.h" -#include "Pokemon_StoryEvents_Tests.h" -#include "Pokemon_StoryLog_Tests.h" -#include "Types/Pokemon_StoryActionArg_Tests.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -// Registers every shared AutoStory suite, for the unit test runner. -inline void add_tests_AutoStory(UnitTestDatabase& database){ - add_tests_StoryActionArg(database); - add_tests_StoryLog(database); - add_tests_StoryStepJson(database); - add_tests_AuthoredCheckpointJson(database); - add_tests_StoryFiles(database); - add_tests_StoryBackend(database); - add_tests_CheckpointAttempts(database); - add_tests_StoryEvents(database); - add_tests_StoryEngine(database); -} - - - -} // namespace Pokemon -} // namespace PokemonAutomation -#endif +/* AutoStory Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The unit tests of the pieces every AutoStory program shares, story + * engine or not. add_tests_AutoStory() is the one entry point the unit + * test runner calls; a new shared AutoStory suite registers there. + * + */ + +#ifndef PokemonAutomation_Pokemon_AutoStory_Tests_H +#define PokemonAutomation_Pokemon_AutoStory_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Data/Pokemon_AuthoredCheckpointJson_Tests.h" +#include "Data/Pokemon_StoryFiles_Tests.h" +#include "Data/Pokemon_StoryStepJson_Tests.h" +#include "Pokemon_StoryLog_Tests.h" +#include "Types/Pokemon_StoryActionArg_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers every shared AutoStory suite, for the unit test runner. +inline void add_tests_AutoStory(UnitTestDatabase& database){ + add_tests_StoryActionArg(database); + add_tests_StoryLog(database); + add_tests_StoryStepJson(database); + add_tests_AuthoredCheckpointJson(database); + add_tests_StoryFiles(database); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif From f8728e16d7d36c161b0a894d89ab494431df5bf3 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 15:34:18 -0800 Subject: [PATCH 4/4] StoryFiles test: drop the extra trailing space in the built-in files summary --- .../Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.cpp index 70e1b1e95b..ebe255ca6c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.cpp @@ -104,7 +104,7 @@ const LoadCase LOAD_CASES[] = { { .name = "built-in files in order, their shared execution fields read", .input = {.builtin = {ROW_0, ROW_1, ROW_2}}, - .expectation = {.summary = "rows 01.00 01.01 01.02 | titles Row Row Row | autosave 01.00 | unverified 01.02 | chained 01.01 | always "}, + .expectation = {.summary = "rows 01.00 01.01 01.02 | titles Row Row Row | autosave 01.00 | unverified 01.02 | chained 01.01 | always "}, }, { .name = "reload_when_chained always",