diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryDevFiles.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryDevFiles.cpp new file mode 100644 index 0000000000..8da82c99d2 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryDevFiles.cpp @@ -0,0 +1,38 @@ +/* Story Dev Files + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Filesystem/FileIO.h" +#include "Common/Cpp/Filesystem/Filesystem.h" +#include "CommonFramework/GlobalAutoPaths.h" +#include "Pokemon_StoryDevFiles.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string story_dev_folder(std::string_view game){ + return std::format("{}AutoStoryDev/{}/", USER_FILE_PATH(), game); +} + +std::vector read_story_dev_files(std::string_view folder, std::string_view game){ + const Filesystem::Path directory(std::string{folder}); + std::vector files; + const std::string prefix = std::format("{}-", game); + for (const Filesystem::Path& path : Filesystem::list_directory(directory)){ + const std::string name = path.filename().string(); + if (!name.starts_with(prefix) || !name.ends_with(".plan.json") || !Filesystem::is_regular_file(path)){ + continue; + } + files.push_back({.name = name, .path = path.string(), .text = file_to_string(path.string())}); + } + return files; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation 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..fd572d6567 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryDevFiles.h @@ -0,0 +1,41 @@ +/* Story Dev Files + * + * From: https://github.com/PokemonAutomation/ + * + * For lab tuning: checkpoint files on disk that a run reads in place of + * the built-in ones of the same name (load_story_data() in + * Pokemon_StoryFiles.h), so a walk can be retimed without a rebuild. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryDevFiles_H +#define PokemonAutomation_Pokemon_StoryDevFiles_H + +#include +#include +#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; +}; + +// The folder whose checkpoint files replace `game`'s built-in ones: +// /AutoStoryDev// (USER_FILE_PATH()). +std::string story_dev_folder(std::string_view game); + +// The -*.plan.json files in `folder`, by name; none if it does not +// exist. +std::vector read_story_dev_files(std::string_view folder, std::string_view game); + + + +} // 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..cb1824b759 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.cpp @@ -0,0 +1,95 @@ +/* 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)); + } +} + +void add_story_row( + std::string_view id, const StoryRowExecution& execution, RowSave start, + std::optional previous_id, 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_id || !rows.autosaves.contains(*previous_id)){ + 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); + } + if (execution.autosave){ + rows.autosaves.emplace(id); + } + 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..7b423becd6 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles.h @@ -0,0 +1,222 @@ +/* Story Files + * + * From: https://github.com/PokemonAutomation/ + * + * A game's story read from its checkpoint files: the checked-in ones, + * built into the program (cmake/EmbedTextFiles.cmake), 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 +}; + +// Adds row `id` to the sets of `rows`. Throws ParseException naming +// `source` when it reloads and starts WITHOUT_SAVE or the row before it, +// `previous_id`, 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_id, 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. + for (auto& [row, source] : rows){ + const bool new_game = reader.starts_without_save && reader.starts_without_save(row.checkpoint); + detail::add_story_row( + row.checkpoint.id, row.execution, + new_game ? detail::RowSave::WITHOUT_SAVE : detail::RowSave::FROM_SAVE, + data.checkpoints.empty() ? std::nullopt : std::optional(data.checkpoints.back().id), + source, data + ); + 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..5ba2235da8 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryFiles_Tests.cpp @@ -0,0 +1,383 @@ +/* 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 | autosave 01.00 | 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 {} | chained {} | always {} | dev_only {} | dev {}", + joined(ids(data.checkpoints)), joined(titles), joined(data.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": "menu"})")}; + +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_MENU = {"test-01.10.plan", file_text("01.00b", R"({"save": "menu"})")}; + +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 | 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 | 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 | 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 = "a save other than autosave or menu fails", + .input = {.builtin = {{"test-01.00.plan", file_text("01.00", R"({"save": "card"})")}}}, + .expectation = {.error = "save is \"autosave\", \"menu\" 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", R"({"save": "menu"})")}, 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"}, + }, + { + .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 | 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_MENU}, .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 | 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 | 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..1175684067 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.cpp @@ -0,0 +1,105 @@ +/* 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(); +} + +bool read_autosave(const JsonObject& execution, std::string_view where){ + const JsonValue* save = execution.get_value("save"); + if (save == nullptr){ + return false; + } + const std::string* text = save->to_string(); + if (text == nullptr || (*text != "autosave" && *text != "menu")){ + throw ParseException(std::format("{}: save is \"autosave\", \"menu\" or left out", where)); + } + return *text == "autosave"; +} + +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{ + .autosave = read_autosave(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..d820f0b6a1 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryRowExecution.h @@ -0,0 +1,104 @@ +/* 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 are for lab runs only, 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 checkpoint file's shared execution fields say. +struct StoryRowExecution{ + // "save": "autosave": the game saves by itself at the row's end, so the + // program does not. "menu" or left out: the program saves, when the + // save policy lets it. + bool autosave = false; + StoryReload reload = StoryReload::NEVER; + // "dev_only": true: a lab walk the story does not need (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; + // 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/Engine/Pokemon_StoryActionNotImplemented.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionNotImplemented.cpp new file mode 100644 index 0000000000..d50dccd657 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionNotImplemented.cpp @@ -0,0 +1,21 @@ +/* Story Action Not Implemented + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryActionNotImplemented.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +StoryActionNotImplemented::StoryActionNotImplemented(std::string message) + : OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, std::move(message)) +{} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionNotImplemented.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionNotImplemented.h new file mode 100644 index 0000000000..566ade4269 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionNotImplemented.h @@ -0,0 +1,35 @@ +/* Story Action Not Implemented + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryActionNotImplemented_H +#define PokemonAutomation_Pokemon_StoryActionNotImplemented_H + +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A story action the game has no code for yet, thrown with what it waits +// for instead of pressing buttons blind. A game's backend lets it end the +// run instead of reloading and trying again, since every attempt would +// fail the same way. +class StoryActionNotImplemented : public OperationFailedException{ +public: + explicit StoryActionNotImplemented(std::string message); + + // code-health: allow char_pointer -- Exception::name() returns a const char pointer in the base class + virtual const char* name() const override{ + return "StoryActionNotImplemented"; + } +}; + + + +} // 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 9d9a1e62d3..d1ae2ba817 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -13,6 +13,7 @@ #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_StoryEnginePolicy_Tests.h" #include "Engine/Pokemon_StoryLaunch_Tests.h" @@ -55,6 +56,7 @@ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_StoryStepJson(database); add_tests_StoryActionArg(database); add_tests_AuthoredCheckpointJson(database); + add_tests_StoryFiles(database); add_tests_StorySavePolicy(database); add_tests_StoryEngine(database); add_tests_StoryEnginePolicy(database); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index c64cc92e1d..1bc9ca57dd 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1559,12 +1559,22 @@ file(GLOB LIBRARY_SOURCES 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.cpp + 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 Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h Source/Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.cpp Source/Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.h + Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionNotImplemented.cpp + Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionNotImplemented.h Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.cpp Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.h Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend.cpp