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..64b5f687f8 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp @@ -0,0 +1,59 @@ +/* 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; +} + +StoryCheckpoint load_authored_checkpoint( + std::span files, std::string_view file, std::string_view game, + const ExecutionReader& read_execution, std::span actions +){ + for (const auto& [name, text] : files){ + if (name == file){ + return read_authored_checkpoint(parse_json(text), game, file, read_execution, actions); + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("Authored checkpoint is not embedded: {}", file)); +} + + + +} // 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..174552214e --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h @@ -0,0 +1,73 @@ +/* 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/Pokemon_BuiltinStoryActions.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 = builtin_story_actions() +); + +// A JSON file built into the program: its name without ".json", and its +// text. +using EmbeddedJsonFile = std::pair; + +// Find embedded file `file` among `files` and parse it as +// read_authored_checkpoint() does. Missing resources throw +// InternalProgramError; malformed documents throw ParseException. +StoryCheckpoint load_authored_checkpoint( + std::span files, std::string_view file, std::string_view game, + const ExecutionReader& read_execution, + std::span actions = builtin_story_actions() +); + + + +} // 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..332ae482ad --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp @@ -0,0 +1,155 @@ +/* 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, + MISSING_RESOURCE, +}; + +struct AuthoredCase{ + std::string name; + struct Input{ + std::string json; + std::string game = "frlg"; + bool resource = false; + std::string file = "plan"; + }; + + 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 embedded resource", .input = {.json = BDSP, .game = "bdsp", .resource = true}, .expectation = { + .checkpoint = "01.03", .execution = R"({"on_failure":"reload_and_retry","saves_in":"Oreburgh City"})", .events = {"roark"}}}, + {.name = "FRLG embedded resource", .input = {.json = FRLG, .resource = true}, .expectation = {}}, + {.name = "wrong game", .input = {.json = BDSP}, .expectation = {.failure = Failure::PARSE}}, + {.name = "empty expected game", .input = {.json = FRLG, .game = ""}, .expectation = {.failure = Failure::PARSE}}, + {.name = "missing resource", .input = {.json = FRLG, .resource = true, .file = "absent"}, .expectation = {.failure = Failure::MISSING_RESOURCE}}, + {.name = "invalid embedded JSON", .input = {.json = "{", .resource = true}, .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 = {}}}, +}; + + +// 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{ + const std::vector> files = {{"plan", test.input.json}}; + Loaded actual; + actual.checkpoint = test.input.resource + ? load_authored_checkpoint(files, test.input.file, test.input.game, keep_execution(actual.execution)) + : read_authored_checkpoint(parse_json(test.input.json), test.input.game, test.name, keep_execution(actual.execution)); + return check_loaded(actual, test); + }catch (const ParseException& error){ + return test.expectation.failure == Failure::PARSE ? "" : std::format("Unexpected parse failure: {}", error.message()); + }catch (const InternalProgramError& error){ + return test.expectation.failure == Failure::MISSING_RESOURCE ? "" : std::format("Unexpected resource 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_StoryDevFiles.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryDevFiles.h new file mode 100644 index 0000000000..ba0cb401a9 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryDevFiles.h @@ -0,0 +1,31 @@ +/* Story Dev Files + * + * From: https://github.com/PokemonAutomation/ + * + * Checkpoint files that a run reads in place of the built-in ones of the + * same name (load_story_data() in Pokemon_StoryFiles.h). The program + * passes none; the tests pass their own. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryDevFiles_H +#define PokemonAutomation_Pokemon_StoryDevFiles_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A checkpoint file read from disk. +struct StoryDevFile{ + std::string name; // "plza-02.01.plan.json" + std::string path; + std::string text; +}; + + + +} // 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..40c416397a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.cpp @@ -0,0 +1,134 @@ +/* Story Files + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryFiles.h" + +namespace PokemonAutomation{ +namespace Pokemon{ +namespace detail{ + + +void check_dev_file_names(std::span builtin, std::span dev_files){ + for (const StoryDevFile& dev : dev_files){ + bool known = false; + for (const auto& [name, text] : builtin){ + known |= dev.name == std::format("{}.json", name); + } + if (!known){ + throw ParseException(std::format("{}: no built-in checkpoint file is named {}", dev.path, dev.name)); + } + } +} + +const StoryDevFile* find_dev_file(std::span dev_files, std::string_view builtin_name){ + const std::string file_name = std::format("{}.json", builtin_name); + for (const StoryDevFile& file : dev_files){ + if (file.name == file_name){ + return &file; + } + } + return nullptr; +} + +ParseException naming_path(const ParseException& error, std::string_view path){ + const std::string message = error.message(); + if (message.find(path) != std::string::npos){ + return error; + } + return ParseException(std::format("{}: {}", path, message)); +} + +void check_dev_checkpoint( + std::string_view path, std::string_view id, std::string_view builtin_id, const std::vector& problems +){ + if (id != builtin_id){ + throw ParseException(std::format("{}: checkpoint id {} does not match the built-in {}", path, id, builtin_id)); + } + if (!problems.empty()){ + throw ParseException(std::format("{}: {}", path, problems.front())); + } +} + +void check_in_story_order( + const std::function& in_story_order, std::string_view id, std::string_view source +){ + if (in_story_order && !in_story_order(id)){ + throw ParseException(std::format("{}: checkpoint {} is not in the game's story order", source, id)); + } +} + +namespace{ + +// Which row sequence the reload check applies to. +enum class RunKind{ + DEVELOPER, + USER, +}; + +// Text naming `run` in a reload error. +std::string_view run_suffix(RunKind run){ + switch (run){ + case RunKind::DEVELOPER: + return ""; + case RunKind::USER: + return " in a user's run"; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown story run kind."); +} + +// Throws ParseException naming `source` unless `previous` ends on the +// game's autosave in `rows`, for `run`. +void check_reload_after( + std::optional previous, const StoryRows& rows, RunKind run, std::string_view 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, run_suffix(run) + )); + } +} + +} // namespace + +void add_story_row( + std::string_view id, const StoryRowExecution& execution, RowSave start, + const PreviousRows& 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)); + } + check_reload_after(previous.in_dev_run, rows, RunKind::DEVELOPER, source); + if (!execution.dev_only && previous.in_user_run != previous.in_dev_run){ + check_reload_after(previous.in_user_run, rows, RunKind::USER, 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; + } + if (execution.dev_only){ + rows.dev_only.emplace(id); + } +} + + + +} // 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..9aafa127b6 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.h @@ -0,0 +1,238 @@ +/* Story Files + * + * From: https://github.com/PokemonAutomation/ + * + * A game's story read from its checkpoint files: the game's own files, + * passed in by name and text, each replaced by the dev file of the same + * name if there is one (Pokemon_StoryDevFiles.h), so a walk can be + * retimed on the console without a rebuild. 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 dev file replaces a built-in + * file, keeps its checkpoint's id and passes the game's lint, and 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 +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_AuthoredCheckpointJson.h" +#include "Pokemon_StoryDevFiles.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; + // The problems the game finds in a dev file's checkpoint; the first + // one refuses the file. None set: no lint. + std::function(const Checkpoint&)> lint = {}; + // 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 = {}; + // Whether the game plays checkpoint `a` before `b`, when that is not + // the order of its files' names. None set: file-name order. + std::function plays_before = {}; + // Whether the game's story order lists checkpoint `id`: a file whose + // id it does not list is refused, not skipped or played out of place. + // None set: the game keeps no list, and every id plays. + std::function in_story_order = {}; +}; + + +// The story of the built-in checkpoint files `builtin`, in their order or +// the game's (StoryFileReader::plays_before), each of `dev_files` in place +// of the built-in file of its name. Throws ParseException naming the file +// when a file does not parse, a dev file matches no built-in file, changes +// its checkpoint's id or fails the game's lint, a file's checkpoint id is +// not in the game's story order (StoryFileReader::in_story_order), or a +// row reloads a save it cannot count on in the order the story plays. +template +StoryData load_story_data( + std::span builtin, std::span dev_files, + const StoryFileReader& reader +); + +// Who a run's rows are listed for. +enum class StoryRowsShown{ + USER, // every row but the dev-only ones + DEVELOPER, // every row (the program's Developer Mode) +}; + +// The rows of `story` a run may play, in order. The start and end +// dropdowns list these, so their indices name these rows. +template +std::vector story_rows_for_mode(const StoryData& story, StoryRowsShown shown); + +// 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{ + +// Throws ParseException naming the dev file that matches no built-in file. +void check_dev_file_names(std::span builtin, std::span dev_files); +// The dev file that replaces the built-in file `builtin_name` (its name +// without ".json"); null if none. +const StoryDevFile* find_dev_file(std::span dev_files, std::string_view builtin_name); +// `error`, its message prefixed with `path` unless it already names it. +ParseException naming_path(const ParseException& error, std::string_view path); +// Throws ParseException naming `path` when the dev file's checkpoint `id` +// is not the built-in file's `builtin_id`, or `problems` is not empty. +void check_dev_checkpoint( + std::string_view path, std::string_view id, std::string_view builtin_id, const std::vector& problems +); + +// Throws ParseException naming `source` and `id` when `in_story_order` +// is set and does not list `id`. +void check_in_story_order( + const std::function& in_story_order, std::string_view id, std::string_view source +); + +// Whether a row starts from a save, which a reload can load. +enum class RowSave{ + FROM_SAVE, + WITHOUT_SAVE, // a new game +}; + +// The rows a row follows in play: in a developer's run, and in a user's, +// which skips the dev-only rows. None for the first row. +struct PreviousRows{ + std::optional in_dev_run; + std::optional in_user_run; +}; + +// Adds row `id` to the sets of `rows`. Throws ParseException naming +// `source` when it reloads and starts WITHOUT_SAVE or a row it follows +// (`previous`: in a developer's run; and in a user's, unless it is +// dev-only itself) 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, + const PreviousRows& previous, std::string_view source, StoryRows& rows +); + +// The dev file `dev`'s row, in place of the built-in file `builtin_name`: +// it must parse, keep the built-in checkpoint's id and pass the lint. +template +StoryFileRow read_dev_file( + const StoryDevFile& dev, std::string_view builtin_text, std::string_view builtin_name, + const StoryFileReader& reader +){ + StoryFileRow row; + try{ + row = reader.read(dev.text, dev.path); + }catch (const ParseException& error){ + // Malformed JSON says nothing of where it came from. + throw naming_path(error, dev.path); + } + const std::string builtin_id = reader.read(builtin_text, builtin_name).checkpoint.id; + const std::vector problems = reader.lint ? reader.lint(row.checkpoint) : std::vector{}; + check_dev_checkpoint(dev.path, row.checkpoint.id, builtin_id, problems); + return row; +} + +} // namespace detail + + +template +StoryData load_story_data( + std::span builtin, std::span dev_files, + const StoryFileReader& reader +){ + detail::check_dev_file_names(builtin, dev_files); + StoryData data; + struct SourcedRow{ + StoryFileRow row; + std::string_view source; + }; + std::vector rows; + for (const auto& [name, text] : builtin){ + const StoryDevFile* dev = detail::find_dev_file(dev_files, name); + if (dev == nullptr){ + rows.push_back({reader.read(text, name), name}); + continue; + } + rows.push_back({detail::read_dev_file(*dev, text, name, reader), dev->path}); + data.dev_files.emplace_back(dev->name, dev->path); + } + for (const auto& [row, source] : rows){ + detail::check_in_story_order(reader.in_story_order, row.checkpoint.id, source); + } + if (reader.plays_before){ + std::stable_sort(rows.begin(), rows.end(), [&](const SourcedRow& a, const SourcedRow& b){ + return reader.plays_before(a.row.checkpoint, b.row.checkpoint); + }); + } + // A reload loads the save the row before it in play ends on, in a + // developer's run and in a user's. + std::optional last_user_row; + for (auto& [row, source] : rows){ + const bool new_game = reader.starts_without_save && reader.starts_without_save(row.checkpoint); + const detail::PreviousRows previous{ + .in_dev_run = data.checkpoints.empty() ? std::nullopt : std::optional(data.checkpoints.back().id), + .in_user_run = last_user_row ? std::optional(data.checkpoints[*last_user_row].id) : std::nullopt, + }; + detail::add_story_row( + row.checkpoint.id, row.execution, + new_game ? detail::RowSave::WITHOUT_SAVE : detail::RowSave::FROM_SAVE, + previous, source, data + ); + if (!row.execution.dev_only){ + last_user_row = data.checkpoints.size(); + } + data.checkpoints.push_back(std::move(row.checkpoint)); + } + return data; +} + +template +std::vector story_rows_for_mode(const StoryData& story, StoryRowsShown shown){ + std::vector rows; + for (const Checkpoint& row : story.checkpoints){ + if (shown == StoryRowsShown::DEVELOPER || !story.dev_only.contains(row.id)){ + rows.push_back(row); + } + } + return rows; +} + +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..170dc30422 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.cpp @@ -0,0 +1,436 @@ +/* Story Files Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#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". Its lint refuses +// the title "unlinted"; 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, + .lint = [](const StoryCheckpoint& checkpoint){ + return checkpoint.title == "unlinted" ? std::vector{"title is unlinted"} : std::vector{}; + }, + .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 | dev_only | dev x.json" +std::string summary(const StoryData& data){ + std::vector dev; + for (const auto& [name, path] : data.dev_files){ + dev.push_back(std::format("{}@{}", name, path)); + } + std::vector titles; + for (const StoryCheckpoint& row : data.checkpoints){ + titles.push_back(row.title); + } + return std::format( + "rows {} | titles {} | autosave {} | unverified {} | chained {} | always {} | dev_only {} | dev {}", + joined(ids(data.checkpoints)), joined(titles), joined(data.autosaves), joined(data.unverified_autosaves), + joined(data.reload_when_chained), + joined(data.reload_always), joined(data.dev_only), joined(dev) + ); +} + + +struct LoadCase{ + std::string name; + struct Input{ + std::vector builtin; + std::vector dev_files = {}; + // Whether the game plays its rows in id order, not file-name order. + bool ordered_by_id = false; + // The ids the game's story order lists; none: the game lists none. + std::optional> story_order = std::nullopt; + }; + 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"({"dev_only": true, "save": "unverified"})")}; + +StoryDevFile dev_file(std::string_view name, std::string text){ + return StoryDevFile{.name = std::string(name), .path = std::format("/dev/{}", name), .text = std::move(text)}; +} + +// Named to come after 01.01 by file name, before it by id. +const EmbeddedJsonFile ROW_0B_NO_SAVE = {"test-01.10.plan", file_text("01.00b", "{}")}; + +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 | dev_only 01.02 | dev "}, + }, + { + .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 | dev_only | dev "}, + }, + { + .name = "a dev file replaces the built-in file of its name and is named", + .input = { + .builtin = {ROW_0, ROW_1}, + .dev_files = {dev_file("test-01.01.plan.json", file_text("01.01", R"({"reload_when_chained": true})", "Retimed"))}, + }, + .expectation = {.summary = "rows 01.00 01.01 | titles Row Retimed | autosave 01.00 | unverified | chained 01.01 | always | dev_only | dev test-01.01.plan.json@/dev/test-01.01.plan.json"}, + }, + { + .name = "a dev file that is not JSON fails naming its path", + .input = {.builtin = {ROW_0}, .dev_files = {dev_file("test-01.00.plan.json", "{ not json")}}, + .expectation = {.error = "/dev/test-01.00.plan.json"}, + }, + { + .name = "a dev file with no built-in file of its name fails", + .input = {.builtin = {ROW_0}, .dev_files = {dev_file("test-09.99.plan.json", file_text("09.99", "{}"))}}, + .expectation = {.error = "/dev/test-09.99.plan.json: no built-in checkpoint file is named test-09.99.plan.json"}, + }, + { + .name = "a dev file that changes its checkpoint's id fails", + .input = {.builtin = {ROW_0}, .dev_files = {dev_file("test-01.00.plan.json", file_text("01.09", R"({"save": "autosave"})"))}}, + .expectation = {.error = "/dev/test-01.00.plan.json: checkpoint id 01.09 does not match the built-in 01.00"}, + }, + { + .name = "a dev file the game's lint refuses fails", + .input = {.builtin = {ROW_0}, .dev_files = {dev_file("test-01.00.plan.json", file_text("01.00", "{}", "unlinted"))}}, + .expectation = {.error = "/dev/test-01.00.plan.json: title is unlinted"}, + }, + { + .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 = "dev_only false fails", + .input = {.builtin = {{"test-01.00.plan", file_text("01.00", R"({"dev_only": false})")}}}, + .expectation = {.error = "dev_only is true or left out"}, + }, + { + .name = "save autosave", + .input = {.builtin = {ROW_0}}, + .expectation = {.summary = "rows 01.00 | titles Row | autosave 01.00 | unverified | chained | always | dev_only | dev "}, + }, + { + .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 | dev_only | dev "}, + }, + { + .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 | dev_only | dev "}, + }, + { + .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 = "a dev-only reload after a dev-only autosave row, the user's row before it not autosaving, loads", + .input = {.builtin = { + {"test-01.00.plan", file_text("01.00", "{}")}, + {"test-01.005.plan", file_text("01.005", R"({"dev_only": true, "save": "autosave"})")}, + {"test-01.01.plan", file_text("01.01", R"({"dev_only": true, "reload_when_chained": true})")}, + }}, + .expectation = {.summary = "rows 01.00 01.005 01.01 | titles Row Row Row | autosave 01.005 | unverified | chained 01.01 | always | dev_only 01.005 01.01 | dev "}, + }, + { + .name = "reload_when_chained after a dev-only autosave row, the user's row before it not autosaving, fails", + .input = {.builtin = { + {"test-01.00.plan", file_text("01.00", "{}")}, + {"test-01.005.plan", file_text("01.005", R"({"dev_only": true, "save": "autosave"})")}, + ROW_1, + }}, + .expectation = {.error = "test-01.01.plan: reload_when_chained after a checkpoint that does not end on the game's autosave in a user's run"}, + }, + { + .name = "reload_when_chained after a dev-only row, both rows before it autosaving", + .input = {.builtin = { + ROW_0, + {"test-01.005.plan", file_text("01.005", R"({"dev_only": true, "save": "autosave"})")}, + ROW_1, + }}, + .expectation = {.summary = "rows 01.00 01.005 01.01 | titles Row Row Row | autosave 01.00 01.005 | unverified | chained 01.01 | always | dev_only 01.005 | dev "}, + }, + { + .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"}, + }, + { + .name = "the game's order, its reload after the autosave row it follows there", + .input = {.builtin = {ROW_1, ROW_0}, .ordered_by_id = true}, + .expectation = {.summary = "rows 01.00 01.01 | titles Row Row | autosave 01.00 | unverified | chained 01.01 | always | dev_only | dev "}, + }, + { + .name = "the game's order, its reload after a row that does not autosave there fails", + .input = {.builtin = {ROW_0, ROW_1, ROW_0B_NO_SAVE}, .ordered_by_id = true}, + .expectation = {.error = "test-01.01.plan: reload_when_chained after a checkpoint that does not end on the game's autosave"}, + }, + { + .name = "every id in the game's story order loads", + .input = {.builtin = {ROW_0, ROW_1}, .story_order = std::vector{"01.00", "01.01"}}, + .expectation = {.summary = "rows 01.00 01.01 | titles Row Row | autosave 01.00 | unverified | chained 01.01 | always | dev_only | dev "}, + }, + { + .name = "a built-in file whose id is not in the game's story order fails naming the file and the id", + .input = {.builtin = {ROW_0, ROW_1}, .story_order = std::vector{"01.00"}}, + .expectation = {.error = "test-01.01.plan: checkpoint 01.01 is not in the game's story order"}, + }, + { + .name = "a dev file in the game's story order replaces the built-in file", + .input = { + .builtin = {ROW_0, ROW_1}, + .dev_files = {dev_file("test-01.01.plan.json", file_text("01.01", R"({"reload_when_chained": true})", "Retimed"))}, + .story_order = std::vector{"01.00", "01.01"}, + }, + .expectation = {.summary = "rows 01.00 01.01 | titles Row Retimed | autosave 01.00 | unverified | chained 01.01 | always | dev_only | dev test-01.01.plan.json@/dev/test-01.01.plan.json"}, + }, + { + .name = "a dev file whose id is not in the game's story order fails naming its path and the id", + .input = { + .builtin = {ROW_0}, + .dev_files = {dev_file("test-01.00.plan.json", file_text("01.00", R"({"save": "autosave"})"))}, + .story_order = std::vector{"01.01"}, + }, + .expectation = {.error = "/dev/test-01.00.plan.json: checkpoint 01.00 is not in the game's story order"}, + }, +}; + +UnitTestResult check_load(const LoadCase& test){ + StoryFileReader reader = TEST_READER; + if (test.input.ordered_by_id){ + reader.plays_before = [](const StoryCheckpoint& a, const StoryCheckpoint& b){ + return a.id < b.id; + }; + } + if (test.input.story_order){ + reader.in_story_order = [&order = *test.input.story_order](std::string_view id){ + return std::find(order.begin(), order.end(), id) != order.end(); + }; + } + std::string got; + std::string error; + try{ + got = summary(load_story_data(test.input.builtin, test.input.dev_files, 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{ + StoryRowsShown shown = StoryRowsShown::USER; + size_t first = 0; + size_t last = 0; + }; + Input input; + struct Expectation{ + std::string rows = {}; + }; + Expectation expectation; +}; + +// 01.00, 01.01, 01.02 with 01.01 dev-only. +const RowsCase ROWS_CASES[] = { + {.name = "Developer Mode lists every row", .input = {.shown = StoryRowsShown::DEVELOPER, .first = 0, .last = 2}, .expectation = {.rows = "01.00 01.01 01.02"}}, + {.name = "a user's run skips the dev-only rows", .input = {.shown = StoryRowsShown::USER, .first = 0, .last = 1}, .expectation = {.rows = "01.00 01.02"}}, + {.name = "a run from one row to a later one", .input = {.shown = StoryRowsShown::DEVELOPER, .first = 1, .last = 2}, .expectation = {.rows = "01.01 01.02"}}, + {.name = "no rows for a start after the end", .input = {.shown = StoryRowsShown::DEVELOPER, .first = 2, .last = 1}, .expectation = {.rows = ""}}, + {.name = "no rows for an end past the table", .input = {.shown = StoryRowsShown::USER, .first = 0, .last = 2}, .expectation = {.rows = ""}}, +}; + +UnitTestResult check_rows(const RowsCase& test){ + StoryData story; + for (std::string_view id : {"01.00", "01.01", "01.02"}){ + StoryCheckpoint row; + row.id = std::string(id); + story.checkpoints.push_back(std::move(row)); + } + story.dev_only.emplace("01.01"); + const std::vector shown = story_rows_for_mode(story, test.input.shown); + const std::string got = joined(ids(story_run_rows(shown, test.input.first, test.input.last))); + if (got != test.expectation.rows){ + return std::format("expected \"{}\", got \"{}\"", test.expectation.rows, got); + } + return true; +} + + +struct ReloadCase{ + std::string name; + struct Input{ + StoryRunPolicy::BoundaryReload boundary_reload = StoryRunPolicy::BoundaryReload::AT_PLAN_BOUNDARIES; + std::string row = {}; + }; + Input input; + struct Expectation{ + bool reloads = false; + }; + Expectation expectation; +}; + +// 01.01 reloads when chained, 01.02 always. +const ReloadCase RELOAD_CASES[] = { + {.name = "at plan boundaries, a when-chained row reloads", .input = {.boundary_reload = StoryRunPolicy::BoundaryReload::AT_PLAN_BOUNDARIES, .row = "01.01"}, .expectation = {.reloads = true}}, + {.name = "straight through, a when-chained row runs on", .input = {.boundary_reload = StoryRunPolicy::BoundaryReload::STRAIGHT_THROUGH, .row = "01.01"}, .expectation = {.reloads = false}}, + {.name = "straight through, an always row reloads", .input = {.boundary_reload = StoryRunPolicy::BoundaryReload::STRAIGHT_THROUGH, .row = "01.02"}, .expectation = {.reloads = true}}, + {.name = "a row with no reload runs on", .input = {.boundary_reload = StoryRunPolicy::BoundaryReload::AT_PLAN_BOUNDARIES, .row = "01.00"}, .expectation = {.reloads = false}}, +}; + +UnitTestResult check_reload(const ReloadCase& test){ + StoryRows rows; + rows.reload_when_chained = {"01.01", "01.02"}; + rows.reload_always = {"01.02"}; + const bool got = story_reloads_before(rows, test.input.boundary_reload, test.input.row); + if (got != test.expectation.reloads){ + return std::format("expected reloads {}, got {}", test.expectation.reloads, 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); + } + for (const ReloadCase& test : RELOAD_CASES){ + database.add>("reload", test, check_reload); + } +} + + + +} // 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..b1c0de7855 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.cpp @@ -0,0 +1,108 @@ +/* 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", "dev_only"}; + +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)); +} + +bool read_dev_only(const JsonObject& execution, std::string_view where){ + const JsonValue* dev_only = execution.get_value("dev_only"); + if (dev_only == nullptr){ + return false; + } + if (!is_true(*dev_only)){ + throw ParseException(std::format("{}: dev_only is true or left out", where)); + } + return true; +} + +} // 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), + .dev_only = read_dev_only(execution, where), + }; +} + +bool story_reloads_before(const StoryRows& rows, StoryRunPolicy::BoundaryReload boundary_reload, std::string_view id){ + if (rows.reload_always.contains(id)){ + return true; + } + return boundary_reload == StoryRunPolicy::BoundaryReload::AT_PLAN_BOUNDARIES && rows.reload_when_chained.contains(id); +} + + + +} // 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..fac9daeb07 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.h @@ -0,0 +1,113 @@ +/* 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, which a run reloads before, and + * which developer mode alone lists, 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 (StoryRunPolicy::BoundaryReload) + 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; + // "dev_only": true: a walk the story does not need, kept for testing + // a part of it (developer mode lists and plays it, a user's run does + // not). + bool dev_only = false; +}; + +// The shared fields of `execution`: "save", "reload_when_chained" and +// "dev_only", 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; + std::set> dev_only; + // The dev files that replaced a built-in checkpoint, as (file name, + // path) (Pokemon_StoryDevFiles.h). + std::vector> dev_files; +}; + +// 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; +}; + +// How a run plays its checkpoints: the attempts each gets, and whether it +// reloads at the plan's boundaries. +struct StoryRunPolicy{ + // Whether a run of several checkpoints reloads the save at a + // WHEN_CHAINED row (AT_PLAN_BOUNDARIES) or runs on from the state the + // row before left (STRAIGHT_THROUGH). ALWAYS rows reload either way, and + // a failed checkpoint's retries reload as usual. + enum class BoundaryReload{ + AT_PLAN_BOUNDARIES, + STRAIGHT_THROUGH, + }; + size_t attempts_per_checkpoint = 1; + BoundaryReload boundary_reload = BoundaryReload::AT_PLAN_BOUNDARIES; +}; + +// Whether a run reloads the save before row `id` of `rows` when it reaches +// it from the row before. +bool story_reloads_before(const StoryRows& rows, StoryRunPolicy::BoundaryReload boundary_reload, std::string_view id); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index ba2eb11a71..abff57ac72 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -12,6 +12,8 @@ #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_StoryEvents_Tests.h" #include "Pokemon_StoryFailureClasses_Tests.h" @@ -32,6 +34,8 @@ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_StoryEvents(database); add_tests_StoryStepExecutor(database); add_tests_StoryStepJson(database); + add_tests_AuthoredCheckpointJson(database); + add_tests_StoryFiles(database); add_tests_StoryRunTypes(database); } diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 5eee7b28ad..6f93fd0f12 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1452,6 +1452,17 @@ file(GLOB LIBRARY_SOURCES Source/NintendoSwitch/Programs/Typewriter/NintendoSwitch_TypewriterTextMapping.h Source/PanelLists.cpp Source/PanelLists.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_StoryDevFiles.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