From 99f60e08549e0ce7ed9a1c8353fa90864ffa94f7 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 14 Nov 2026 23:18:33 -0800 Subject: [PATCH 1/8] AutoStory: CheckpointId value type and segment-start check CheckpointId parses "SS.CC" ids like "03.08" (exactly two digits, a dot, two digits), prints them back, orders them, and starts_segment() tells a caller when a run enters a new segment so it can count Segments Started. --- .../ComputerPrograms_UnitTestRunner.cpp | 2 + .../AutoStory/Pokemon_CheckpointId.cpp | 62 +++++ .../Pokemon/AutoStory/Pokemon_CheckpointId.h | 48 ++++ .../AutoStory/Pokemon_CheckpointId_Tests.cpp | 260 ++++++++++++++++++ .../AutoStory/Pokemon_CheckpointId_Tests.h | 23 ++ SerialPrograms/cmake/SourceFiles.cmake | 4 + 6 files changed, 399 insertions(+) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.h diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index c6c3e6b052..9ead73d4c0 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -16,6 +16,7 @@ #include "Common/Qt/QtThreadPool_Tests.h" #include "Kernels/Kernels_Tests.h" #include "Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h" +#include "Pokemon/AutoStory/Pokemon_CheckpointId_Tests.h" #include "Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.h" #include "CommonFramework/AudioPipeline/AudioInfo_Tests.h" #include "CommonFramework/AudioPipeline/Tools/ChannelMixer.h" @@ -78,6 +79,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Kernels::add_tests(ret); Pokemon::add_tests_AutoStorySelect(ret); Pokemon::add_tests_AutoStoryStats(ret); + Pokemon::add_tests_CheckpointId(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); NintendoSwitch::add_tests_UpdatePopupDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp new file mode 100644 index 0000000000..6bb35dedae --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp @@ -0,0 +1,62 @@ +/* AutoStory Checkpoint Id + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_CheckpointId.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +// The value of two decimal digits, or nullopt if either is not a digit. +std::optional parse_two_digits(std::string_view text){ + if (text.size() != 2){ + return std::nullopt; + } + uint8_t value = 0; + for (char c : text){ + if (c < '0' || c > '9'){ + return std::nullopt; + } + value = (uint8_t)(value * 10 + (c - '0')); + } + return value; +} + +} // namespace + + + +std::optional CheckpointId::parse(std::string_view text){ + if (text.size() != 5 || text[2] != '.'){ + return std::nullopt; + } + std::optional segment = parse_two_digits(text.substr(0, 2)); + std::optional checkpoint = parse_two_digits(text.substr(3, 2)); + if (!segment || !checkpoint){ + return std::nullopt; + } + return CheckpointId{*segment, *checkpoint}; +} + +std::string CheckpointId::to_string() const{ + return std::format("{:02}.{:02}", segment, checkpoint); +} + +std::string CheckpointId::segment_string() const{ + return std::format("{:02}", segment); +} + + +bool starts_segment(std::optional previous, CheckpointId next){ + return !previous || previous->segment != next.segment; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.h new file mode 100644 index 0000000000..67ffb07c12 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.h @@ -0,0 +1,48 @@ +/* AutoStory Checkpoint Id + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_CheckpointId_H +#define PokemonAutomation_Pokemon_CheckpointId_H + +#include +#include +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// An AutoStory checkpoint, written "SS.CC": segment 03, checkpoint 08 is +// "03.08". Ids order by segment, then by checkpoint. +struct CheckpointId{ + uint8_t segment; + uint8_t checkpoint; + + // Reads exactly two digits, a dot and two digits. Anything else + // ("3.08", "03.08b", "03-08", "03.08.01") returns nullopt. + static std::optional parse(std::string_view text); + + // "03.08". + std::string to_string() const; + // "03". + std::string segment_string() const; + + auto operator<=>(const CheckpointId&) const = default; +}; + + +// Whether reaching `next` starts a segment: true for the first checkpoint of +// a run (`previous` is nullopt) and when the segment differs from the last +// checkpoint's. A caller adds one to AutoStoryStats::m_segments_started then. +bool starts_segment(std::optional previous, CheckpointId next); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp new file mode 100644 index 0000000000..dd2a3fe601 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp @@ -0,0 +1,260 @@ +/* AutoStory Checkpoint Id Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include "Pokemon_CheckpointId.h" +#include "Pokemon_CheckpointId_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + + +// Parse: text in, the id printed back out (nullopt when parse rejects it). + +struct ParseInput{ + std::string text; +}; + +struct ParseExpectation{ + std::optional id; + std::optional segment; +}; + +struct ParseScenario{ + std::string name; + ParseInput input; + ParseExpectation expectation; +}; + +class Test_CheckpointIdParse : public UnitTest{ +public: + Test_CheckpointIdParse(ParseScenario scenario) + : UnitTest(std::format("Pokemon::CheckpointId::parse - {}", scenario.name)) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::optional got = CheckpointId::parse(m_scenario.input.text); + const ParseExpectation& expected = m_scenario.expectation; + if (!expected.id){ + if (got){ + return std::format("Expected \"{}\" to be rejected, got {}", m_scenario.input.text, got->to_string()); + } + return true; + } + if (!got){ + return std::format("Expected \"{}\" to parse, it was rejected", m_scenario.input.text); + } + if (got->to_string() != *expected.id){ + return std::format("Expected id {}, got {}", *expected.id, got->to_string()); + } + if (got->segment_string() != *expected.segment){ + return std::format("Expected segment {}, got {}", *expected.segment, got->segment_string()); + } + return true; + } + +private: + const ParseScenario m_scenario; +}; + + +// Ordering: two ids, how the first compares to the second. + +struct OrderInput{ + CheckpointId left; + CheckpointId right; +}; + +struct OrderExpectation{ + std::strong_ordering order; +}; + +struct OrderScenario{ + std::string name; + OrderInput input; + OrderExpectation expectation; +}; + +const char* order_name(std::strong_ordering order){ + if (order < 0){ + return "less"; + } + if (order > 0){ + return "greater"; + } + return "equal"; +} + +class Test_CheckpointIdOrder : public UnitTest{ +public: + Test_CheckpointIdOrder(OrderScenario scenario) + : UnitTest(std::format("Pokemon::CheckpointId order - {}", scenario.name)) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::strong_ordering got = m_scenario.input.left <=> m_scenario.input.right; + if (got != m_scenario.expectation.order){ + return std::format( + "Expected {} to be {} than {}, got {}", + m_scenario.input.left.to_string(), + order_name(m_scenario.expectation.order), + m_scenario.input.right.to_string(), + order_name(got) + ); + } + return true; + } + +private: + const OrderScenario m_scenario; +}; + + +// Segment starts: the checkpoints a run passes, in order, and the ones that +// start a segment. + +struct SegmentStartInput{ + std::vector passed; +}; + +struct SegmentStartExpectation{ + std::vector starts; +}; + +struct SegmentStartScenario{ + std::string name; + SegmentStartInput input; + SegmentStartExpectation expectation; +}; + +std::string join(const std::vector& ids){ + std::string ret; + for (const std::string& id : ids){ + if (!ret.empty()){ + ret += ", "; + } + ret += id; + } + return ret; +} + +class Test_CheckpointIdSegmentStart : public UnitTest{ +public: + Test_CheckpointIdSegmentStart(SegmentStartScenario scenario) + : UnitTest(std::format("Pokemon::CheckpointId starts_segment - {}", scenario.name)) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + std::vector got; + std::optional previous; + for (CheckpointId next : m_scenario.input.passed){ + if (starts_segment(previous, next)){ + got.emplace_back(next.to_string()); + } + previous = next; + } + if (got != m_scenario.expectation.starts){ + return std::format( + "Expected segment starts [{}], got [{}]", + join(m_scenario.expectation.starts), join(got) + ); + } + return true; + } + +private: + const SegmentStartScenario m_scenario; +}; + + +} // namespace + + + +void add_tests_CheckpointId(UnitTestDatabase& database){ + const std::vector parse_cases{ + {.name = "segment and checkpoint", .input = {.text = "03.08"}, .expectation = {.id = "03.08", .segment = "03"}}, + {.name = "first checkpoint", .input = {.text = "00.00"}, .expectation = {.id = "00.00", .segment = "00"}}, + {.name = "largest id", .input = {.text = "99.99"}, .expectation = {.id = "99.99", .segment = "99"}}, + {.name = "letter suffix", .input = {.text = "03.08b"}}, + {.name = "one-digit segment", .input = {.text = "3.08"}}, + {.name = "one-digit checkpoint", .input = {.text = "03.8"}}, + {.name = "three-digit segment", .input = {.text = "100.08"}}, + {.name = "three-digit checkpoint", .input = {.text = "03.100"}}, + {.name = "no dot", .input = {.text = "0308"}}, + {.name = "other separator", .input = {.text = "03-08"}}, + {.name = "extra part", .input = {.text = "03.08.01"}}, + {.name = "segment only", .input = {.text = "03"}}, + {.name = "sign", .input = {.text = "+3.08"}}, + {.name = "spaces", .input = {.text = " 3.08"}}, + {.name = "empty", .input = {.text = ""}}, + }; + for (const ParseScenario& scenario : parse_cases){ + database.add(scenario); + } + + const std::vector order_cases{ + { + .name = "same id", + .input = {.left = {3, 8}, .right = {3, 8}}, + .expectation = {.order = std::strong_ordering::equal}, + }, + { + .name = "later checkpoint in the same segment", + .input = {.left = {3, 9}, .right = {3, 8}}, + .expectation = {.order = std::strong_ordering::greater}, + }, + { + .name = "segment wins over checkpoint", + .input = {.left = {2, 99}, .right = {3, 0}}, + .expectation = {.order = std::strong_ordering::less}, + }, + }; + for (const OrderScenario& scenario : order_cases){ + database.add(scenario); + } + + const std::vector segment_cases{ + { + .name = "first checkpoint of a run starts its segment", + .input = {.passed = {{3, 8}}}, + .expectation = {.starts = {"03.08"}}, + }, + { + .name = "checkpoints in one segment start it once", + .input = {.passed = {{3, 8}, {3, 9}, {3, 10}}}, + .expectation = {.starts = {"03.08"}}, + }, + { + .name = "each new segment starts once", + .input = {.passed = {{2, 4}, {2, 5}, {3, 0}, {3, 1}, {4, 0}}}, + .expectation = {.starts = {"02.04", "03.00", "04.00"}}, + }, + { + .name = "empty run starts nothing", + .input = {.passed = {}}, + .expectation = {.starts = {}}, + }, + }; + for (const SegmentStartScenario& scenario : segment_cases){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.h new file mode 100644 index 0000000000..37212aa763 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.h @@ -0,0 +1,23 @@ +/* AutoStory Checkpoint Id Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_CheckpointId_Tests_H +#define PokemonAutomation_Pokemon_CheckpointId_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers the tests for parsing, printing and ordering checkpoint ids. +void add_tests_CheckpointId(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index b2df0b557f..3c546cb9f6 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1483,6 +1483,10 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_AutoStorySelect.h Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.cpp Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h + Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp + Source/Pokemon/AutoStory/Pokemon_CheckpointId.h + Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.h From 99cdd6d0bfc4d9cb04a50527d680a1b0c9e195bf Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 14 Nov 2026 23:18:54 -0800 Subject: [PATCH 2/8] CheckpointId tests: split registration, full case rows --- .../AutoStory/Pokemon_CheckpointId_Tests.cpp | 54 +++++++++++-------- 1 file changed, 33 insertions(+), 21 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp index dd2a3fe601..a9a100f3cc 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include "Pokemon_CheckpointId.h" @@ -86,7 +87,7 @@ struct OrderScenario{ OrderExpectation expectation; }; -const char* order_name(std::strong_ordering order){ +std::string_view order_name(std::strong_ordering order){ if (order < 0){ return "less"; } @@ -180,32 +181,30 @@ class Test_CheckpointIdSegmentStart : public UnitTest{ }; -} // namespace - - - -void add_tests_CheckpointId(UnitTestDatabase& database){ +void add_parse_tests(UnitTestDatabase& database){ const std::vector parse_cases{ - {.name = "segment and checkpoint", .input = {.text = "03.08"}, .expectation = {.id = "03.08", .segment = "03"}}, - {.name = "first checkpoint", .input = {.text = "00.00"}, .expectation = {.id = "00.00", .segment = "00"}}, - {.name = "largest id", .input = {.text = "99.99"}, .expectation = {.id = "99.99", .segment = "99"}}, - {.name = "letter suffix", .input = {.text = "03.08b"}}, - {.name = "one-digit segment", .input = {.text = "3.08"}}, - {.name = "one-digit checkpoint", .input = {.text = "03.8"}}, - {.name = "three-digit segment", .input = {.text = "100.08"}}, - {.name = "three-digit checkpoint", .input = {.text = "03.100"}}, - {.name = "no dot", .input = {.text = "0308"}}, - {.name = "other separator", .input = {.text = "03-08"}}, - {.name = "extra part", .input = {.text = "03.08.01"}}, - {.name = "segment only", .input = {.text = "03"}}, - {.name = "sign", .input = {.text = "+3.08"}}, - {.name = "spaces", .input = {.text = " 3.08"}}, - {.name = "empty", .input = {.text = ""}}, + {.name = "segment and checkpoint", .input = {.text = "03.08"}, .expectation = {.id = "03.08", .segment = "03"}}, + {.name = "first checkpoint", .input = {.text = "00.00"}, .expectation = {.id = "00.00", .segment = "00"}}, + {.name = "largest id", .input = {.text = "99.99"}, .expectation = {.id = "99.99", .segment = "99"}}, + {.name = "letter suffix", .input = {.text = "03.08b"}, .expectation = {}}, + {.name = "one-digit segment", .input = {.text = "3.08"}, .expectation = {}}, + {.name = "one-digit checkpoint", .input = {.text = "03.8"}, .expectation = {}}, + {.name = "three-digit segment", .input = {.text = "100.08"}, .expectation = {}}, + {.name = "three-digit checkpoint", .input = {.text = "03.100"}, .expectation = {}}, + {.name = "no dot", .input = {.text = "0308"}, .expectation = {}}, + {.name = "other separator", .input = {.text = "03-08"}, .expectation = {}}, + {.name = "extra part", .input = {.text = "03.08.01"}, .expectation = {}}, + {.name = "segment only", .input = {.text = "03"}, .expectation = {}}, + {.name = "sign", .input = {.text = "+3.08"}, .expectation = {}}, + {.name = "spaces", .input = {.text = " 3.08"}, .expectation = {}}, + {.name = "empty", .input = {.text = ""}, .expectation = {}}, }; for (const ParseScenario& scenario : parse_cases){ database.add(scenario); } +} +void add_order_tests(UnitTestDatabase& database){ const std::vector order_cases{ { .name = "same id", @@ -226,7 +225,9 @@ void add_tests_CheckpointId(UnitTestDatabase& database){ for (const OrderScenario& scenario : order_cases){ database.add(scenario); } +} +void add_segment_start_tests(UnitTestDatabase& database){ const std::vector segment_cases{ { .name = "first checkpoint of a run starts its segment", @@ -255,6 +256,17 @@ void add_tests_CheckpointId(UnitTestDatabase& database){ } +} // namespace + + + +void add_tests_CheckpointId(UnitTestDatabase& database){ + add_parse_tests(database); + add_order_tests(database); + add_segment_start_tests(database); +} + + } // namespace Pokemon } // namespace PokemonAutomation From 51b07e89fd1d8563a39a4e29b77c0b2128cdac00 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 14 Nov 2026 23:19:11 -0800 Subject: [PATCH 3/8] CheckpointId tests: segment runs as id strings --- .../AutoStory/Pokemon_CheckpointId_Tests.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp index a9a100f3cc..b1eade625f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp @@ -127,7 +127,7 @@ class Test_CheckpointIdOrder : public UnitTest{ // start a segment. struct SegmentStartInput{ - std::vector passed; + std::vector passed; }; struct SegmentStartExpectation{ @@ -161,9 +161,13 @@ class Test_CheckpointIdSegmentStart : public UnitTest{ virtual UnitTestResult run(Logger&, CancellableScope&) const override{ std::vector got; std::optional previous; - for (CheckpointId next : m_scenario.input.passed){ - if (starts_segment(previous, next)){ - got.emplace_back(next.to_string()); + for (const std::string& text : m_scenario.input.passed){ + const std::optional next = CheckpointId::parse(text); + if (!next){ + return std::format("Bad checkpoint id \"{}\" in the test input", text); + } + if (starts_segment(previous, *next)){ + got.emplace_back(next->to_string()); } previous = next; } @@ -231,17 +235,17 @@ void add_segment_start_tests(UnitTestDatabase& database){ const std::vector segment_cases{ { .name = "first checkpoint of a run starts its segment", - .input = {.passed = {{3, 8}}}, + .input = {.passed = {"03.08"}}, .expectation = {.starts = {"03.08"}}, }, { .name = "checkpoints in one segment start it once", - .input = {.passed = {{3, 8}, {3, 9}, {3, 10}}}, + .input = {.passed = {"03.08", "03.09", "03.10"}}, .expectation = {.starts = {"03.08"}}, }, { .name = "each new segment starts once", - .input = {.passed = {{2, 4}, {2, 5}, {3, 0}, {3, 1}, {4, 0}}}, + .input = {.passed = {"02.04", "02.05", "03.00", "03.01", "04.00"}}, .expectation = {.starts = {"02.04", "03.00", "04.00"}}, }, { From 6d5cfa409aaf652d0db857deb9183b3a53c9de39 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 14 Nov 2026 23:22:07 -0800 Subject: [PATCH 4/8] CheckpointId: allow one optional lowercase letter suffix FRLG splits boss battles out of a checkpoint without renumbering the ones after it (00.12b, 12.02b). The suffix sorts after the bare id and before the next checkpoint; starts_segment ignores it. --- .../AutoStory/Pokemon_CheckpointId.cpp | 17 +++++-- .../Pokemon/AutoStory/Pokemon_CheckpointId.h | 18 +++++--- .../AutoStory/Pokemon_CheckpointId_Tests.cpp | 46 +++++++++++++++++-- 3 files changed, 68 insertions(+), 13 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp index 6bb35dedae..38a7f2491f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp @@ -32,7 +32,7 @@ std::optional parse_two_digits(std::string_view text){ std::optional CheckpointId::parse(std::string_view text){ - if (text.size() != 5 || text[2] != '.'){ + if ((text.size() != 5 && text.size() != 6) || text[2] != '.'){ return std::nullopt; } std::optional segment = parse_two_digits(text.substr(0, 2)); @@ -40,11 +40,22 @@ std::optional CheckpointId::parse(std::string_view text){ if (!segment || !checkpoint){ return std::nullopt; } - return CheckpointId{*segment, *checkpoint}; + char suffix = '\0'; + if (text.size() == 6){ + suffix = text[5]; + if (suffix < 'a' || suffix > 'z'){ + return std::nullopt; + } + } + return CheckpointId{*segment, *checkpoint, suffix}; } std::string CheckpointId::to_string() const{ - return std::format("{:02}.{:02}", segment, checkpoint); + std::string ret = std::format("{:02}.{:02}", segment, checkpoint); + if (suffix != '\0'){ + ret += suffix; + } + return ret; } std::string CheckpointId::segment_string() const{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.h index 67ffb07c12..16fca4c994 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.h @@ -17,17 +17,23 @@ namespace PokemonAutomation{ namespace Pokemon{ -// An AutoStory checkpoint, written "SS.CC": segment 03, checkpoint 08 is -// "03.08". Ids order by segment, then by checkpoint. +// An AutoStory checkpoint, written "SS.CC" with an optional lowercase +// letter: segment 03, checkpoint 08 is "03.08". A letter splits a checkpoint +// without renumbering the ones after it, e.g. FRLG's "12.02b" for a boss +// battle cut out of 12.02. Ids order by segment, then checkpoint, then +// letter: 12.02 < 12.02b < 12.02c < 12.03. struct CheckpointId{ uint8_t segment; uint8_t checkpoint; + // 'a' to 'z', or '\0' for none. + char suffix = '\0'; - // Reads exactly two digits, a dot and two digits. Anything else - // ("3.08", "03.08b", "03-08", "03.08.01") returns nullopt. + // Reads two digits, a dot, two digits and at most one lowercase letter. + // Anything else ("3.08", "03.08B", "03.08bc", "03.08b1", "03-08", + // "03.08.01") returns nullopt. static std::optional parse(std::string_view text); - // "03.08". + // "03.08", or "03.08b" with a suffix. std::string to_string() const; // "03". std::string segment_string() const; @@ -38,7 +44,7 @@ struct CheckpointId{ // Whether reaching `next` starts a segment: true for the first checkpoint of // a run (`previous` is nullopt) and when the segment differs from the last -// checkpoint's. A caller adds one to AutoStoryStats::m_segments_started then. +// checkpoint's. The suffix does not matter. A caller adds one to AutoStoryStats::m_segments_started then. bool starts_segment(std::optional previous, CheckpointId next); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp index b1eade625f..ec2f9ed0b6 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp @@ -190,7 +190,15 @@ void add_parse_tests(UnitTestDatabase& database){ {.name = "segment and checkpoint", .input = {.text = "03.08"}, .expectation = {.id = "03.08", .segment = "03"}}, {.name = "first checkpoint", .input = {.text = "00.00"}, .expectation = {.id = "00.00", .segment = "00"}}, {.name = "largest id", .input = {.text = "99.99"}, .expectation = {.id = "99.99", .segment = "99"}}, - {.name = "letter suffix", .input = {.text = "03.08b"}, .expectation = {}}, + {.name = "letter suffix", .input = {.text = "12.02b"}, .expectation = {.id = "12.02b", .segment = "12"}}, + {.name = "first letter", .input = {.text = "00.12a"}, .expectation = {.id = "00.12a", .segment = "00"}}, + {.name = "last letter", .input = {.text = "03.08z"}, .expectation = {.id = "03.08z", .segment = "03"}}, + {.name = "uppercase letter", .input = {.text = "03.08B"}, .expectation = {}}, + {.name = "two letters", .input = {.text = "03.08bc"}, .expectation = {}}, + {.name = "digit after the letter", .input = {.text = "03.08b1"}, .expectation = {}}, + {.name = "third checkpoint digit", .input = {.text = "03.081"}, .expectation = {}}, + {.name = "punctuation suffix", .input = {.text = "03.08!"}, .expectation = {}}, + {.name = "letter in the segment", .input = {.text = "0b.08"}, .expectation = {}}, {.name = "one-digit segment", .input = {.text = "3.08"}, .expectation = {}}, {.name = "one-digit checkpoint", .input = {.text = "03.8"}, .expectation = {}}, {.name = "three-digit segment", .input = {.text = "100.08"}, .expectation = {}}, @@ -212,19 +220,39 @@ void add_order_tests(UnitTestDatabase& database){ const std::vector order_cases{ { .name = "same id", - .input = {.left = {3, 8}, .right = {3, 8}}, + .input = {.left = {3, 8, '\0'}, .right = {3, 8, '\0'}}, .expectation = {.order = std::strong_ordering::equal}, }, { .name = "later checkpoint in the same segment", - .input = {.left = {3, 9}, .right = {3, 8}}, + .input = {.left = {3, 9, '\0'}, .right = {3, 8, '\0'}}, .expectation = {.order = std::strong_ordering::greater}, }, { .name = "segment wins over checkpoint", - .input = {.left = {2, 99}, .right = {3, 0}}, + .input = {.left = {2, 99, '\0'}, .right = {3, 0, '\0'}}, .expectation = {.order = std::strong_ordering::less}, }, + { + .name = "no suffix before a suffix", + .input = {.left = {12, 2, '\0'}, .right = {12, 2, 'b'}}, + .expectation = {.order = std::strong_ordering::less}, + }, + { + .name = "suffixes in letter order", + .input = {.left = {12, 2, 'b'}, .right = {12, 2, 'c'}}, + .expectation = {.order = std::strong_ordering::less}, + }, + { + .name = "suffix before the next checkpoint", + .input = {.left = {12, 2, 'c'}, .right = {12, 3, '\0'}}, + .expectation = {.order = std::strong_ordering::less}, + }, + { + .name = "same suffix", + .input = {.left = {12, 2, 'b'}, .right = {12, 2, 'b'}}, + .expectation = {.order = std::strong_ordering::equal}, + }, }; for (const OrderScenario& scenario : order_cases){ database.add(scenario); @@ -248,6 +276,16 @@ void add_segment_start_tests(UnitTestDatabase& database){ .input = {.passed = {"02.04", "02.05", "03.00", "03.01", "04.00"}}, .expectation = {.starts = {"02.04", "03.00", "04.00"}}, }, + { + .name = "suffix does not start a segment", + .input = {.passed = {"12.01", "12.02", "12.02b", "12.03"}}, + .expectation = {.starts = {"12.01"}}, + }, + { + .name = "suffixed checkpoint can start a segment", + .input = {.passed = {"00.12", "00.12b", "01.00"}}, + .expectation = {.starts = {"00.12", "01.00"}}, + }, { .name = "empty run starts nothing", .input = {.passed = {}}, From 6a78529a22f35bb001da27b434db4129c049c849 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 14 Nov 2026 23:28:25 -0800 Subject: [PATCH 5/8] CheckpointId: optional suffix, private fields built only by parse() suffix is std::optional instead of a '\0' sentinel, the fields have defaults and are private behind accessors, so parse() is the only way to build an id. Order tests take ids as text. The parse test expects one optional. Sorted the CMake list and the test-runner include; shortened the starts_segment comment. --- .../ComputerPrograms_UnitTestRunner.cpp | 2 +- .../AutoStory/Pokemon_CheckpointId.cpp | 17 ++--- .../Pokemon/AutoStory/Pokemon_CheckpointId.h | 29 ++++++--- .../AutoStory/Pokemon_CheckpointId_Tests.cpp | 62 +++++++++++-------- SerialPrograms/cmake/SourceFiles.cmake | 6 +- 5 files changed, 71 insertions(+), 45 deletions(-) diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 9ead73d4c0..cfc9664f24 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -16,8 +16,8 @@ #include "Common/Qt/QtThreadPool_Tests.h" #include "Kernels/Kernels_Tests.h" #include "Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h" -#include "Pokemon/AutoStory/Pokemon_CheckpointId_Tests.h" #include "Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.h" +#include "Pokemon/AutoStory/Pokemon_CheckpointId_Tests.h" #include "CommonFramework/AudioPipeline/AudioInfo_Tests.h" #include "CommonFramework/AudioPipeline/Tools/ChannelMixer.h" #include "CommonFramework/AudioPipeline/SinkPipeline_Tests.h" diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp index 38a7f2491f..432f32333c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp @@ -40,31 +40,32 @@ std::optional CheckpointId::parse(std::string_view text){ if (!segment || !checkpoint){ return std::nullopt; } - char suffix = '\0'; + std::optional suffix; if (text.size() == 6){ - suffix = text[5]; - if (suffix < 'a' || suffix > 'z'){ + const char letter = text[5]; + if (letter < 'a' || letter > 'z'){ return std::nullopt; } + suffix = letter; } return CheckpointId{*segment, *checkpoint, suffix}; } std::string CheckpointId::to_string() const{ - std::string ret = std::format("{:02}.{:02}", segment, checkpoint); - if (suffix != '\0'){ - ret += suffix; + std::string ret = std::format("{:02}.{:02}", m_segment, m_checkpoint); + if (m_suffix){ + ret += *m_suffix; } return ret; } std::string CheckpointId::segment_string() const{ - return std::format("{:02}", segment); + return std::format("{:02}", m_segment); } bool starts_segment(std::optional previous, CheckpointId next){ - return !previous || previous->segment != next.segment; + return !previous || previous->segment() != next.segment(); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.h index 16fca4c994..7e5001266e 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.h @@ -21,13 +21,10 @@ namespace Pokemon{ // letter: segment 03, checkpoint 08 is "03.08". A letter splits a checkpoint // without renumbering the ones after it, e.g. FRLG's "12.02b" for a boss // battle cut out of 12.02. Ids order by segment, then checkpoint, then -// letter: 12.02 < 12.02b < 12.02c < 12.03. -struct CheckpointId{ - uint8_t segment; - uint8_t checkpoint; - // 'a' to 'z', or '\0' for none. - char suffix = '\0'; - +// letter: 12.02 < 12.02b < 12.02c < 12.03. parse() is the only way to build +// one, so every id is valid. +class CheckpointId{ +public: // Reads two digits, a dot, two digits and at most one lowercase letter. // Anything else ("3.08", "03.08B", "03.08bc", "03.08b1", "03-08", // "03.08.01") returns nullopt. @@ -38,13 +35,29 @@ struct CheckpointId{ // "03". std::string segment_string() const; + uint8_t segment() const{ return m_segment; } + uint8_t checkpoint() const{ return m_checkpoint; } + // 'a' to 'z'. + std::optional suffix() const{ return m_suffix; } + auto operator<=>(const CheckpointId&) const = default; + +private: + CheckpointId(uint8_t segment, uint8_t checkpoint, std::optional suffix) + : m_segment(segment) + , m_checkpoint(checkpoint) + , m_suffix(suffix) + {} + + uint8_t m_segment = 0; + uint8_t m_checkpoint = 0; + std::optional m_suffix; }; // Whether reaching `next` starts a segment: true for the first checkpoint of // a run (`previous` is nullopt) and when the segment differs from the last -// checkpoint's. The suffix does not matter. A caller adds one to AutoStoryStats::m_segments_started then. +// checkpoint's. The suffix does not matter. bool starts_segment(std::optional previous, CheckpointId next); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp index ec2f9ed0b6..9a507d7234 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp @@ -26,9 +26,13 @@ struct ParseInput{ std::string text; }; +struct ParsedId{ + std::string id; + std::string segment; +}; + struct ParseExpectation{ - std::optional id; - std::optional segment; + std::optional parsed; }; struct ParseScenario{ @@ -47,7 +51,7 @@ class Test_CheckpointIdParse : public UnitTest{ virtual UnitTestResult run(Logger&, CancellableScope&) const override{ const std::optional got = CheckpointId::parse(m_scenario.input.text); const ParseExpectation& expected = m_scenario.expectation; - if (!expected.id){ + if (!expected.parsed){ if (got){ return std::format("Expected \"{}\" to be rejected, got {}", m_scenario.input.text, got->to_string()); } @@ -56,11 +60,11 @@ class Test_CheckpointIdParse : public UnitTest{ if (!got){ return std::format("Expected \"{}\" to parse, it was rejected", m_scenario.input.text); } - if (got->to_string() != *expected.id){ - return std::format("Expected id {}, got {}", *expected.id, got->to_string()); + if (got->to_string() != expected.parsed->id){ + return std::format("Expected id {}, got {}", expected.parsed->id, got->to_string()); } - if (got->segment_string() != *expected.segment){ - return std::format("Expected segment {}, got {}", *expected.segment, got->segment_string()); + if (got->segment_string() != expected.parsed->segment){ + return std::format("Expected segment {}, got {}", expected.parsed->segment, got->segment_string()); } return true; } @@ -73,8 +77,8 @@ class Test_CheckpointIdParse : public UnitTest{ // Ordering: two ids, how the first compares to the second. struct OrderInput{ - CheckpointId left; - CheckpointId right; + std::string left; + std::string right; }; struct OrderExpectation{ @@ -105,13 +109,21 @@ class Test_CheckpointIdOrder : public UnitTest{ {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const std::strong_ordering got = m_scenario.input.left <=> m_scenario.input.right; + const std::optional left = CheckpointId::parse(m_scenario.input.left); + const std::optional right = CheckpointId::parse(m_scenario.input.right); + if (!left || !right){ + return std::format( + "Bad checkpoint id \"{}\" or \"{}\" in the test input", + m_scenario.input.left, m_scenario.input.right + ); + } + const std::strong_ordering got = *left <=> *right; if (got != m_scenario.expectation.order){ return std::format( "Expected {} to be {} than {}, got {}", - m_scenario.input.left.to_string(), + m_scenario.input.left, order_name(m_scenario.expectation.order), - m_scenario.input.right.to_string(), + m_scenario.input.right, order_name(got) ); } @@ -187,12 +199,12 @@ class Test_CheckpointIdSegmentStart : public UnitTest{ void add_parse_tests(UnitTestDatabase& database){ const std::vector parse_cases{ - {.name = "segment and checkpoint", .input = {.text = "03.08"}, .expectation = {.id = "03.08", .segment = "03"}}, - {.name = "first checkpoint", .input = {.text = "00.00"}, .expectation = {.id = "00.00", .segment = "00"}}, - {.name = "largest id", .input = {.text = "99.99"}, .expectation = {.id = "99.99", .segment = "99"}}, - {.name = "letter suffix", .input = {.text = "12.02b"}, .expectation = {.id = "12.02b", .segment = "12"}}, - {.name = "first letter", .input = {.text = "00.12a"}, .expectation = {.id = "00.12a", .segment = "00"}}, - {.name = "last letter", .input = {.text = "03.08z"}, .expectation = {.id = "03.08z", .segment = "03"}}, + {.name = "segment and checkpoint", .input = {.text = "03.08"}, .expectation = {.parsed = ParsedId{.id = "03.08", .segment = "03"}}}, + {.name = "first checkpoint", .input = {.text = "00.00"}, .expectation = {.parsed = ParsedId{.id = "00.00", .segment = "00"}}}, + {.name = "largest id", .input = {.text = "99.99"}, .expectation = {.parsed = ParsedId{.id = "99.99", .segment = "99"}}}, + {.name = "letter suffix", .input = {.text = "12.02b"}, .expectation = {.parsed = ParsedId{.id = "12.02b", .segment = "12"}}}, + {.name = "first letter", .input = {.text = "00.12a"}, .expectation = {.parsed = ParsedId{.id = "00.12a", .segment = "00"}}}, + {.name = "last letter", .input = {.text = "03.08z"}, .expectation = {.parsed = ParsedId{.id = "03.08z", .segment = "03"}}}, {.name = "uppercase letter", .input = {.text = "03.08B"}, .expectation = {}}, {.name = "two letters", .input = {.text = "03.08bc"}, .expectation = {}}, {.name = "digit after the letter", .input = {.text = "03.08b1"}, .expectation = {}}, @@ -220,37 +232,37 @@ void add_order_tests(UnitTestDatabase& database){ const std::vector order_cases{ { .name = "same id", - .input = {.left = {3, 8, '\0'}, .right = {3, 8, '\0'}}, + .input = {.left = "03.08", .right = "03.08"}, .expectation = {.order = std::strong_ordering::equal}, }, { .name = "later checkpoint in the same segment", - .input = {.left = {3, 9, '\0'}, .right = {3, 8, '\0'}}, + .input = {.left = "03.09", .right = "03.08"}, .expectation = {.order = std::strong_ordering::greater}, }, { .name = "segment wins over checkpoint", - .input = {.left = {2, 99, '\0'}, .right = {3, 0, '\0'}}, + .input = {.left = "02.99", .right = "03.00"}, .expectation = {.order = std::strong_ordering::less}, }, { .name = "no suffix before a suffix", - .input = {.left = {12, 2, '\0'}, .right = {12, 2, 'b'}}, + .input = {.left = "12.02", .right = "12.02b"}, .expectation = {.order = std::strong_ordering::less}, }, { .name = "suffixes in letter order", - .input = {.left = {12, 2, 'b'}, .right = {12, 2, 'c'}}, + .input = {.left = "12.02b", .right = "12.02c"}, .expectation = {.order = std::strong_ordering::less}, }, { .name = "suffix before the next checkpoint", - .input = {.left = {12, 2, 'c'}, .right = {12, 3, '\0'}}, + .input = {.left = "12.02c", .right = "12.03"}, .expectation = {.order = std::strong_ordering::less}, }, { .name = "same suffix", - .input = {.left = {12, 2, 'b'}, .right = {12, 2, 'b'}}, + .input = {.left = "12.02b", .right = "12.02b"}, .expectation = {.order = std::strong_ordering::equal}, }, }; diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 3c546cb9f6..f534e8dd22 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1483,13 +1483,13 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_AutoStorySelect.h Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.cpp Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h + Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.h + Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.h Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp Source/Pokemon/AutoStory/Pokemon_CheckpointId.h Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.h - Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.h - Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp - Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.h Source/Pokemon/Pokemon_AdvRng.cpp Source/Pokemon/Pokemon_AdvRng.h Source/Pokemon/Pokemon_BdspRng.cpp From bcf32d4447b3cf7cc42365c884e92693bb108232 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 14 Nov 2026 23:39:05 -0800 Subject: [PATCH 6/8] AutoStory: screen events and story step types CommonTools/ScreenEvents (what the screen is doing, since when) and the shared story vocabulary every AutoStory engine game builds on: the step types, the step executor, story events, the step JSON reader, the story log and the shared failure classes. Cut from plza/fault-sweep with only what PLZA AutoStory builds; the fault sweep's sim-fault mapping comes with the sweep later. --- .../CommonTools/ScreenEvents/ScreenEventLog.h | 90 ++ .../ScreenEvents/ScreenEventTypes.h | 94 +++ .../CommonTools/ScreenEvents/ScreenEvents.cpp | 195 +++++ .../CommonTools/ScreenEvents/ScreenEvents.h | 83 ++ .../ScreenEvents/ScreenEvents_Tests.cpp | 281 +++++++ .../ScreenEvents/ScreenEvents_Tests.h | 21 + .../CommonTools/ScreenEvents/ScreenFades.h | 43 + .../ComputerPrograms_UnitTestRunner.cpp | 16 + .../Data/Pokemon_AuthoredCheckpointJson.cpp | 59 ++ .../Data/Pokemon_AuthoredCheckpointJson.h | 68 ++ .../Pokemon_AuthoredCheckpointJson_Tests.cpp | 181 ++++ .../Pokemon_AuthoredCheckpointJson_Tests.h | 23 + .../AutoStory/Data/Pokemon_StoryStepJson.cpp | 384 +++++++++ .../AutoStory/Data/Pokemon_StoryStepJson.h | 60 ++ .../Data/Pokemon_StoryStepJson_Tests.cpp | 295 +++++++ .../Data/Pokemon_StoryStepJson_Tests.h | 30 + .../AutoStory/Pokemon_BuiltinStoryActions.cpp | 79 ++ .../AutoStory/Pokemon_BuiltinStoryActions.h | 66 ++ .../Pokemon/AutoStory/Pokemon_MapUtil.h | 44 + .../AutoStory/Pokemon_StoryCheckpointTypes.h | 86 ++ .../Pokemon/AutoStory/Pokemon_StoryEvent.h | 90 ++ .../Pokemon/AutoStory/Pokemon_StoryEvents.cpp | 578 +++++++++++++ .../Pokemon/AutoStory/Pokemon_StoryEvents.h | 74 ++ .../AutoStory/Pokemon_StoryEvents_Tests.cpp | 771 ++++++++++++++++++ .../AutoStory/Pokemon_StoryEvents_Tests.h | 23 + .../AutoStory/Pokemon_StoryFailureClasses.cpp | 294 +++++++ .../AutoStory/Pokemon_StoryFailureClasses.h | 107 +++ .../Pokemon_StoryFailureClasses_Tests.cpp | 260 ++++++ .../Pokemon_StoryFailureClasses_Tests.h | 23 + .../Pokemon/AutoStory/Pokemon_StoryLog.cpp | 85 ++ .../Pokemon/AutoStory/Pokemon_StoryLog.h | 85 ++ .../AutoStory/Pokemon_StoryLog_Tests.cpp | 167 ++++ .../AutoStory/Pokemon_StoryLog_Tests.h | 23 + .../Pokemon/AutoStory/Pokemon_StoryOutcome.h | 76 ++ .../AutoStory/Pokemon_StoryOutcomeClass.cpp | 35 + .../AutoStory/Pokemon_StoryOutcomeClass.h | 35 + .../Pokemon/AutoStory/Pokemon_StoryPose.h | 79 ++ .../AutoStory/Pokemon_StoryStepExecutor.cpp | 181 ++++ .../AutoStory/Pokemon_StoryStepExecutor.h | 132 +++ .../Pokemon_StoryStepExecutor_Tests.cpp | 451 ++++++++++ .../Pokemon_StoryStepExecutor_Tests.h | 23 + .../Pokemon/AutoStory/Pokemon_TilePose.cpp | 54 ++ .../Pokemon/AutoStory/Pokemon_TilePose.h | 49 ++ .../AutoStory/Types/Pokemon_DeclaredPose.h | 53 ++ .../AutoStory/Types/Pokemon_GridPose.h | 37 + .../Types/Pokemon_StoryActionArg.cpp | 20 + .../AutoStory/Types/Pokemon_StoryActionArg.h | 93 +++ .../Types/Pokemon_StoryActionArg_Tests.cpp | 143 ++++ .../Types/Pokemon_StoryActionArg_Tests.h | 23 + .../Types/Pokemon_StoryActionSpec.cpp | 62 ++ .../AutoStory/Types/Pokemon_StoryActionSpec.h | 56 ++ .../Types/Pokemon_StoryBreakpoints.cpp | 91 +++ .../Types/Pokemon_StoryBreakpoints.h | 97 +++ .../Types/Pokemon_StoryCheckLevel.cpp | 32 + .../AutoStory/Types/Pokemon_StoryCheckLevel.h | 43 + .../AutoStory/Types/Pokemon_StoryCheckpoint.h | 48 ++ .../Types/Pokemon_StoryCheckpointMetadata.cpp | 37 + .../Types/Pokemon_StoryCheckpointMetadata.h | 69 ++ .../Types/Pokemon_StoryPostconditions.h | 43 + .../AutoStory/Types/Pokemon_StorySaveMode.cpp | 43 + .../AutoStory/Types/Pokemon_StorySaveMode.h | 59 ++ .../Types/Pokemon_StorySegmentTypes.cpp | 38 + .../Types/Pokemon_StorySegmentTypes.h | 91 +++ .../AutoStory/Types/Pokemon_StoryStep.h | 60 ++ .../AutoStory/Types/Pokemon_StoryStepKind.cpp | 52 ++ .../AutoStory/Types/Pokemon_StoryStepKind.h | 45 + .../Pokemon/Navigation/Pokemon_Direction.cpp | 30 + .../Pokemon/Navigation/Pokemon_Direction.h | 36 + .../Pokemon/Navigation/Pokemon_Grid.cpp | 35 + .../Source/Pokemon/Navigation/Pokemon_Grid.h | 78 ++ SerialPrograms/cmake/SourceFiles.cmake | 69 ++ 71 files changed, 7476 insertions(+) create mode 100644 SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEventLog.h create mode 100644 SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEventTypes.h create mode 100644 SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents.cpp create mode 100644 SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents.h create mode 100644 SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents_Tests.cpp create mode 100644 SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents_Tests.h create mode 100644 SerialPrograms/Source/CommonTools/ScreenEvents/ScreenFades.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_MapUtil.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryCheckpointTypes.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcome.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_DeclaredPose.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_GridPose.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryBreakpoints.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryBreakpoints.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryPostconditions.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.h diff --git a/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEventLog.h b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEventLog.h new file mode 100644 index 0000000000..2d3039a5e7 --- /dev/null +++ b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEventLog.h @@ -0,0 +1,90 @@ +/* Screen Event Log + * + * From: https://github.com/PokemonAutomation/ + * + * The screen events of a stream of frames, in order and timed. + * + */ + +#ifndef PokemonAutomation_CommonTools_ScreenEvents_ScreenEventLog_H +#define PokemonAutomation_CommonTools_ScreenEvents_ScreenEventLog_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "ScreenEventTypes.h" + +namespace PokemonAutomation{ + + +// Whether an event started or stopped showing. +enum class ScreenEventEdge : uint8_t{ + ROSE, + FELL, +}; + +// One event starting or stopping to show, at the frame that showed it. +struct ScreenEventChange{ + WallClock time; + ScreenEvent event; + ScreenEventEdge edge; + + bool operator==(const ScreenEventChange& other) const = default; +}; + +// How many changes a log keeps. A walk's events change a few times a +// second at most (a fade's black, a box, the screen going still), so this +// is a minute or more of a busy scene. +constexpr size_t SCREEN_EVENT_LOG_CAPACITY = 256; + +// The events of a stream of frames, in order and timed: what rose and fell +// when, not only what was seen (ScreenEventWatcher::seen()). The judges that +// care about order read it: a flash then a battle is an encounter, a box +// then a battle a trainer's sight. +// +// It keeps the newest `capacity` changes and counts the ones it dropped. +// Not thread-safe; ScreenEventWatcher guards its own. +class ScreenEventLog{ +public: + explicit ScreenEventLog(size_t capacity = SCREEN_EVENT_LOG_CAPACITY); + + // Adds a frame: a change for each event that rose or fell since the + // frame before (the first frame's events all rise). `now` must not go + // back in time. + void record(const ScreenEvents& frame, WallClock now); + + // The changes kept, oldest first. + const std::deque& changes() const{ + return m_changes; + } + // How many changes were dropped, oldest first, to keep the capacity. + size_t dropped() const{ + return m_dropped; + } + // The events of the last frame recorded. + ScreenEvents showing() const{ + return m_showing; + } + // When the last frame was recorded; none before the first. + std::optional last_frame() const{ + return m_last_frame; + } + void clear(); + +private: + size_t m_capacity; + std::deque m_changes; + size_t m_dropped = 0; + ScreenEvents m_showing; + std::optional m_last_frame; +}; +// "+1200 ms dialog box rose", times from `origin`, one change per line. +std::string describe(const ScreenEventLog& log, WallClock origin); + + + +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEventTypes.h b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEventTypes.h new file mode 100644 index 0000000000..e9d05d5052 --- /dev/null +++ b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEventTypes.h @@ -0,0 +1,94 @@ +/* Screen Event Types + * + * From: https://github.com/PokemonAutomation/ + * + * The words a program uses for what the screen shows: a fade, a dialogue + * box, a battle starting. ScreenEvents.h watches a stream for them. + * + */ + +#ifndef PokemonAutomation_CommonTools_ScreenEvents_ScreenEventTypes_H +#define PokemonAutomation_CommonTools_ScreenEvents_ScreenEventTypes_H + +#include +#include +#include +#include +#include + +namespace PokemonAutomation{ + + +// One thing a frame shows. A game reports the ones its detectors can see. +enum class ScreenEvent : uint8_t{ + FADE_BLACK, // A uniform dark screen: a door, a cave mouth, a scene cut. + FADE_WHITE, // A uniform white screen: a cave exit. + LOCATION_BANNER, // A location banner. An observer given an expected + // map reports only that map's. + DIALOG_BOX, // A dialogue box. + CHOICE_BOX, // A choice (Yes/No, a menu of answers). + INTERACT_PROMPT, // A button prompt to interact ("A Talk"). + BATTLE_STARTED, // A battle shows (its menu, its HUD or its opening). + BATTLE_ENDED, // A battle's closing screen. + PLAYER_CAN_MOVE, // The overworld with the player in control. + SCREEN_STILL, // The screen barely changed since the frame before. + SWITCH_HOME_MENU, // The Switch's HOME menu: the game is not on the screen. +}; +// How many ScreenEvent values there are. +constexpr size_t SCREEN_EVENT_COUNT = 11; +static_assert((size_t)ScreenEvent::SWITCH_HOME_MENU + 1 == SCREEN_EVENT_COUNT, "SWITCH_HOME_MENU is the last ScreenEvent"); +// "dialog box", for the log. +std::string screen_event_name(ScreenEvent event); + + +// How a screen's fade looks: the kind of FADE_BLACK / FADE_WHITE. +enum class WarpFade{ + NONE, + BLACK, // a door's black, or a cave mouth's dim fade + WHITE, // a cave exit's white, with no battle after it +}; +// "black fade", for the log. +std::string warp_fade_name(WarpFade fade); + + +// The events of one frame, or of all the frames a watcher saw. +class ScreenEvents{ +public: + ScreenEvents() = default; + ScreenEvents(std::initializer_list events); + + bool has(ScreenEvent event) const{ + return (m_bits & bit(event)) != 0; + } + // Whether any of `events` is in this set. + bool any_of(const ScreenEvents& events) const{ + return (m_bits & events.m_bits) != 0; + } + // Adds `event`, or removes it when `on` is false (as std::bitset::set). + void set(ScreenEvent event, bool on); + void merge(const ScreenEvents& events){ + m_bits |= events.m_bits; + } + + uint32_t bits() const{ + return m_bits; + } + static ScreenEvents from_bits(uint32_t bits); + + bool operator==(const ScreenEvents& other) const = default; + +private: + static uint32_t bit(ScreenEvent event){ + return uint32_t(1) << (uint32_t)event; + } + + uint32_t m_bits = 0; +}; +// "dialog box, player can move" (joined by `separator`); "nothing" when +// empty. +std::string describe(const ScreenEvents& events, std::string_view separator = ", "); + + + +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents.cpp b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents.cpp new file mode 100644 index 0000000000..d063dd3c56 --- /dev/null +++ b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents.cpp @@ -0,0 +1,195 @@ +/* Screen Events + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "ScreenEventLog.h" +#include "ScreenEventTypes.h" +#include "ScreenFades.h" +#include "ScreenEvents.h" + +namespace PokemonAutomation{ + + +std::string screen_event_name(ScreenEvent event){ + switch (event){ + case ScreenEvent::FADE_BLACK: return "black fade"; + case ScreenEvent::FADE_WHITE: return "white fade"; + case ScreenEvent::LOCATION_BANNER: return "location banner"; + case ScreenEvent::DIALOG_BOX: return "dialog box"; + case ScreenEvent::CHOICE_BOX: return "choice box"; + case ScreenEvent::INTERACT_PROMPT: return "interact prompt"; + case ScreenEvent::BATTLE_STARTED: return "battle started"; + case ScreenEvent::BATTLE_ENDED: return "battle ended"; + case ScreenEvent::PLAYER_CAN_MOVE: return "player can move"; + case ScreenEvent::SCREEN_STILL: return "screen still"; + case ScreenEvent::SWITCH_HOME_MENU: return "Switch HOME menu"; + } + return "?"; +} + +std::string warp_fade_name(WarpFade fade){ + switch (fade){ + case WarpFade::NONE: return "no fade"; + case WarpFade::BLACK: return "black fade"; + case WarpFade::WHITE: return "white fade"; + } + return "?"; +} + + +ScreenEvents::ScreenEvents(std::initializer_list events){ + for (ScreenEvent event : events){ + set(event, true); + } +} +void ScreenEvents::set(ScreenEvent event, bool on){ + if (on){ + m_bits |= bit(event); + }else{ + m_bits &= ~bit(event); + } +} +ScreenEvents ScreenEvents::from_bits(uint32_t bits){ + ScreenEvents out; + out.m_bits = bits & ((uint32_t(1) << SCREEN_EVENT_COUNT) - 1); + return out; +} + +ScreenEvents fade_events(WarpFade fade){ + switch (fade){ + case WarpFade::NONE: + return {}; + case WarpFade::BLACK: + return {ScreenEvent::FADE_BLACK}; + case WarpFade::WHITE: + return {ScreenEvent::FADE_WHITE}; + } + return {}; +} +WarpFade fade_in(const ScreenEvents& events){ + if (events.has(ScreenEvent::FADE_BLACK)){ + return WarpFade::BLACK; + } + if (events.has(ScreenEvent::FADE_WHITE)){ + return WarpFade::WHITE; + } + return WarpFade::NONE; +} +std::string describe(const ScreenEvents& events, std::string_view separator){ + std::string out; + for (size_t c = 0; c < SCREEN_EVENT_COUNT; c++){ + const ScreenEvent event = (ScreenEvent)c; + if (!events.has(event)){ + continue; + } + if (!out.empty()){ + out += separator; + } + out += screen_event_name(event); + } + return out.empty() ? "nothing" : out; +} + + +// Black is is_black() (SolidColorTest, BlackScreenDetector's test) with +// the fade's thresholds. +// White is not is_white(): that also wants an even grey, and a fade to +// white can be tinted. +WarpFade fade_of(const ImageStats& middle){ + if (is_black(middle, FADE_MAX_DARK_SUM, FADE_MAX_STDDEV_SUM)){ + return WarpFade::BLACK; + } + if (middle.stddev.sum() > FADE_MAX_STDDEV_SUM){ + return WarpFade::NONE; + } + return middle.average.sum() >= FADE_MIN_WHITE_SUM ? WarpFade::WHITE : WarpFade::NONE; +} +WarpFade fade_of_screen(const ImageViewRGB32& screen){ + return fade_of(image_stats(extract_box_reference(screen, ImageFloatBox(0.1, 0.1, 0.8, 0.8)))); +} + + +ScreenEventLog::ScreenEventLog(size_t capacity) + : m_capacity(capacity) +{} +void ScreenEventLog::record(const ScreenEvents& frame, WallClock now){ + const uint32_t changed = frame.bits() ^ m_showing.bits(); + for (size_t c = 0; c < SCREEN_EVENT_COUNT; c++){ + if ((changed & (uint32_t(1) << c)) == 0){ + continue; + } + const ScreenEvent event = (ScreenEvent)c; + m_changes.push_back({now, event, frame.has(event) ? ScreenEventEdge::ROSE : ScreenEventEdge::FELL}); + } + while (m_changes.size() > m_capacity){ + m_changes.pop_front(); + m_dropped++; + } + m_showing = frame; + m_last_frame = now; +} +void ScreenEventLog::clear(){ + m_changes.clear(); + m_dropped = 0; + m_showing = ScreenEvents(); + m_last_frame.reset(); +} +std::string describe(const ScreenEventLog& log, WallClock origin){ + std::string out; + if (log.dropped() > 0){ + out += std::format("({} older changes dropped)\n", log.dropped()); + } + for (const ScreenEventChange& change : log.changes()){ + out += std::format( + "{:+} ms {} {}\n", + std::chrono::duration_cast(change.time - origin).count(), + screen_event_name(change.event), + change.edge == ScreenEventEdge::ROSE ? "rose" : "fell" + ); + } + return out.empty() ? "no changes" : out; +} + + +ScreenEventWatcher::ScreenEventWatcher(ScreenEventObserver& observer, ScreenEvents stop_on) + : VisualInferenceCallback("ScreenEventWatcher") + , m_observer(observer) + , m_stop_on(stop_on) +{} +void ScreenEventWatcher::make_overlays(VideoOverlaySet& items) const{ + m_observer.make_overlays(items); +} +bool ScreenEventWatcher::process_frame(const VideoSnapshot& frame){ + const ScreenEvents events = m_observer.observe(frame, frame.timestamp); + m_seen.fetch_or(events.bits(), std::memory_order_acq_rel); + { + LockGuard lg(m_log_lock); + m_log.record(events, frame.timestamp); + } + if (!events.any_of(m_stop_on)){ + return false; + } + m_stopped_on.store(events.bits(), std::memory_order_release); + return true; +} +ScreenEventLog ScreenEventWatcher::log() const{ + LockGuard lg(m_log_lock); + return m_log; +} +void ScreenEventWatcher::reset(){ + m_seen.store(0, std::memory_order_release); + m_stopped_on.store(0, std::memory_order_release); + LockGuard lg(m_log_lock); + m_log.clear(); +} + + + +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents.h b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents.h new file mode 100644 index 0000000000..3e90b8d85d --- /dev/null +++ b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents.h @@ -0,0 +1,83 @@ +/* Screen Events + * + * From: https://github.com/PokemonAutomation/ + * + * What an autonomous program can see on the screen, in words every game + * shares: a fade, a location banner, a dialogue box, a battle starting. + * Each game implements ScreenEventObserver with its own detectors; the + * judgements built on these events are then the same for all of them. + * + * An observer runs during a controller action as a ScreenEventWatcher + * (a VisualInferenceCallback for run_until), or is asked frame by frame. + * + */ + +#ifndef PokemonAutomation_CommonTools_ScreenEvents_ScreenEvents_H +#define PokemonAutomation_CommonTools_ScreenEvents_ScreenEvents_H + +#include +#include +#include "Common/Cpp/Concurrency/Mutex.h" +#include "Common/Cpp/Time.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "ScreenEventLog.h" +#include "ScreenEventTypes.h" + +namespace PokemonAutomation{ + + +// A game's detectors, as events. Observers may keep state between frames +// (the frame before, for SCREEN_STILL; when a banner was last read, to +// gate OCR), so one observer watches one stream at a time. +class ScreenEventObserver{ +public: + virtual ~ScreenEventObserver() = default; + + // What `frame` shows. `now` is the caller's clock, for observers that + // rate-limit expensive reads. A null frame shows nothing. + virtual ScreenEvents observe(const VideoSnapshot& frame, WallClock now) = 0; + + // The boxes the detectors read, for the video overlay. + virtual void make_overlays(VideoOverlaySet& items) const = 0; +}; + + +// An observer as a run_until callback: it records every event it sees, in +// order in a log, and stops the action on any of `stop_on` (none: it only +// records). +class ScreenEventWatcher : public VisualInferenceCallback{ +public: + ScreenEventWatcher(ScreenEventObserver& observer, ScreenEvents stop_on = {}); + + virtual void make_overlays(VideoOverlaySet& items) const override; + using VisualInferenceCallback::process_frame; + virtual bool process_frame(const VideoSnapshot& frame) override; + + // Every event seen since construction (or the last reset()). + ScreenEvents seen() const{ + return ScreenEvents::from_bits(m_seen.load(std::memory_order_acquire)); + } + // The events of the frame that stopped the action ("nothing" if none did). + ScreenEvents stopped_on() const{ + return ScreenEvents::from_bits(m_stopped_on.load(std::memory_order_acquire)); + } + // A copy of the timed log of every frame since construction (or the + // last reset()). + ScreenEventLog log() const; + void reset(); + +private: + ScreenEventObserver& m_observer; + const ScreenEvents m_stop_on; + std::atomic m_seen{0}; + std::atomic m_stopped_on{0}; + mutable Mutex m_log_lock; + ScreenEventLog m_log; +}; + + + +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents_Tests.cpp b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents_Tests.cpp new file mode 100644 index 0000000000..7b61ab9227 --- /dev/null +++ b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents_Tests.cpp @@ -0,0 +1,281 @@ +/* Screen Events Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The shared event vocabulary and the watcher form of an observer. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "ScreenEventLog.h" +#include "ScreenEventTypes.h" +#include "ScreenFades.h" +#include "ScreenEvents.h" +#include "ScreenEvents_Tests.h" + +namespace PokemonAutomation{ + +namespace{ + +using namespace std::chrono_literals; + +UnitTestResult expect_equal(const std::string& what, const std::string& got, const std::string& expected){ + if (got == expected){ + return true; + } + return std::format("{}: expected \"{}\", got \"{}\"", what, expected, got); +} + + +UnitTestResult test_set_and_describe(){ + ScreenEvents events{ScreenEvent::DIALOG_BOX, ScreenEvent::PLAYER_CAN_MOVE}; + if (!events.has(ScreenEvent::DIALOG_BOX) || events.has(ScreenEvent::CHOICE_BOX)){ + return "has() disagrees with the constructor's events"; + } + events.set(ScreenEvent::DIALOG_BOX, false); + events.merge(fade_events(WarpFade::WHITE)); + events.merge(fade_events(WarpFade::NONE)); + if (fade_in(events) != WarpFade::WHITE){ + return "fade_events(WHITE) did not give a white fade"; + } + if (ScreenEvents::from_bits(events.bits()) != events){ + return "from_bits(bits()) is not the same set"; + } + if (describe(ScreenEvents()) != "nothing"){ + return "an empty set does not describe as nothing"; + } + return expect_equal("describe()", describe(events), "white fade, player can move"); +} + +// A screen filled with one colour, or a checkerboard of two. +ImageRGB32 screen_of(uint32_t a, uint32_t b){ + ImageRGB32 out(64, 36); + for (size_t y = 0; y < out.height(); y++){ + for (size_t x = 0; x < out.width(); x++){ + out.pixel(x, y) = (x + y) % 2 == 0 ? a : b; + } + } + return out; +} + +UnitTestResult test_fade_of_screen(){ + struct Row{ + std::string name; + uint32_t a; + uint32_t b; + WarpFade fade; + }; + const std::vector rows = { + {"black", 0xff000000, 0xff000000, WarpFade::BLACK}, + {"a cave mouth's dim fade (60 a channel)", 0xff3c3c3c, 0xff3c3c3c, WarpFade::BLACK}, + {"white", 0xffffffff, 0xffffffff, WarpFade::WHITE}, + {"grey, neither", 0xff787878, 0xff787878, WarpFade::NONE}, + {"a dark textured floor", 0xff101010, 0xff505050, WarpFade::NONE}, + }; + for (const Row& row : rows){ + const WarpFade got = fade_of_screen(screen_of(row.a, row.b)); + if (got != row.fade){ + return std::format("{}: expected {}, got {}", row.name, warp_fade_name(row.fade), warp_fade_name(got)); + } + } + return true; +} + +// Replays a fixed list of event sets, one per frame. +class ScriptedObserver : public ScreenEventObserver{ +public: + explicit ScriptedObserver(std::vector frames) + : m_frames(std::move(frames)) + {} + virtual ScreenEvents observe(const VideoSnapshot&, WallClock) override{ + return m_next < m_frames.size() ? m_frames[m_next++] : ScreenEvents(); + } + virtual void make_overlays(VideoOverlaySet&) const override{} + +private: + std::vector m_frames; + size_t m_next = 0; +}; + +UnitTestResult test_watcher(){ + ScriptedObserver observer({ + {ScreenEvent::PLAYER_CAN_MOVE}, + {ScreenEvent::FADE_BLACK}, + {ScreenEvent::LOCATION_BANNER, ScreenEvent::PLAYER_CAN_MOVE}, + {ScreenEvent::DIALOG_BOX}, + }); + ScreenEventWatcher watcher(observer, {ScreenEvent::LOCATION_BANNER}); + const VideoSnapshot frame; + std::vector stops; + for (size_t c = 0; c < 4; c++){ + stops.push_back(watcher.process_frame(frame)); + } + if (stops != std::vector{false, false, true, false}){ + return "the watcher did not stop exactly on the banner frame"; + } + UnitTestResult result = expect_equal("seen()", describe(watcher.seen()), + "black fade, location banner, dialog box, player can move"); + if (result.result != UnitTestResult::PASSED){ + return result; + } + result = expect_equal("stopped_on()", describe(watcher.stopped_on()), "location banner, player can move"); + if (result.result != UnitTestResult::PASSED){ + return result; + } + watcher.reset(); + return expect_equal("seen() after reset()", describe(watcher.seen()), "nothing"); +} + + +struct ScreenEventsCase{ + struct Input{ + std::function body; + }; + struct Expectation{ + }; + + std::string name; + Input input; + Expectation expectation; +}; + +class Test_ScreenEvents : public UnitTest{ +public: + explicit Test_ScreenEvents(ScreenEventsCase test_case) + : UnitTest(std::format("CommonTools::ScreenEvents - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_case.input.body(); + } + +private: + ScreenEventsCase m_case; +}; + +} // namespace + + +const ScreenEventsCase SCREEN_EVENTS_CASES[] = { + { + .name = "a set of events, its fade and its log text", + .input = {.body = test_set_and_describe}, + .expectation = {}, + }, + { + .name = "a fade is uniform, dark or white; a textured floor is none", + .input = {.body = test_fade_of_screen}, + .expectation = {}, + }, + { + .name = "an observer as a watcher records and stops", + .input = {.body = test_watcher}, + .expectation = {}, + }, +}; + +namespace{ + +// A stream of frames into a ScreenEventLog, and its describe() text. +struct ScreenEventLogCase{ + struct Frame{ + int ms = 0; + std::vector events; + }; + struct Input{ + size_t capacity = 0; + std::vector frames; + }; + struct Expectation{ + // describe() of the log, times from the first frame. + std::string text; + size_t dropped = 0; + }; + + std::string name; + Input input; + Expectation expectation; +}; + +class Test_ScreenEventLog : public UnitTest{ +public: + explicit Test_ScreenEventLog(ScreenEventLogCase test_case) + : UnitTest(std::format("CommonTools::ScreenEventLog - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + ScreenEventLog log(m_case.input.capacity); + const WallClock origin = current_time(); + for (const ScreenEventLogCase::Frame& frame : m_case.input.frames){ + ScreenEvents events; + for (ScreenEvent event : frame.events){ + events.set(event, true); + } + log.record(events, origin + Milliseconds(frame.ms)); + } + if (log.dropped() != m_case.expectation.dropped){ + return std::format("dropped(): expected {}, got {}", m_case.expectation.dropped, log.dropped()); + } + return expect_equal("describe()", describe(log, origin), m_case.expectation.text); + } + +private: + ScreenEventLogCase m_case; +}; + +} // namespace + +const ScreenEventLogCase SCREEN_EVENT_LOG_CASES[] = { + { + .name = "no frames", + .input = {.capacity = 8, .frames = {}}, + .expectation = {.text = "no changes", .dropped = 0}, + }, + { + .name = "the first frame's events all rise", + .input = {.capacity = 8, .frames = {{.ms = 0, .events = {ScreenEvent::DIALOG_BOX, ScreenEvent::SCREEN_STILL}}}}, + .expectation = {.text = "+0 ms dialog box rose\n+0 ms screen still rose\n", .dropped = 0}, + }, + { + .name = "only changes are kept, rising and falling", + .input = {.capacity = 8, .frames = { + {.ms = 0, .events = {ScreenEvent::PLAYER_CAN_MOVE}}, + {.ms = 100, .events = {ScreenEvent::PLAYER_CAN_MOVE}}, + {.ms = 200, .events = {ScreenEvent::FADE_BLACK}}, + {.ms = 900, .events = {}}, + }}, + .expectation = { + .text = "+0 ms player can move rose\n+200 ms black fade rose\n+200 ms player can move fell\n+900 ms black fade fell\n", + .dropped = 0, + }, + }, + { + .name = "the oldest changes drop past the capacity", + .input = {.capacity = 2, .frames = { + {.ms = 0, .events = {ScreenEvent::DIALOG_BOX}}, + {.ms = 100, .events = {}}, + {.ms = 200, .events = {ScreenEvent::CHOICE_BOX}}, + }}, + .expectation = {.text = "(1 older changes dropped)\n+100 ms dialog box fell\n+200 ms choice box rose\n", .dropped = 1}, + }, +}; + +void add_tests_ScreenEvents(UnitTestDatabase& database){ + for (const auto& item : SCREEN_EVENTS_CASES){ + database.add(item); + } + for (const auto& item : SCREEN_EVENT_LOG_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents_Tests.h b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents_Tests.h new file mode 100644 index 0000000000..3d1c84b44f --- /dev/null +++ b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenEvents_Tests.h @@ -0,0 +1,21 @@ +/* Screen Events Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ScreenEvents_ScreenEvents_Tests_H +#define PokemonAutomation_CommonTools_ScreenEvents_ScreenEvents_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ + + +// Registers unit tests for the shared screen events. +void add_tests_ScreenEvents(UnitTestDatabase& database); + + + +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenFades.h b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenFades.h new file mode 100644 index 0000000000..a153f49246 --- /dev/null +++ b/SerialPrograms/Source/CommonTools/ScreenEvents/ScreenFades.h @@ -0,0 +1,43 @@ +/* Screen Fades + * + * From: https://github.com/PokemonAutomation/ + * + * A fade to black or white, read from a screen and as screen events. + * + */ + +#ifndef PokemonAutomation_CommonTools_ScreenEvents_ScreenFades_H +#define PokemonAutomation_CommonTools_ScreenEvents_ScreenFades_H + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "ScreenEventTypes.h" + +namespace PokemonAutomation{ + + +// The event of a fade: FADE_BLACK, FADE_WHITE, or none for WarpFade::NONE. +ScreenEvents fade_events(WarpFade fade); +// The fade `events` show: BLACK before WHITE if they have both. +WarpFade fade_in(const ScreenEvents& events); + + +// A fade is uniform over the middle 80% of the screen, the same stddev +// test as the shared Black/WhiteScreenWatcher: a dim cave floor (mean +// about 46 a channel) is textured, so it is no fade. A tighter bound +// needs checking against such dim floors first. +constexpr double FADE_MAX_STDDEV_SUM = 10; +// Dark goes to an rgb sum of 225, as a cave mouth's fade is dim, 45 to 64 +// a channel, not black. +constexpr double FADE_MAX_DARK_SUM = 225; +// White from an rgb sum of 500, as the shared WhiteScreenWatcher's. +constexpr double FADE_MIN_WHITE_SUM = 500; +// The fade `middle` (the stats of the screen's middle 80%) shows, if any. +WarpFade fade_of(const ImageStats& middle); +// fade_of() for a screen. +WarpFade fade_of_screen(const ImageViewRGB32& screen); + + + +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index cfc9664f24..f4665c9940 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -18,6 +18,13 @@ #include "Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h" #include "Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.h" #include "Pokemon/AutoStory/Pokemon_CheckpointId_Tests.h" +#include "Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.h" +#include "Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.h" +#include "Pokemon/AutoStory/Pokemon_StoryEvents_Tests.h" +#include "Pokemon/AutoStory/Pokemon_StoryFailureClasses_Tests.h" +#include "Pokemon/AutoStory/Pokemon_StoryLog_Tests.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.h" #include "CommonFramework/AudioPipeline/AudioInfo_Tests.h" #include "CommonFramework/AudioPipeline/Tools/ChannelMixer.h" #include "CommonFramework/AudioPipeline/SinkPipeline_Tests.h" @@ -29,6 +36,7 @@ #include "CommonFramework/Windows/LabControl.h" #include "CommonTools/VisualDetectors/BlackBorderDetector.h" #include "CommonTools/OCR/OCR_Tests.h" +#include "CommonTools/ScreenEvents/ScreenEvents_Tests.h" #include "NintendoSwitch/Inference/NintendoSwitch_CheckOnlineDetector.h" #include "NintendoSwitch/Inference/NintendoSwitch_FailedToConnectDetector.h" @@ -76,10 +84,18 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ add_tests_AudioFileLoader(ret); add_tests_LabControl(ret); OCR::add_tests(ret); + add_tests_ScreenEvents(ret); Kernels::add_tests(ret); Pokemon::add_tests_AutoStorySelect(ret); Pokemon::add_tests_AutoStoryStats(ret); Pokemon::add_tests_CheckpointId(ret); + Pokemon::add_tests_AuthoredCheckpointJson(ret); + Pokemon::add_tests_StoryStepJson(ret); + Pokemon::add_tests_StoryStepExecutor(ret); + Pokemon::add_tests_StoryEvents(ret); + Pokemon::add_tests_StoryFailureClasses(ret); + Pokemon::add_tests_StoryLog(ret); + Pokemon::add_tests_StoryActionArg(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); NintendoSwitch::add_tests_UpdatePopupDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.cpp new file mode 100644 index 0000000000..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..bdd61af353 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h @@ -0,0 +1,68 @@ +/* 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. + * + */ + +#ifndef PokemonAutomation_AuthoredCheckpointJson_H +#define PokemonAutomation_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..94f31cf0f0 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp @@ -0,0 +1,181 @@ +/* Shared Authored Checkpoint JSON Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_AuthoredCheckpointJson.h" +#ifndef PA_STORY_DATA_STANDALONE +#include "Pokemon_AuthoredCheckpointJson_Tests.h" +#endif + +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()); + } +} + + +#ifndef PA_STORY_DATA_STANDALONE + +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; +}; + +#endif + + +} // namespace + + +#ifndef PA_STORY_DATA_STANDALONE + +void add_tests_AuthoredCheckpointJson(UnitTestDatabase& database){ + for (const AuthoredCase& test : CASES){ + database.add(test); + } +} + +#endif + + + +} // namespace Pokemon +} // namespace PokemonAutomation + + +#ifdef PA_STORY_DATA_STANDALONE + +int main(){ + int failed = 0; + for (const auto& test : PokemonAutomation::Pokemon::CASES){ + const std::string error = PokemonAutomation::Pokemon::check_case(test); + std::cout << test.name << ": " << (error.empty() ? "PASS" : error) << '\n'; + failed += !error.empty(); + } + return failed != 0; +} + +#endif 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_StoryStepJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp new file mode 100644 index 0000000000..095cbd5014 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp @@ -0,0 +1,384 @@ +/* Story Step JSON + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon_StoryStepJson.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// The wire names of the step kinds. +constexpr std::array, 15> KINDS{{ + {StoryStepKind::NEW_GAME, "new_game"}, + {StoryStepKind::OPTIONS, "options"}, + {StoryStepKind::ROUTE, "route"}, + {StoryStepKind::LEGS, "legs"}, + {StoryStepKind::STEP, "step"}, + {StoryStepKind::TALK, "talk"}, + {StoryStepKind::ANSWER, "answer"}, + {StoryStepKind::MASH, "scene"}, + {StoryStepKind::BATTLE, "battle"}, + {StoryStepKind::TRAIN, "train"}, + {StoryStepKind::HEAL, "heal"}, + {StoryStepKind::SHOP, "shop"}, + {StoryStepKind::SAVE, "save"}, + {StoryStepKind::READY, "ready"}, + {StoryStepKind::GAME, "game_action"}, +}}; + +// The wire names of the directions. +constexpr std::array, 4> DIRECTIONS{{ + {Direction::NORTH, "north"}, + {Direction::EAST, "east"}, + {Direction::SOUTH, "south"}, + {Direction::WEST, "west"}, +}}; + + +// `value` as an object with no field outside `keys`. +const JsonObject& fields(const JsonValue& value, std::initializer_list keys, std::string_view source){ + const JsonObject& object = value.to_object_throw(std::string(source)); + for (const auto& [key, unused] : object){ + bool known = false; + for (std::string_view allowed : keys){ + known |= key == allowed; + } + if (!known){ + throw ParseException(std::format("{}: unsupported field {}", source, key)); + } + } + return object; +} + +template +Enum read_enum(const std::array, N>& names, std::string_view name, std::string_view source){ + for (const auto& [value, label] : names){ + if (label == name){ + return value; + } + } + throw ParseException(std::format("{}: unsupported value {}", source, name)); +} + +int integer(const JsonValue& value, std::string_view source){ + const int64_t number = value.to_integer_throw(std::string(source)); + if (number < std::numeric_limits::min() || number > std::numeric_limits::max()){ + throw ParseException(std::format("{}: coordinate exceeds native int", source)); + } + return (int)number; +} + +size_t count(const JsonValue& value, std::string_view source){ + const int64_t number = value.to_integer_throw(std::string(source)); + if (number < 0 || (uint64_t)number > std::numeric_limits::max()){ + throw ParseException(std::format("{}: count is out of range", source)); + } + return (size_t)number; +} + +std::vector read_strings(const JsonValue& value, std::string_view source){ + std::vector result; + for (const JsonValue& item : value.to_array_throw(std::string(source))){ + result.push_back(item.to_string_throw(std::string(source))); + } + return result; +} + +std::vector read_legs(const JsonValue& value, std::string_view source){ + std::vector result; + for (const JsonValue& item : value.to_array_throw(std::string(source))){ + const JsonObject& row = fields(item, {"direction", "tiles"}, source); + result.push_back({.direction = read_enum(DIRECTIONS, row.get_string_throw("direction"), source), + .tiles = integer(row.get_value_throw("tiles"), source)}); + } + return result; +} + +std::vector read_items(const JsonValue& value, std::string_view source){ + std::vector result; + for (const JsonValue& item : value.to_array_throw(std::string(source))){ + const JsonObject& row = fields(item, {"item", "quantity"}, source); + result.push_back({.item = row.get_string_throw("item"), .quantity = count(row.get_value_throw("quantity"), source)}); + } + return result; +} + +std::vector> read_integer_rows(const JsonValue& value, std::string_view source){ + std::vector> result; + for (const JsonValue& item : value.to_array_throw(std::string(source))){ + std::vector row; + for (const JsonValue& number : item.to_array_throw(std::string(source))){ + row.push_back(number.to_integer_throw(std::string(source))); + } + result.push_back(std::move(row)); + } + return result; +} + +std::vector read_timed_legs(const JsonValue& value, std::string_view source){ + std::vector result; + for (const JsonValue& item : value.to_array_throw(std::string(source))){ + const JsonArray& pair = item.to_array_throw(std::string(source)); + if (pair.size() != 2){ + throw ParseException(std::format("{}: a timed leg is [turn degrees, ms]", source)); + } + result.push_back({.turn = integer(pair[0], source), .ms = integer(pair[1], source)}); + } + return result; +} + +std::vector read_tiles(const JsonValue& value, std::string_view source){ + std::vector result; + for (const JsonValue& item : value.to_array_throw(std::string(source))){ + const JsonArray& pair = item.to_array_throw(std::string(source)); + if (pair.size() != 2){ + throw ParseException(std::format("{}: a tile needs two coordinates", source)); + } + result.push_back({integer(pair[0], source), integer(pair[1], source)}); + } + return result; +} + +// One arg's value read as `type`. +StoryArgValue read_arg(const JsonValue& value, StoryArgType type, std::string_view source){ + switch (type){ + case StoryArgType::BOOLEAN: + return value.to_boolean_throw(std::string(source)); + case StoryArgType::INTEGER: + return value.to_integer_throw(std::string(source)); + case StoryArgType::WORD: + return value.to_string_throw(std::string(source)); + case StoryArgType::DIRECTION: + return read_enum(DIRECTIONS, value.to_string_throw(std::string(source)), source); + case StoryArgType::GRID_POSE: + return read_grid_pose(value, source); + case StoryArgType::LEGS: + return read_legs(value, source); + case StoryArgType::WORDS: + return read_strings(value, source); + case StoryArgType::ITEMS: + return read_items(value, source); + case StoryArgType::INTEGER_ROWS: + return read_integer_rows(value, source); + case StoryArgType::TIMED_LEGS: + return read_timed_legs(value, source); + } + throw ParseException(std::format("{}: unsupported story arg type", source)); +} + +// The step's action among `actions`: the named one, or the kind's default. +// Null for a kind with no action that names none. +const StoryActionSpec* step_action( + const StoryStep& step, std::span actions, std::string_view source +){ + if (step.kind == StoryStepKind::GAME && step.action.empty()){ + throw ParseException(std::format("{}: game_action step {} names no action", source, step.name)); + } + const StoryActionSpec* spec = find_story_action(actions, step.kind, step.action); + if (spec == nullptr && !step.action.empty()){ + throw ParseException(std::format("{}: step {}: unknown action {}", source, step.name, step.action)); + } + return spec; +} + +// The step's args, read against its action's spec, with the fallbacks +// filled in. +StoryActionArgs read_args( + const JsonValue* value, const StoryActionSpec* spec, const StoryStep& step, std::string_view source +){ + const StoryActionSpec none{.kind = step.kind, .name = "", .args = {}}; + const StoryActionSpec& action = spec ? *spec : none; + StoryActionArgs result; + if (value != nullptr){ + for (const auto& [key, item] : value->to_object_throw(std::string(source))){ + const auto arg = std::find_if(action.args.begin(), action.args.end(), [&](const StoryArgSpec& candidate){ + return candidate.key == key; + }); + if (arg == action.args.end()){ + throw ParseException(std::format("{}: step {}: unknown argument \"{}\"", source, step.name, key)); + } + result[key] = read_arg(item, arg->type, source); + } + } + const std::vector errors = story_args_errors(action, result); + if (!errors.empty()){ + throw ParseException(std::format("{}: step {}: {}", source, step.name, errors.front())); + } + return with_fallbacks(action, std::move(result)); +} + + +StoryPostconditions read_postconditions(const JsonValue& value, std::string_view source){ + const JsonObject& root = fields(value, {"position", "items", "flags"}, source); + StoryPostconditions result; + if (const JsonValue* field = root.get_value("position")){ + result.position = read_grid_pose(*field, source); + } + if (const JsonValue* field = root.get_value("items")){ + result.items = read_items(*field, source); + } + if (const JsonValue* field = root.get_value("flags")){ + result.flags = read_strings(*field, source); + } + return result; +} + + +StoryVerification read_verification(const JsonValue& value, std::string_view source){ + const JsonObject& root = fields(value, {"steps_hash", "build", "date", "runs"}, source); + StoryVerification result; + result.steps_hash = root.get_string_throw("steps_hash"); + if (const JsonValue* field = root.get_value("build")){ + result.build = field->to_string_throw(); + } + if (const JsonValue* field = root.get_value("date")){ + result.date = field->to_string_throw(); + } + if (const JsonValue* field = root.get_value("runs")){ + result.runs = field->to_string_throw(); + } + return result; +} + +// Reads "metadata" into `checkpoint`. A missing phase is testing. +void read_metadata(const JsonValue& value, std::string_view source, StoryCheckpoint& checkpoint){ + const JsonObject& root = fields(value, {"phase", "verified", "source", "postconditions"}, source); + if (const JsonValue* field = root.get_value("phase")){ + const std::string name = field->to_string_throw(); + const std::optional phase = read_story_phase(name); + if (!phase){ + throw ParseException(std::format("{}: unknown phase {}", source, name)); + } + checkpoint.metadata.phase = *phase; + } + if (const JsonValue* field = root.get_value("verified")){ + checkpoint.metadata.verified = read_verification(*field, source); + } + if (const JsonValue* field = root.get_value("source")){ + checkpoint.metadata.source = field->to_string_throw(); + } + if (const JsonValue* field = root.get_value("postconditions")){ + checkpoint.postconditions = read_postconditions(*field, source); + } +} + + +} // namespace + + +GridPose read_grid_pose(const JsonValue& value, std::string_view source){ + const JsonObject& root = fields(value, {"map", "tiles", "facing"}, source); + GridPose result; + result.map = root.get_string_throw("map"); + // None: any tile of the map, or a game with no tiles (a zone). + if (const JsonValue* field = root.get_value("tiles")){ + result.tiles = read_tiles(*field, source); + } + if (const JsonValue* field = root.get_value("facing")){ + result.facing = read_enum(DIRECTIONS, field->to_string_throw(), source); + } + return result; +} + +DeclaredPose read_declared_pose(const JsonValue& value, std::string_view source){ + const JsonObject& root = value.to_object_throw(std::string(source)); + const bool tile = root.get_value("map") != nullptr; + const bool zone = root.get_value("place") != nullptr; + if (tile == zone){ + throw ParseException(std::format("{}: a declared pose has a \"map\" (tiles) or a \"place\" (a zone), not {}", source, tile ? "both" : "neither")); + } + if (tile){ + GridPose grid = read_grid_pose(value, source); + return TileDeclared{.map = std::move(grid.map), .tiles = std::move(grid.tiles), .facing = grid.facing}; + } + fields(value, {"place", "spot", "heading"}, source); + ZoneDeclared result; + result.place = root.get_string_throw("place"); + if (const JsonValue* field = root.get_value("spot")){ + result.spot = field->to_string_throw(std::string(source)); + } + if (const JsonValue* field = root.get_value("heading")){ + result.heading = integer(*field, source); + } + return result; +} + +StoryStep read_story_step(const JsonValue& value, std::string_view source, std::span actions){ + const JsonObject& root = fields( + value, {"id", "kind", "why", "action", "args", "skip_if", "declared_after", "once_per_save"}, source + ); + StoryStep result; + result.name = root.get_string_throw("id"); + if (result.name.empty()){ + throw ParseException("Empty story step id."); + } + result.kind = read_enum(KINDS, root.get_string_throw("kind"), source); + if (const JsonValue* field = root.get_value("why")){ + result.why = field->to_string_throw(); + } + if (const JsonValue* field = root.get_value("action")){ + result.action = field->to_string_throw(); + } + result.args = read_args(root.get_value("args"), step_action(result, actions, source), result, source); + if (const JsonValue* field = root.get_value("skip_if")){ + result.skip_if = read_strings(*field, source); + } + if (const JsonValue* field = root.get_value("declared_after")){ + result.pose_after = read_declared_pose(*field, source); + } + if (const JsonValue* field = root.get_value("once_per_save")){ + result.once_per_save = field->to_boolean_throw(std::string(source)); + } + return result; +} + +StoryCheckpoint read_story_checkpoint(const JsonValue& value, std::string_view source, std::span actions){ + const JsonObject& root = fields(value, {"id", "title", "start", "events", "metadata"}, source); + StoryCheckpoint result; + result.id = root.get_string_throw("id"); + if (result.id.empty()){ + throw ParseException("Empty story checkpoint id."); + } + result.title = root.get_string_throw("title"); + if (const JsonValue* start = root.get_value("start")){ + result.start = read_declared_pose(*start, source); + } + std::set names; + result.steps_json = root.get_value_throw("events").dump(-1); + for (const JsonValue& event : root.get_array_throw("events")){ + StoryStep step = read_story_step(event, source, actions); + if (step.name.empty() || !names.insert(step.name).second){ + throw ParseException("Empty or duplicate story event id."); + } + result.steps.push_back(std::move(step)); + } + if (const JsonValue* metadata = root.get_value("metadata")){ + read_metadata(*metadata, source, result); + } + return result; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h new file mode 100644 index 0000000000..a67f5df31c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h @@ -0,0 +1,60 @@ +/* Story Step JSON + * + * From: https://github.com/PokemonAutomation/ + * + * Readers of the shared JSON wire form of the story data types (Types/): + * poses, steps and checkpoints, read strictly. This is + * the only layer that reads story JSON: a step comes out with its args + * typed and checked, and nothing after it parses. + * + */ + +#ifndef PokemonAutomation_StoryStepJson_H +#define PokemonAutomation_StoryStepJson_H + +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryStep.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Read a grid pose, {"map": "PalletTown", "tiles": [[3, 4]], "facing": "north"}; +// malformed and unknown fields fail. No "tiles" reads +// as none (any tile, or a game with no tiles). +GridPose read_grid_pose(const JsonValue& value, std::string_view source); + +// Read a declared pose (a checkpoint's "start", a step's "declared_after"): +// a tile one as a grid pose, {"map": ..., "tiles": [[x, y]], "facing": ...}, +// or a zone one, {"place": "LumioseCity", "spot": "HotelZ", "heading": 90} +// (spot and heading optional). One with both or neither of "map" and "place", +// and malformed or unknown fields, fail. +DeclaredPose read_declared_pose(const JsonValue& value, std::string_view source); + + +// Read a step, its args parsed against its action among `actions` (by +// default the built-in ones; a game passes them with its own) and their +// fallbacks filled in. Unknown fields, kinds, actions and args, mistyped +// values and missing required args fail. +StoryStep read_story_step( + const JsonValue& value, std::string_view source, + std::span actions = builtin_story_actions() +); + + +// Read the common checkpoint, its steps read as read_story_step() does. +// Its steps_json keeps the "events" array as read, dumped compactly. +StoryCheckpoint read_story_checkpoint( + const JsonValue& value, std::string_view source, + std::span actions = builtin_story_actions() +); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp new file mode 100644 index 0000000000..296b300744 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp @@ -0,0 +1,295 @@ +/* Story Step JSON Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Each case reads a record from JSON: accepted cases check the values + * read, rejected cases check that the read fails. The standalone + * StoryDataTests also checks PokemonSimulation's shared case file when given + * its path (devtools/story-data-tests/StoryWireCases.h). + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon/AutoStory/Types/Pokemon_DeclaredPose.h" +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h" +#include "Pokemon/Navigation/Pokemon_Direction.h" +#include "Pokemon_StoryStepJson.h" +#include "Pokemon_StoryStepJson_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// Which record a case reads. +enum class Record{ + POSE, + DECLARED, + STEP, + CHECKPOINT, +}; + +// What a read gives. +using ReadRecord = std::variant; + +// "" when the record read is as expected, else what differs. +using ReadCheck = std::string (*)(const ReadRecord& record); + +struct WireCase{ + // A record to read, and which kind it is. + std::string_view name; + struct Input{ + Record record = Record::STEP; + std::string_view json; + }; + + // What reading it gives: a record the check accepts, or a rejection. + struct Expectation{ + ReadCheck check = nullptr; + bool rejected = false; + }; + + Input input; + Expectation expectation; +}; + +std::string expect(bool ok, std::string_view what){ + return ok ? "" : std::format("Expected {}.", what); +} + +const StoryStep& step_of(const ReadRecord& record){ + return std::get(record); +} + +const WireCase CASES[] = { + {.name = "no args", .input = {.json = R"({"id":"talk","kind":"talk"})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryStep& step = step_of(record); + return expect(step.name == "talk" && step.kind == StoryStepKind::TALK && step.args.empty() && !step.pose_after, "a bare talk step"); + }}}, + {.name = "all shared fields", .input = {.json = R"({"id":"all","kind":"game_action","why":"source reason","action":"profile","skip_if":["flag"],"declared_after":{"map":"B","tiles":[[0,0],[1,0]],"facing":"east"}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryStep& step = step_of(record); + const DeclaredPose after = TileDeclared{.map = "B", .tiles = {{0, 0}, {1, 0}}, .facing = Direction::EAST}; + return expect(step.kind == StoryStepKind::GAME && step.why == "source reason" && step.action == "profile" + && step.skip_if == std::vector{"flag"} && step.pose_after == after, "every shared field read"); + }}}, + {.name = "once per save", .input = {.json = R"({"id":"heal","kind":"game_action","action":"profile","once_per_save":true})"}, .expectation = {.check = [](const ReadRecord& record){ + return expect(step_of(record).once_per_save, "a once_per_save step"); + }}}, + {.name = "every time by default", .input = {.json = R"({"id":"heal","kind":"game_action","action":"profile"})"}, .expectation = {.check = [](const ReadRecord& record){ + return expect(!step_of(record).once_per_save, "a step run every time"); + }}}, + {.name = "route fills its fallback", .input = {.json = R"({"id":"r","kind":"route","args":{"target":{"map":"A","tiles":[[1,2]]}}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"fight_wild", false}, {"target", GridPose{.map = "A", .tiles = {{1, 2}}, .facing = std::nullopt}}}; + return expect(step_of(record).args == expected, "the target and fight_wild false"); + }}}, + {.name = "legs", .input = {.json = R"({"id":"l","kind":"legs","action":"legs","args":{"legs":[{"direction":"south","tiles":2}],"fight_wild":true}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"fight_wild", true}, {"legs", std::vector{{.direction = Direction::SOUTH, .tiles = 2}}}}; + return expect(step_of(record).args == expected, "one south leg of 2 tiles"); + }}}, + {.name = "direction", .input = {.json = R"({"id":"s","kind":"step","args":{"direction":"west"}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"direction", Direction::WEST}}; + return expect(step_of(record).args == expected, "direction west"); + }}}, + {.name = "items", .input = {.json = R"({"id":"s","kind":"shop","args":{"items":[{"item":"potion","quantity":5}]}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"items", std::vector{{.item = "potion", .quantity = 5}}}}; + return expect(step_of(record).args == expected, "5 potions"); + }}}, + {.name = "game args", .input = {.json = R"({"id":"buy","kind":"game_action","action":"mart","args":{"map":"CeruleanCity_Mart","budget":3000,"if_present":true}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"budget", int64_t(3000)}, {"if_present", true}, {"map", std::string("CeruleanCity_Mart")}}; + return expect(step_of(record).args == expected, "the Mart args"); + }}}, + {.name = "game words", .input = {.json = R"({"id":"buy","kind":"game_action","action":"mart","args":{"map":"M","budget":1,"skip":["a","b"]}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"budget", int64_t(1)}, {"if_present", false}, {"map", std::string("M")}, {"skip", std::vector{"a", "b"}}}; + return expect(step_of(record).args == expected, "the words and if_present false"); + }}}, + {.name = "game integer rows", .input = {.json = R"({"id":"w","kind":"game_action","action":"walk","args":{"legs":[[0,4500],[-90,0],[]]}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"legs", std::vector>{{0, 4500}, {-90, 0}, {}}}}; + return expect(step_of(record).args == expected, "three rows, the last empty"); + }}}, + {.name = "timed legs", .input = {.json = R"({"id":"w","kind":"game_action","action":"timed_walk","args":{"legs":[[0,4500],[-90,1200]]}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryActionArgs expected = {{"legs", std::vector{{.turn = 0, .ms = 4500}, {.turn = -90, .ms = 1200}}}}; + return expect(step_of(record).args == expected, "two timed legs"); + }}}, + {.name = "unknown facing stays absent", .input = {.record = Record::POSE, .json = R"({"map":"M","tiles":[[0,0]]})"}, .expectation = {.check = [](const ReadRecord& record){ + return expect(std::get(record) == GridPose{.map = "M", .tiles = {{0, 0}}, .facing = std::nullopt}, "one tile, no facing"); + }}}, + {.name = "no tiles", .input = {.record = Record::POSE, .json = R"({"map":"M","tiles":[]})"}, .expectation = {.check = [](const ReadRecord& record){ + return expect(std::get(record).tiles.empty(), "no tiles"); + }}}, + {.name = "declared tile pose", .input = {.record = Record::DECLARED, .json = R"({"map":"M","tiles":[[1,2]],"facing":"north"})"}, .expectation = {.check = [](const ReadRecord& record){ + const DeclaredPose expected = TileDeclared{.map = "M", .tiles = {{1, 2}}, .facing = Direction::NORTH}; + return expect(std::get(record) == expected, "a tile pose facing north"); + }}}, + {.name = "declared place", .input = {.record = Record::DECLARED, .json = R"({"place":"LumioseCity","spot":"HotelZ","heading":90})"}, .expectation = {.check = [](const ReadRecord& record){ + const DeclaredPose expected = ZoneDeclared{.place = "LumioseCity", .spot = "HotelZ", .heading = 90}; + return expect(std::get(record) == expected, "a zone pose with spot and heading"); + }}}, + {.name = "declared place alone", .input = {.record = Record::DECLARED, .json = R"({"place":"HotelZ"})"}, .expectation = {.check = [](const ReadRecord& record){ + const DeclaredPose expected = ZoneDeclared{.place = "HotelZ", .spot = std::nullopt, .heading = std::nullopt}; + return expect(std::get(record) == expected, "a zone pose alone"); + }}}, + {.name = "checkpoint starting at a place", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"03.01","title":"Lobby","start":{"place":"HotelZ"},"events":[{"id":"down","kind":"scene","declared_after":{"place":"HotelZLobby","heading":180}}]})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + const DeclaredPose start = ZoneDeclared{.place = "HotelZ", .spot = std::nullopt, .heading = std::nullopt}; + return expect(checkpoint.start == start && checkpoint.steps.size() == 1 && checkpoint.steps[0].kind == StoryStepKind::MASH, "a zone start and one scene"); + }}}, + {.name = "ordered checkpoint", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"00.05","title":"Parcel","events":[ {"id":"first","kind":"talk"}, {"id":"second","kind":"scene"} ]})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + return expect(checkpoint.id == "00.05" && checkpoint.title == "Parcel" && !checkpoint.start && checkpoint.steps.size() == 2 + && checkpoint.steps[0].name == "first" && checkpoint.steps[1].name == "second" + && checkpoint.steps_json == R"([{"id":"first","kind":"talk"},{"id":"second","kind":"scene"}])", "two steps in order and their compact JSON"); + }}}, + {.name = "checkpoint postconditions", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[],"metadata":{"phase":"reproduction","postconditions":{"position":{"map":"M","tiles":[[3,4]]},"items":[{"item":"LIFT_KEY","quantity":1}],"flags":["f"]}}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + const StoryPostconditions& post = checkpoint.postconditions; + // Named, not temporaries in the comparison: GCC's -Wdangling-pointer + // flags the braced vector temporaries there. + const GridPose position{.map = "M", .tiles = {{3, 4}}, .facing = std::nullopt}; + const std::vector items{{.item = "LIFT_KEY", .quantity = 1}}; + const std::vector flags{"f"}; + return expect(checkpoint.metadata.phase == StoryPhase::REPRODUCTION + && post.position == position && post.items == items && post.flags == flags, + "the phase, position, item and flag"); + }}}, + {.name = "integer rows, not rows", .input = {.json = R"({"id":"w","kind":"game_action","action":"walk","args":{"legs":[0,4500]}})"}, .expectation = {.rejected = true}}, + {.name = "integer rows, fraction", .input = {.json = R"({"id":"w","kind":"game_action","action":"walk","args":{"legs":[[0,4.5]]}})"}, .expectation = {.rejected = true}}, + {.name = "timed leg of three numbers", .input = {.json = R"({"id":"w","kind":"game_action","action":"timed_walk","args":{"legs":[[0,4500,1]]}})"}, .expectation = {.rejected = true}}, + {.name = "unknown arg", .input = {.json = R"({"id":"a","kind":"game_action","action":"mart","args":{"map":"M","budget":1,"budgte":1}})"}, .expectation = {.rejected = true}}, + {.name = "missing required arg", .input = {.json = R"({"id":"a","kind":"game_action","action":"mart","args":{"map":"M"}})"}, .expectation = {.rejected = true}}, + {.name = "route without target", .input = {.json = R"({"id":"a","kind":"route"})"}, .expectation = {.rejected = true}}, + {.name = "args on a kind with none", .input = {.json = R"({"id":"a","kind":"talk","args":{"yes":true}})"}, .expectation = {.rejected = true}}, + {.name = "game step without action", .input = {.json = R"({"id":"a","kind":"game_action"})"}, .expectation = {.rejected = true}}, + {.name = "unknown action name", .input = {.json = R"({"id":"a","kind":"game_action","action":"dance"})"}, .expectation = {.rejected = true}}, + {.name = "fractional arg", .input = {.json = R"({"id":"a","kind":"game_action","action":"mart","args":{"map":"M","budget":1.5}})"}, .expectation = {.rejected = true}}, + {.name = "args not an object", .input = {.json = R"({"id":"a","kind":"game_action","action":"mart","args":["map"]})"}, .expectation = {.rejected = true}}, + {.name = "old field", .input = {.json = R"({"id":"a","kind":"battle","may_lose":true})"}, .expectation = {.rejected = true}}, + {.name = "old variant", .input = {.json = R"({"id":"a","kind":"game_action","variant":"mart"})"}, .expectation = {.rejected = true}}, + {.name = "unknown field", .input = {.json = R"({"id":"a","kind":"talk","mystery":0})"}, .expectation = {.rejected = true}}, + {.name = "unknown kind", .input = {.json = R"({"id":"a","kind":"magic"})"}, .expectation = {.rejected = true}}, + {.name = "boolean count", .input = {.json = R"({"id":"a","kind":"train","args":{"battles":false}})"}, .expectation = {.rejected = true}}, + {.name = "wrong bool", .input = {.json = R"({"id":"a","kind":"answer","args":{"yes":0}})"}, .expectation = {.rejected = true}}, + {.name = "old pose", .input = {.record = Record::POSE, .json = R"({"map":"M","certainty":"unknown","where":{"kind":"unknown"}})"}, .expectation = {.rejected = true}}, + {.name = "bad coordinate", .input = {.record = Record::POSE, .json = R"({"map":"M","tiles":[[0,true]]})"}, .expectation = {.rejected = true}}, + {.name = "declared map and place", .input = {.record = Record::DECLARED, .json = R"({"map":"M","place":"HotelZ"})"}, .expectation = {.rejected = true}}, + {.name = "declared place with tiles", .input = {.record = Record::DECLARED, .json = R"({"place":"HotelZ","tiles":[[1,2]]})"}, .expectation = {.rejected = true}}, + {.name = "declared map with heading", .input = {.record = Record::DECLARED, .json = R"({"map":"M","heading":90})"}, .expectation = {.rejected = true}}, + {.name = "declared neither", .input = {.record = Record::DECLARED, .json = R"({"spot":"Lobby"})"}, .expectation = {.rejected = true}}, + {.name = "duplicate events", .input = {.record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[{"id":"a","kind":"talk"},{"id":"a","kind":"talk"}]})"}, .expectation = {.rejected = true}}, +}; + + +// The built-in actions and a game's: a Mart step (GAME "mart") and a +// profile check that takes no args. +std::vector test_actions(){ + std::vector actions(builtin_story_actions().begin(), builtin_story_actions().end()); + actions.push_back({.kind = StoryStepKind::GAME, .name = "mart", .args = { + {.key = "map", .type = StoryArgType::WORD, .required = true, .fallback = std::nullopt, .why = "the Mart's map"}, + {.key = "budget", .type = StoryArgType::INTEGER, .required = true, .fallback = std::nullopt, .why = "money to spend"}, + {.key = "if_present", .type = StoryArgType::BOOLEAN, .required = false, .fallback = false, .why = ""}, + {.key = "skip", .type = StoryArgType::WORDS, .required = false, .fallback = std::nullopt, .why = ""}, + }}); + actions.push_back({.kind = StoryStepKind::GAME, .name = "walk", .args = { + {.key = "legs", .type = StoryArgType::INTEGER_ROWS, .required = true, .fallback = std::nullopt, .why = "rows of numbers"}, + }}); + actions.push_back({.kind = StoryStepKind::GAME, .name = "timed_walk", .args = { + {.key = "legs", .type = StoryArgType::TIMED_LEGS, .required = true, .fallback = std::nullopt, .why = "[turn degrees, ms] legs"}, + }}); + actions.push_back({.kind = StoryStepKind::GAME, .name = "profile", .args = {}}); + return actions; +} + + +// `input` read, with `source` naming it in parse errors. +ReadRecord read_record(const WireCase::Input& input, std::string_view source){ + static const std::vector actions = test_actions(); + const JsonValue value = parse_json(std::string(input.json)); + switch (input.record){ + case Record::POSE: + return read_grid_pose(value, source); + case Record::DECLARED: + return read_declared_pose(value, source); + case Record::STEP: + return read_story_step(value, source, actions); + case Record::CHECKPOINT: + return read_story_checkpoint(value, source, actions); + } + throw ParseException("Unknown test record."); +} + +// "" when `test` reads as expected, else what differs. +std::string check_case(const WireCase& test){ + try{ + const ReadRecord record = read_record(test.input, test.name); + if (test.expectation.rejected){ + return "Expected rejection, read accepted record."; + } + return test.expectation.check(record); + }catch (const ParseException& error){ + return test.expectation.rejected ? "" : std::format("Unexpected parse failure: {}", error.message()); + } +} + + +#ifndef PA_STORY_DATA_STANDALONE + +class StoryJsonTest : public UnitTest{ +public: + explicit StoryJsonTest(WireCase test) + : UnitTest(std::format("Pokemon::StoryStepJson - {}", test.name)) + , m_case(test) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string error = check_case(m_case); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } + +private: + WireCase m_case; +}; + +#endif + + +} // namespace + + +#ifndef PA_STORY_DATA_STANDALONE + +void add_tests_StoryStepJson(UnitTestDatabase& database){ + for (const WireCase& test : CASES){ + database.add(test); + } +} + +#else + +size_t run_story_step_json_cases(){ + size_t failed = 0; + for (const WireCase& test : CASES){ + const std::string error = check_case(test); + std::cout << test.name << ": " << (error.empty() ? "PASS" : error) << '\n'; + failed += !error.empty(); + } + return failed; +} + +#endif + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h new file mode 100644 index 0000000000..507d670981 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h @@ -0,0 +1,30 @@ +/* Story Step JSON Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStepJson_Tests_H +#define PokemonAutomation_Pokemon_StoryStepJson_Tests_H + +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the lossless shared story-data wire contract. +void add_tests_StoryStepJson(UnitTestDatabase& database); + +#ifdef PA_STORY_DATA_STANDALONE +// Standalone StoryDataTests only: runs the built-in cases, prints one line +// per case, returns how many failed. +size_t run_story_step_json_cases(); +#endif + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.cpp new file mode 100644 index 0000000000..898504d384 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.cpp @@ -0,0 +1,79 @@ +/* Builtin Story Actions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Pokemon_BuiltinStoryActions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +StoryArgSpec required(std::string key, StoryArgType type, std::string why){ + return StoryArgSpec{.key = std::move(key), .type = type, .required = true, .fallback = std::nullopt, .why = std::move(why)}; +} + +StoryArgSpec optional(std::string key, StoryArgType type, StoryArgValue fallback, std::string why){ + return StoryArgSpec{.key = std::move(key), .type = type, .required = false, .fallback = std::move(fallback), .why = std::move(why)}; +} + +std::vector make_builtin_actions(){ + const StoryArgSpec fight_wild = optional("fight_wild", StoryArgType::BOOLEAN, false, "fight wild battles on the way instead of running"); + return { + {.kind = StoryStepKind::ROUTE, .name = "route", .args = { + required("target", StoryArgType::GRID_POSE, "where to go; with several tiles, any of them"), + fight_wild, + }}, + {.kind = StoryStepKind::READY, .name = "ready", .args = { + required("target", StoryArgType::GRID_POSE, "the nurse"), + }}, + {.kind = StoryStepKind::LEGS, .name = "legs", .args = { + required("legs", StoryArgType::LEGS, "the straight legs to walk"), + fight_wild, + }}, + {.kind = StoryStepKind::STEP, .name = "face", .args = { + required("direction", StoryArgType::DIRECTION, "the way to step or face"), + }}, + {.kind = StoryStepKind::ANSWER, .name = "answer", .args = { + optional("yes", StoryArgType::BOOLEAN, true, "the answer"), + }}, + {.kind = StoryStepKind::BATTLE, .name = "fight", .args = { + optional("may_lose", StoryArgType::BOOLEAN, false, "losing goes on (a rival's first battle)"), + }}, + {.kind = StoryStepKind::TRAIN, .name = "train", .args = { + required("battles", StoryArgType::INTEGER, "the battles to fight"), + }}, + {.kind = StoryStepKind::SHOP, .name = "shop", .args = { + required("items", StoryArgType::ITEMS, "the items and how many of each"), + }}, + }; +} + + +} // namespace + + +std::span builtin_story_actions(){ + static const std::vector actions = make_builtin_actions(); + return actions; +} + +const StoryActionSpec* find_story_action(std::span actions, StoryStepKind kind, std::string_view name){ + for (const StoryActionSpec& action : actions){ + if (action.kind == kind && (name.empty() || action.name == name)){ + return &action; + } + } + return nullptr; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h new file mode 100644 index 0000000000..a13a29cfec --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h @@ -0,0 +1,66 @@ +/* Builtin Story Actions + * + * From: https://github.com/PokemonAutomation/ + * + * The shared engine's built-in actions (a route, fixed legs, a battle, a + * shop...) with the args each takes, and reading a step's args. A game + * adds its own actions (GAME steps and its other ways of doing a kind) to + * these when it loads its tables. + * + */ + +#ifndef PokemonAutomation_Pokemon_BuiltinStoryActions_H +#define PokemonAutomation_Pokemon_BuiltinStoryActions_H + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_MapUtil.h" +#include "Types/Pokemon_StoryActionArg.h" +#include "Types/Pokemon_StoryActionSpec.h" +#include "Types/Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The built-in actions: each kind's usual way. A kind's first one is its +// default, the action of a step that names none. +// route ROUTE target GRID_POSE (required), fight_wild BOOLEAN (false) +// ready READY target GRID_POSE (required): the nurse +// legs LEGS legs LEGS (required), fight_wild BOOLEAN (false) +// face STEP direction DIRECTION (required) +// answer ANSWER yes BOOLEAN (true) +// fight BATTLE may_lose BOOLEAN (false) +// train TRAIN battles INTEGER (required) +// shop SHOP items ITEMS (required) +// Other kinds (TALK, MASH, HEAL, SAVE, ...) take no args. +std::span builtin_story_actions(); + +// The action of `kind` named `name` among `actions`; for an empty name, +// the kind's first. Null when there is none. +const StoryActionSpec* find_story_action(std::span actions, StoryStepKind kind, std::string_view name); + +// The value of arg `key`, which the step's action requires or gives a +// fallback, so the loaded step has it. Throws InternalProgramError when it +// is missing or of another type: a step built without its action's spec. +template +const Type& story_arg(const StoryActionArgs& args, std::string_view key); + + +template +const Type& story_arg(const StoryActionArgs& args, std::string_view key){ + const Type* value = value_if_at_it(args, args.find(key)); + if (value == nullptr){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("Missing or mistyped story arg: {}", key)); + } + return *value; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_MapUtil.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_MapUtil.h new file mode 100644 index 0000000000..f9be88108b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_MapUtil.h @@ -0,0 +1,44 @@ +/* Map Util + * + * From: https://github.com/PokemonAutomation/ + * + * Lookups in a map through the iterator find() returned, so a call site + * says which lookup it does and never copies the value by accident: + * const int64_t* budget = value_if_at_it(args, args.find("budget")); + * + */ + +#ifndef PokemonAutomation_Pokemon_MapUtil_H +#define PokemonAutomation_Pokemon_MapUtil_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The value at `it`, or null when `it` is `map`'s end. +template +const typename Map::mapped_type* value_at_it(const Map& map, typename Map::const_iterator it); + +// The `Type` alternative of the variant at `it`, or null when `it` is +// `map`'s end or the variant holds another type. +template +const Type* value_if_at_it(const Map& map, typename Map::const_iterator it); + + +template +const typename Map::mapped_type* value_at_it(const Map& map, typename Map::const_iterator it){ + return it == map.end() ? nullptr : &it->second; +} + +template +const Type* value_if_at_it(const Map& map, typename Map::const_iterator it){ + return it == map.end() ? nullptr : std::get_if(&it->second); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryCheckpointTypes.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryCheckpointTypes.h new file mode 100644 index 0000000000..79e540b467 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryCheckpointTypes.h @@ -0,0 +1,86 @@ +/* Story Checkpoint Types + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_StoryEvents.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryCheckpointTypes_H +#define PokemonAutomation_Pokemon_StoryCheckpointTypes_H + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon_StoryLog.h" +#include "Pokemon_StoryEvent.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Pose confidence adjustment following an event interruption. +enum class InterruptPose{ + UNCHANGED, // Cleared where we stood (a talk-only trainer). + WITHIN_SET, // Moved an unknown part of a leg: still within the position we had, no longer exactly where. + LOST, // Anywhere. +}; +// Policy defining how an interrupted event should be resumed. +enum class ResumePolicy{ + RETRY_EVENT, // Run the event again, from its skip_if. + RECHECK_EXPECT, // The action may have finished: done if its expects hold, else retry. + STOP, // Stop the checkpoint. +}; + +// Something that can stop an action part-way. +struct Interrupt{ + std::string name; + Check detect; + Act handle; + InterruptPose pose = InterruptPose::UNCHANGED; + ResumePolicy resume = ResumePolicy::RETRY_EVENT; +}; +// Writes what an interrupt did (`effect`) into `pose`. +void apply_interrupt_pose(InterruptPose effect, Pose& pose); + + +// Story milestone containing pre/post conditions and a series of events. +struct Checkpoint{ + std::string id; + // Must hold before the first event (the save it starts from). + std::vector start; + std::vector interrupts; + std::vector events; + // Must hold after the last event. + std::vector end; + // Saves the game after the end check, if set. + Act save; + size_t max_interrupts_per_event = 5; +}; + + +// Result report from executing a checkpoint. +struct CheckpointReport{ + bool completed = false; + // 1-based number of the event that failed; 0 for the start or end check + // or the save, or when nothing failed. + size_t failed_event = 0; + std::string failed_name; + Outcome failure; + size_t events_run = 0; + size_t events_skipped = 0; +}; + +// Callback receiver for story event execution log messages. +using EventLogger = MoveOnlyFunction; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h new file mode 100644 index 0000000000..ffda3cee12 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h @@ -0,0 +1,90 @@ +/* Story Event + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_StoryEvents.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryEvent_H +#define PokemonAutomation_Pokemon_StoryEvent_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon_StoryLog.h" +#include "Pokemon_StoryOutcome.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Predicate callable evaluating current run state. +using Check = MoveOnlyFunction; + +// A question the screen (or the run state) answers, named for the log. +struct Condition{ + std::string name; + Check check; +}; +// Constructs a named Condition from a predicate check. +Condition condition(std::string name, Check check); + +// Holds while the pose is on `map` (any map if empty) and at least as +// certain as `need`. +Condition pose_known(std::string map, PoseCertainty need); + + +// Strategy for recovering from a failed event. +enum class RecoveryKind{ + WAIT, // Something transient (a wanderer, a slow scene): wait, try again. + REANCHOR, // The pose is in doubt: confirm it on a landmark, try again. + STOP, // Nothing to do: stop the checkpoint. +}; +// Returns the readable name of a recovery strategy. +std::string recovery_name(RecoveryKind kind); + +// Answers a failure named `on` (any failure if empty): runs `prepare`, if +// any, and tries the event again, up to `attempts` times. +struct Recovery{ + std::string on; + RecoveryKind kind = RecoveryKind::STOP; + Act prepare; + size_t attempts = 1; + std::string why; +}; + + +// Single executable story action with preconditions, recovery steps, and postconditions. +struct Event{ + std::string name; + std::string why; + // Skipped when all of these hold (and there is at least one). + std::vector skip_if; + // Run when the event is skipped: what the event leaves in the run + // state that is already so (a door it opens, a flag it sets). + std::function when_skipped; + // Must hold before `act`; a failure is "require_failed". + std::vector require; + Act act; + // Must hold after `act`; a failure is "expect_failed". + std::vector expect; + // Written to the run's pose once the event succeeds. An action that + // learns its pose as it goes (the row that answered) returns it in + // its Outcome instead. + std::optional pose_learned; + // In order of escalation. + std::vector recoveries; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp new file mode 100644 index 0000000000..1dd6975bff --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp @@ -0,0 +1,578 @@ +/* Story Events + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_StoryOutcomeClass.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string event_log_line(std::string_view checkpoint, size_t number, std::string_view event, std::string_view status){ + return std::format("[Event] {}/{} {}: {}", checkpoint, number, event, status); +} + +std::string checkpoint_log_line(std::string_view checkpoint, std::string_view text){ + return std::format("[Checkpoint] {}: {}", checkpoint, text); +} + +std::string certainty_name(PoseCertainty certainty){ + switch (certainty){ + case PoseCertainty::TILE: + return "tile"; + case PoseCertainty::COLUMN: + return "column"; + case PoseCertainty::ROW: + return "row"; + case PoseCertainty::SET: + return "set"; + case PoseCertainty::UNKNOWN: + return "unknown"; + } + return "?"; +} + +bool certainty_covers(PoseCertainty have, PoseCertainty need){ + switch (need){ + case PoseCertainty::UNKNOWN: + return true; + case PoseCertainty::SET: + return have != PoseCertainty::UNKNOWN; + case PoseCertainty::COLUMN: + case PoseCertainty::ROW: + return have == need || have == PoseCertainty::TILE; + case PoseCertainty::TILE: + return have == PoseCertainty::TILE; + } + return false; +} + +std::string to_string(const Pose& pose){ + std::string text = pose.map.empty() ? "?" : pose.map; + if (pose.where){ + const std::string where = pose.where->describe(); + if (!where.empty()){ + text += std::format(" {}", where); + } + } + return std::format("{} ({})", text, certainty_name(pose.certainty)); +} + + +bool Outcome::succeeded() const{ + return failure.empty(); +} +Outcome outcome_ok(std::optional pose){ + Outcome outcome; + outcome.pose = std::move(pose); + return outcome; +} + +Outcome outcome_unchanged(){ + Outcome outcome; + outcome.changed_nothing = true; + return outcome; +} + +Outcome outcome_failed(std::string failure, std::string detail, std::optional failure_class){ + Outcome outcome; + outcome.failure = std::move(failure); + outcome.detail = std::move(detail); + outcome.failure_class = failure_class; + return outcome; +} +std::string to_string(const Outcome& outcome){ + return outcome.detail.empty() ? outcome.failure : std::format("{}: {}", outcome.failure, outcome.detail); +} + +Outcome outcome_game_not_running(){ + return outcome_failed(std::string(GAME_NOT_RUNNING), "the game is not running: the Switch HOME menu is showing"); +} + +Condition condition(std::string name, Check check){ + return Condition{std::move(name), std::move(check)}; +} + +Condition pose_known(std::string map, PoseCertainty need){ + std::string name = std::format("pose {}{}", certainty_name(need), map.empty() ? "" : std::format(" on {}", map)); + return condition(std::move(name), [map = std::move(map), need](RunState& state){ + return (map.empty() || state.pose.map == map) && certainty_covers(state.pose.certainty, need); + }); +} + +std::string recovery_name(RecoveryKind kind){ + switch (kind){ + case RecoveryKind::WAIT: + return "wait"; + case RecoveryKind::REANCHOR: + return "re-anchor"; + case RecoveryKind::STOP: + return "stop"; + } + return "?"; +} + + +namespace{ + +// Runs an action; if it succeeded knowing where it left the player, that +// becomes the run's pose. +Outcome run_act(Act& act, RunState& state){ + Outcome outcome = act(state); + if (outcome.succeeded() && outcome.pose){ + state.pose = *outcome.pose; + } + return outcome; +} + +// The name of the first condition that does not hold. +std::optional first_failing(std::vector& conditions, RunState& state){ + for (Condition& item : conditions){ + if (!item.check(state)){ + return item.name; + } + } + return std::nullopt; +} + +bool already_done(Event& event, RunState& state){ + return !event.skip_if.empty() && !first_failing(event.skip_if, state); +} + +Outcome check_expects(Event& event, RunState& state){ + std::optional failing = first_failing(event.expect, state); + if (failing){ + return outcome_failed("expect_failed", *failing); + } + if (event.pose_learned){ + state.pose = *event.pose_learned; + } + return outcome_ok(); +} + +Outcome attempt_event(Event& event, RunState& state){ + std::optional failing = first_failing(event.require, state); + if (failing){ + return outcome_failed("require_failed", *failing); + } + Outcome outcome = run_act(event.act, state); + if (!outcome.succeeded()){ + return outcome; + } + return check_expects(event, state); +} + +} // namespace + +void apply_interrupt_pose(InterruptPose effect, Pose& pose){ + switch (effect){ + case InterruptPose::UNCHANGED: + return; + case InterruptPose::WITHIN_SET: + if (pose.certainty != PoseCertainty::UNKNOWN){ + pose.certainty = PoseCertainty::SET; + } + return; + case InterruptPose::LOST: + pose.where.reset(); + pose.certainty = PoseCertainty::UNKNOWN; + return; + } +} + +namespace{ + + +// One event being run, with what it has used up. +struct EventRun{ + Checkpoint& checkpoint; + size_t number; + Event& event; + RunState& state; + EventLogger& log; + std::vector recoveries_used; + size_t interrupts = 0; +}; + +void log_status(const std::string& status, EventRun& run){ + run.log(event_log_line(run.checkpoint.id, run.number, run.event.name, status)); +} + + +// What the interrupts showing after an action ask for. +struct InterruptResult{ + bool fired = false; + ResumePolicy resume = ResumePolicy::RECHECK_EXPECT; + Outcome outcome; +}; + +// The policy that asks for more: STOP over RETRY_EVENT over RECHECK_EXPECT. +ResumePolicy stronger(ResumePolicy x, ResumePolicy y){ + if (x == ResumePolicy::STOP || y == ResumePolicy::STOP){ + return ResumePolicy::STOP; + } + if (x == ResumePolicy::RETRY_EVENT || y == ResumePolicy::RETRY_EVENT){ + return ResumePolicy::RETRY_EVENT; + } + return ResumePolicy::RECHECK_EXPECT; +} + +// Clears every interrupt showing. +InterruptResult clear_interrupts(EventRun& run){ + InterruptResult result; + for (Interrupt& interrupt : run.checkpoint.interrupts){ + if (!interrupt.detect(run.state)){ + continue; + } + run.interrupts++; + log_status(std::format("interrupt: {}", interrupt.name), run); + if (run.interrupts > run.checkpoint.max_interrupts_per_event){ + result.outcome = outcome_failed("too_many_interrupts", interrupt.name); + return result; + } + if (interrupt.handle){ + Outcome handled = run_act(interrupt.handle, run.state); + if (!handled.succeeded()){ + result.outcome = outcome_failed("interrupt_failed", std::format("{}: {}", interrupt.name, to_string(handled))); + return result; + } + } + apply_interrupt_pose(interrupt.pose, run.state.pose); + result.resume = result.fired ? stronger(result.resume, interrupt.resume) : interrupt.resume; + result.fired = true; + } + return result; +} + + +// The next recovery for `failure`, using up one of its attempts. +Recovery* next_recovery(const std::string& failure, EventRun& run){ + std::vector& recoveries = run.event.recoveries; + for (size_t c = 0; c < recoveries.size(); c++){ + Recovery& recovery = recoveries[c]; + if (!recovery.on.empty() && recovery.on != failure){ + continue; + } + if (recovery.kind != RecoveryKind::STOP && run.recoveries_used[c] >= recovery.attempts){ + continue; + } + run.recoveries_used[c]++; + return &recovery; + } + return nullptr; +} + +// Answers `failure` with the event's recoveries. Returns nothing to try the +// event again, or the failure that stops it. A recovery that fails itself +// is answered in turn, so escalation goes on from there. +std::optional recover(Outcome failure, EventRun& run){ + while (true){ + if (failure.failure == GAME_NOT_RUNNING){ + return failure; + } + Recovery* recovery = next_recovery(failure.failure, run); + if (recovery == nullptr){ + return failure; + } + std::string line = std::format("recover: {} ({})", recovery_name(recovery->kind), failure.failure); + log_status(recovery->why.empty() ? line : std::format("{}: {}", line, recovery->why), run); + if (recovery->kind == RecoveryKind::STOP){ + return failure; + } + if (!recovery->prepare){ + return std::nullopt; + } + Outcome prepared = run_act(recovery->prepare, run.state); + if (prepared.succeeded()){ + return std::nullopt; + } + failure = std::move(prepared); + } +} + + +enum class Next{ + DONE, + RETRY, + RECOVER, + STOP, +}; + +// After one attempt: what the interrupts showing and the outcome call for. +// `outcome` becomes the failure to recover from or stop on. +Next after_attempt(EventRun& run, Outcome& outcome){ + InterruptResult interrupted = clear_interrupts(run); + if (!interrupted.outcome.succeeded()){ + outcome = std::move(interrupted.outcome); + return Next::STOP; + } + if (interrupted.fired){ + switch (interrupted.resume){ + case ResumePolicy::STOP: + outcome = outcome_failed("interrupted", "stopped by an interrupt"); + return Next::STOP; + case ResumePolicy::RETRY_EVENT: + return Next::RETRY; + case ResumePolicy::RECHECK_EXPECT: + outcome = check_expects(run.event, run.state); + return outcome.succeeded() ? Next::DONE : Next::RETRY; + } + } + return outcome.succeeded() ? Next::DONE : Next::RECOVER; +} + +// Runs one event to success or to the failure that stops it. +Outcome run_event(EventRun& run){ + log_status("start", run); + for (bool first = true; ; first = false){ + if (!first && already_done(run.event, run.state)){ + log_status("done: already showing", run); + return outcome_ok(); + } + Outcome outcome = attempt_event(run.event, run.state); + Next next = after_attempt(run, outcome); + if (next == Next::DONE){ + log_status("done", run); + return outcome_ok(); + } + if (next == Next::RETRY){ + continue; + } + if (next == Next::RECOVER){ + std::optional stop = recover(std::move(outcome), run); + if (!stop){ + continue; + } + outcome = std::move(*stop); + } + log_status(std::format("failed: {}", to_string_with_class(outcome)), run); + return outcome; + } +} + + +// What the exception being handled says, for a log line, with its class +// when the engine knows it. +std::string current_exception_text(){ + try{ + throw; + }catch (OperationFailedException& e){ + return std::format("{}: {} ({})", e.name(), e.message(), story_failure_class_tag(StoryFailureClass::OPERATION_FAILED)); + }catch (Exception& e){ + return std::format("{}: {}", e.name(), e.message()); + }catch (std::exception& e){ + return e.what(); + }catch (...){ + return "unknown exception"; + } +} + +// run_event(), logging the event and its checkpoint as failed before an +// exception from the game's steps leaves the runner. The exception goes +// on: the game decides what it means. +Outcome run_event_logging_throws(EventRun& run){ + try{ + return run_event(run); + }catch (...){ + const std::string what = current_exception_text(); + log_status(std::format("failed: {}", what), run); + run.log(checkpoint_log_line(run.checkpoint.id, std::format("failed at {} {}: {}", run.number, run.event.name, what))); + throw; + } +} + +CheckpointReport stop_checkpoint(EventLogger& log, const std::string& id, Outcome failure, CheckpointReport& report){ + std::string where = report.failed_event == 0 + ? "" + : std::format(" at {} {}", report.failed_event, report.failed_name); + log(checkpoint_log_line(id, std::format("failed{}: {}", where, to_string_with_class(failure)))); + report.failure = std::move(failure); + return report; +} + +Outcome finish_checkpoint(RunState& state, Checkpoint& checkpoint){ + std::optional failing = first_failing(checkpoint.end, state); + if (failing){ + return outcome_failed("end_failed", *failing); + } + if (!checkpoint.save){ + return outcome_ok(); + } + Outcome saved = run_act(checkpoint.save, state); + return saved.succeeded() ? saved : outcome_failed("save_failed", to_string(saved)); +} + +} // namespace + + +CheckpointReport run_checkpoint(RunState& state, Checkpoint& checkpoint, EventLogger& log){ + CheckpointReport report; + const std::string& id = checkpoint.id; + log(checkpoint_start_line(id, checkpoint.events.size())); + std::optional failing = first_failing(checkpoint.start, state); + if (failing){ + return stop_checkpoint(log, id, outcome_failed("start_failed", *failing), report); + } + for (size_t c = 0; c < checkpoint.events.size(); c++){ + Event& event = checkpoint.events[c]; + EventRun run{checkpoint, c + 1, event, state, log, std::vector(event.recoveries.size(), 0), 0}; + if (already_done(event, state)){ + log_status("skipped", run); + if (event.when_skipped){ + event.when_skipped(state); + } + report.events_skipped++; + continue; + } + report.events_run++; + Outcome outcome = run_event_logging_throws(run); + if (!outcome.succeeded()){ + report.failed_event = c + 1; + report.failed_name = event.name; + return stop_checkpoint(log, id, std::move(outcome), report); + } + } + Outcome finished = finish_checkpoint(state, checkpoint); + if (!finished.succeeded()){ + return stop_checkpoint(log, id, std::move(finished), report); + } + report.completed = true; + log(checkpoint_log_line(id, std::format("done, {} run, {} skipped", report.events_run, report.events_skipped))); + return report; +} + + +namespace{ + +void lint_conditions(const std::string& where, const std::vector& conditions, std::vector& problems){ + for (const Condition& item : conditions){ + if (item.name.empty() || !item.check){ + problems.emplace_back(std::format("{}: a condition without a name or a check", where)); + } + } +} + +void lint_recoveries(const Event& event, std::vector& problems){ + RecoveryKind last = RecoveryKind::WAIT; + for (const Recovery& recovery : event.recoveries){ + if ((int)recovery.kind < (int)last){ + problems.emplace_back(std::format( + "{}: recovery {} after {}", event.name, recovery_name(recovery.kind), recovery_name(last) + )); + } + if (recovery.kind != RecoveryKind::STOP && recovery.attempts == 0){ + problems.emplace_back(std::format("{}: recovery {} with no attempts", event.name, recovery_name(recovery.kind))); + } + last = recovery.kind; + } +} + +void lint_event(const Event& event, std::set& names, std::vector& problems){ + if (event.name.empty()){ + problems.emplace_back("an event without a name"); + }else if (!names.insert(event.name).second){ + problems.emplace_back(std::format("{}: two events with this name", event.name)); + } + if (!event.act){ + problems.emplace_back(std::format("{}: no action", event.name)); + } + lint_conditions(std::format("{} skip_if", event.name), event.skip_if, problems); + lint_conditions(std::format("{} require", event.name), event.require, problems); + lint_conditions(std::format("{} expect", event.name), event.expect, problems); + lint_recoveries(event, problems); +} + +} // namespace + + +std::vector lint_checkpoint(const Checkpoint& checkpoint){ + std::vector problems; + if (checkpoint.id.empty()){ + problems.emplace_back("a checkpoint without an id"); + } + if (checkpoint.events.empty()){ + problems.emplace_back(std::format("{}: no events", checkpoint.id)); + } + std::set names; + for (const Event& event : checkpoint.events){ + lint_event(event, names, problems); + } + for (const Interrupt& interrupt : checkpoint.interrupts){ + if (interrupt.name.empty() || !interrupt.detect){ + problems.emplace_back("an interrupt without a name or a detector"); + } + } + lint_conditions(std::format("{} start", checkpoint.id), checkpoint.start, problems); + lint_conditions(std::format("{} end", checkpoint.id), checkpoint.end, problems); + return problems; +} + + +namespace{ + +std::string names_of(const std::vector& conditions){ + std::string text; + for (const Condition& item : conditions){ + text += (text.empty() ? "" : ", ") + item.name; + } + return text; +} + +void describe_line(const std::string& indent, const std::string& label, const std::string& value, std::string& text){ + if (!value.empty()){ + text += std::format("{}{}: {}\n", indent, label, value); + } +} + +void describe_event(size_t number, const Event& event, std::string& text){ + text += std::format(" event {} {}{}\n", number, event.name, event.why.empty() ? "" : std::format(": {}", event.why)); + describe_line(" ", "skip_if", names_of(event.skip_if), text); + describe_line(" ", "require", names_of(event.require), text); + describe_line(" ", "expect", names_of(event.expect), text); + if (event.pose_learned){ + describe_line(" ", "pose_learned", to_string(*event.pose_learned), text); + } + for (const Recovery& recovery : event.recoveries){ + text += std::format( + " recovery: {} on {}{}{}\n", + recovery_name(recovery.kind), + recovery.on.empty() ? "any failure" : recovery.on, + recovery.kind == RecoveryKind::STOP ? "" : std::format(" x{}", recovery.attempts), + recovery.why.empty() ? "" : std::format(": {}", recovery.why) + ); + } +} + +} // namespace + + +std::string describe(const Checkpoint& checkpoint){ + std::string text = std::format("checkpoint {}: {} events\n", checkpoint.id, checkpoint.events.size()); + describe_line(" ", "start", names_of(checkpoint.start), text); + std::string interrupts; + for (const Interrupt& interrupt : checkpoint.interrupts){ + interrupts += (interrupts.empty() ? "" : ", ") + interrupt.name; + } + describe_line(" ", "interrupts", interrupts, text); + for (size_t c = 0; c < checkpoint.events.size(); c++){ + describe_event(c + 1, checkpoint.events[c], text); + } + describe_line(" ", "end", names_of(checkpoint.end), text); + if (checkpoint.save){ + text += " saves\n"; + } + return text; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h new file mode 100644 index 0000000000..860d7d5f45 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h @@ -0,0 +1,74 @@ +/* Story Events + * + * From: https://github.com/PokemonAutomation/ + * + * A story checkpoint as a list of events. Each event states what must hold + * before it (require), does one thing (act), and checks what the game shows + * afterwards (expect). An event whose effect is already on screen (skip_if) + * is skipped, so resuming a checkpoint after a reload re-checks instead of + * replaying. A failed event is answered by its named recoveries, in order + * of escalation (wait, then re-anchor, then stop), and anything without a + * recovery stops the checkpoint with the event and the reason. + * + * Interrupts (a wild battle, a trainer, a scene) are declared once per + * checkpoint: after each action the runner asks whether one is showing, + * clears it, marks what it did to the pose and resumes as it says. + * + * The run state is the runner's to change. An action that knows where it + * left the player says so in its Outcome, and the runner writes that into + * the pose once the action has succeeded. + * + * Observation and actuation are callables the game supplies, so this file + * knows nothing of any one game or console, and the runner can be tested + * against a scripted world. See docs/design/AutoStory-Event-Model.md. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryEvents_H +#define PokemonAutomation_Pokemon_StoryEvents_H + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon_StoryLog.h" +#include "Pokemon_StoryCheckpointTypes.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The runner's own log lines, beside the checkpoint lines of +// Pokemon_StoryLog.h. One event's line: +// [Event] 00.04/3 talk_mom: start +// [Event] 00.04/3 talk_mom: failed: expect_failed: has_parcel +std::string event_log_line(std::string_view checkpoint, size_t number, std::string_view event, std::string_view status); + +// Any other line about a checkpoint, such as how its run ended: +// [Checkpoint] 00.04: done, 3 run, 0 skipped +// [Checkpoint] 00.04: failed at 2 talk_mom: expect_failed: has_parcel +std::string checkpoint_log_line(std::string_view checkpoint, std::string_view text); + +// Problems an author should fix before running: unnamed or empty events, +// missing actions, recoveries out of escalation order. +std::vector lint_checkpoint(const Checkpoint& checkpoint); + +// A readable dump for review, one line per item: the checkpoint's start, +// interrupts and end by name, each event with its why, its conditions' +// names, its learned pose and its recoveries. Nothing runs. +std::string describe(const Checkpoint& checkpoint); + +// Runs the checkpoint's events in order, from the first. Events whose +// effect is already showing are skipped, so after a reload this resumes. +// Logs each event's start and end through `log`. +CheckpointReport run_checkpoint(RunState& state, Checkpoint& checkpoint, EventLogger& log); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp new file mode 100644 index 0000000000..3b54de788e --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp @@ -0,0 +1,771 @@ +/* Story Events Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The checkpoint runner against a scripted world: a few fields that the + * events' actions change and their checks read, instead of a console. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_StoryEvents_Tests.h" +#include "Pokemon_StoryOutcomeClass.h" +#include "Pokemon_TilePose.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// A small slice of Route 201/202 and the player's house. +struct World{ + std::string map = "Route 202"; + int potions = 0; + bool parcel = false; + bool dialogue_open = false; + bool battle_showing = false; + // Talks that open nothing before the NPC answers (she is wandering). + int talks_before_answer = 0; + // Rows between us and Mom; a talk from a row off reaches nobody. + int rows_off = 0; + // Walks that fail before one gets through. + int walk_failures = 0; + std::vector trace; +}; + +struct Lines{ + std::vector lines; + + EventLogger logger(){ + return [this](const std::string& line){ lines.push_back(line); }; + } + bool has(const std::string& line) const{ + return std::find(lines.begin(), lines.end(), line) != lines.end(); + } + std::string all() const{ + std::string text; + for (const std::string& line : lines){ + text += std::format("\n{}", line); + } + return text; + } +}; + +Event make_event(std::string name, Act act){ + Event event; + event.name = std::move(name); + event.act = std::move(act); + return event; +} + +// The pose, confirmed on a landmark. +Pose anchored(const Pose& pose){ + Pose anchored = pose; + anchored.certainty = PoseCertainty::TILE; + return anchored; +} + +Act record(std::string what, World& world){ + return [&world, what = std::move(what)](RunState&){ + world.trace.push_back(what); + return outcome_ok(); + }; +} + +Condition has_potions(World& world){ + return condition("potions in the Bag", [&world](RunState&){ return world.potions > 0; }); +} + +Condition dialogue_opened(World& world){ + return condition("dialogue opened", [&world](RunState&){ return world.dialogue_open; }); +} + +// The Poke Mart lady: answers once she has wandered back, gives 10 Potions. +Event talk_to_lady(World& world){ + Event event = make_event("talk_poke_mart_lady", [&world](RunState&){ + world.trace.push_back("talk"); + if (world.talks_before_answer > 0){ + world.talks_before_answer--; + return outcome_ok(); + } + world.dialogue_open = true; + world.potions += 10; + return outcome_ok(); + }); + event.skip_if.push_back(has_potions(world)); + event.expect.push_back(dialogue_opened(world)); + return event; +} + +Recovery recovery(std::string on, RecoveryKind kind, size_t attempts, Act prepare = nullptr){ + Recovery recovery; + recovery.on = std::move(on); + recovery.kind = kind; + recovery.attempts = attempts; + recovery.prepare = std::move(prepare); + return recovery; +} + +Checkpoint make_checkpoint(){ + Checkpoint checkpoint; + checkpoint.id = "00.04"; + return checkpoint; +} + + +UnitTestResult test_runs_events_in_order(){ + World world; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(make_event("walk_to_corner", record("walk", world))); + checkpoint.events.push_back(make_event("talk_lady", record("talk", world))); + checkpoint.events.push_back(make_event("save", record("save", world))); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + const std::vector expected = { + "[Checkpoint] 00.04: start, 3 events", + "[Event] 00.04/1 walk_to_corner: start", + "[Event] 00.04/1 walk_to_corner: done", + "[Event] 00.04/2 talk_lady: start", + "[Event] 00.04/2 talk_lady: done", + "[Event] 00.04/3 save: start", + "[Event] 00.04/3 save: done", + "[Checkpoint] 00.04: done, 3 run, 0 skipped", + }; + if (!report.completed || lines.lines != expected){ + return std::format("Unexpected log:{}", lines.all()); + } + if (world.trace != std::vector{"walk", "talk", "save"}){ + return "Events ran out of order."; + } + return true; +} + +UnitTestResult test_skips_done_event(){ + World world; + world.potions = 10; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(talk_to_lady(world)); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (!report.completed || report.events_skipped != 1 || report.events_run != 0){ + return "Expected the event skipped."; + } + if (!world.trace.empty() || !lines.has("[Event] 00.04/1 talk_poke_mart_lady: skipped")){ + return std::format("The skipped event should not act:{}", lines.all()); + } + return true; +} + +UnitTestResult test_expect_failure_waited_out(){ + World world; + world.talks_before_answer = 2; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(talk_to_lady(world)); + checkpoint.events.back().recoveries.push_back(recovery("expect_failed", RecoveryKind::WAIT, 2)); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (!report.completed || world.trace.size() != 3 || world.potions != 10){ + return std::format("Expected three talks, the last answered:{}", lines.all()); + } + if (!lines.has("[Event] 00.04/1 talk_poke_mart_lady: recover: wait (expect_failed)")){ + return std::format("Expected the wait logged:{}", lines.all()); + } + return true; +} + +// Mom: a talk from the wrong row reaches nobody. Waiting does not help; +// confirming the row on a landmark does. +Event talk_to_mom(World& world){ + Event event = make_event("talk_mom", [&world](RunState&){ + world.trace.push_back("talk"); + world.dialogue_open = world.rows_off == 0; + return outcome_ok(); + }); + event.expect.push_back(dialogue_opened(world)); + event.recoveries.push_back(recovery("expect_failed", RecoveryKind::WAIT, 1, record("wait", world))); + event.recoveries.push_back(recovery("expect_failed", RecoveryKind::REANCHOR, 1, [&world](RunState& state){ + world.trace.push_back("anchor"); + world.rows_off = 0; + return outcome_ok(anchored(state.pose)); + })); + event.recoveries.push_back(recovery("", RecoveryKind::STOP, 0)); + event.recoveries.back().why = "four rows cover the mat to the TV"; + return event; +} + +UnitTestResult test_escalates_to_reanchor(){ + World world; + world.rows_off = 1; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(talk_to_mom(world)); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + const std::vector expected = {"talk", "wait", "talk", "anchor", "talk"}; + if (!report.completed || world.trace != expected){ + return std::format("Expected wait, then re-anchor:{}", lines.all()); + } + if (state.pose.certainty != PoseCertainty::TILE){ + return "The re-anchor should have fixed the pose."; + } + return true; +} + +UnitTestResult test_stop_names_failed_event(){ + World world; + world.rows_off = 1; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(make_event("enter_home", record("enter", world))); + checkpoint.events.push_back(talk_to_mom(world)); + checkpoint.events.back().recoveries[1].prepare = record("anchor", world); // An anchor that does not help. + checkpoint.events.push_back(make_event("mom_dialogue", record("dialogue", world))); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (report.completed || report.failed_event != 2 || report.failed_name != "talk_mom"){ + return std::format("Expected event 2 reported:{}", lines.all()); + } + if (report.failure.failure != "expect_failed" || report.failure.detail != "dialogue opened"){ + return "Expected the failing expect reported."; + } + if (std::count(world.trace.begin(), world.trace.end(), "dialogue") != 0){ + return "Nothing after the failed event should run."; + } + if (!lines.has("[Event] 00.04/2 talk_mom: recover: stop (expect_failed): four rows cover the mat to the TV") + || !lines.has("[Event] 00.04/2 talk_mom: failed: expect_failed: dialogue opened (class=state_check_failed)") + || lines.lines.back() != "[Checkpoint] 00.04: failed at 2 talk_mom: expect_failed: dialogue opened (class=state_check_failed)" + ){ + return std::format("Unexpected log:{}", lines.all()); + } + return true; +} + +UnitTestResult test_unmatched_failure_stops(){ + World world; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(make_event("probe_for_mom", [&world](RunState&){ + world.trace.push_back("probe"); + return outcome_failed("probe_exhausted", "4 rows"); + })); + checkpoint.events.back().recoveries.push_back(recovery("blocked", RecoveryKind::WAIT, 3)); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (report.completed || report.failure.failure != "probe_exhausted" || world.trace.size() != 1){ + return std::format("A failure no recovery names should stop at once:{}", lines.all()); + } + if (!lines.has("[Event] 00.04/1 probe_for_mom: failed: probe_exhausted: 4 rows")){ + return std::format("Unexpected log:{}", lines.all()); + } + return true; +} + +// A game's own failure name with the class the game gives it. +UnitTestResult test_failure_names_its_class(){ + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(make_event("probe_for_mom", [](RunState&){ + return outcome_failed("probe_exhausted", "4 rows", StoryFailureClass::POSE_LOST); + })); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (failure_class_of(report.failure) != StoryFailureClass::POSE_LOST){ + return std::format("Expected the report's failure of class pose_lost:{}", lines.all()); + } + if (!lines.has("[Event] 00.04/1 probe_for_mom: failed: probe_exhausted: 4 rows (class=pose_lost)") + || lines.lines.back() != "[Checkpoint] 00.04: failed at 1 probe_for_mom: probe_exhausted: 4 rows (class=pose_lost)" + ){ + return std::format("Unexpected log:{}", lines.all()); + } + return true; +} + +// A game's action that throws OperationFailedException: the exception goes +// on, the log names its class. +UnitTestResult test_throw_names_its_class(){ + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(make_event("talk_mom", [](RunState&) -> Outcome{ + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, "no dialog"); + })); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + try{ + run_checkpoint(state, checkpoint, log); + return "Expected the exception to go on."; + }catch (OperationFailedException&){} + if (!lines.has("[Event] 00.04/1 talk_mom: failed: OperationFailedException: no dialog (class=operation_failed)") + || lines.lines.back() != "[Checkpoint] 00.04: failed at 1 talk_mom: OperationFailedException: no dialog (class=operation_failed)" + ){ + return std::format("Unexpected log:{}", lines.all()); + } + return true; +} + +Interrupt wild_battle(ResumePolicy resume, World& world){ + Interrupt interrupt; + interrupt.name = "wild_battle"; + interrupt.detect = [&world](RunState&){ return world.battle_showing; }; + interrupt.handle = [&world](RunState&){ + world.trace.push_back("flee"); + world.battle_showing = false; + return outcome_ok(); + }; + interrupt.pose = InterruptPose::WITHIN_SET; + interrupt.resume = resume; + return interrupt; +} + +// A walk through grass: the first try meets a wild battle half-way. +Event walk_through_grass(World& world){ + Event event = make_event("walk_to_corner", [&world](RunState&){ + world.trace.push_back("walk"); + if (world.walk_failures > 0){ + world.walk_failures--; + world.battle_showing = true; + return outcome_failed("walk_stopped"); + } + world.map = "Route 201"; + return outcome_ok(); + }); + event.require.push_back(pose_known("Route 202", PoseCertainty::TILE)); + event.expect.push_back(condition("on Route 201", [&world](RunState&){ return world.map == "Route 201"; })); + Pose corner; + corner.map = "Route 201"; + corner.certainty = PoseCertainty::TILE; + corner.where = std::make_shared(std::vector{TilePos{42, 3}}); + event.pose_learned = corner; + event.recoveries.push_back(recovery("require_failed", RecoveryKind::REANCHOR, 1, [&world](RunState& state){ + world.trace.push_back("anchor"); + return outcome_ok(anchored(state.pose)); + })); + return event; +} + +RunState at_catch_spot(std::optional facing = std::nullopt){ + RunState state; + state.pose.map = "Route 202"; + state.pose.certainty = PoseCertainty::TILE; + state.pose.where = std::make_shared(std::vector{TilePos{10, 20}}, facing); + return state; +} + +UnitTestResult test_interrupt_mid_event(){ + World world; + world.walk_failures = 1; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.interrupts.push_back(wild_battle(ResumePolicy::RETRY_EVENT, world)); + checkpoint.events.push_back(walk_through_grass(world)); + RunState state = at_catch_spot(); + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + // The battle leaves the pose inexact, so the retry first re-anchors. + const std::vector expected = {"walk", "flee", "anchor", "walk"}; + if (!report.completed || world.trace != expected){ + return std::format("Expected flee, re-anchor, walk again:{}", lines.all()); + } + if (!lines.has("[Event] 00.04/1 walk_to_corner: interrupt: wild_battle")){ + return std::format("Expected the interrupt logged:{}", lines.all()); + } + if (state.pose.map != "Route 201" || tiles_of(state.pose) != std::vector{TilePos{42, 3}}){ + return std::format("Expected the learned pose: {}", to_string(state.pose)); + } + return true; +} + +UnitTestResult test_interrupt_recheck_expect(){ + World world; + Checkpoint checkpoint = make_checkpoint(); + Interrupt interrupt = wild_battle(ResumePolicy::RECHECK_EXPECT, world); + interrupt.pose = InterruptPose::UNCHANGED; + checkpoint.interrupts.push_back(std::move(interrupt)); + // A talk-only trainer stops us on the last step: we arrived anyway. + checkpoint.events.push_back(make_event("walk_to_exit", [&world](RunState&){ + world.trace.push_back("walk"); + world.map = "Route 201"; + world.battle_showing = true; + return outcome_failed("walk_stopped"); + })); + checkpoint.events.back().expect.push_back(condition("on Route 201", [&world](RunState&){ return world.map == "Route 201"; })); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (!report.completed || world.trace != std::vector{"walk", "flee"}){ + return std::format("Expected done without walking again:{}", lines.all()); + } + return true; +} + +UnitTestResult test_too_many_interrupts(){ + World world; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.max_interrupts_per_event = 2; + checkpoint.interrupts.push_back(wild_battle(ResumePolicy::RETRY_EVENT, world)); + checkpoint.events.push_back(make_event("walk", [&world](RunState&){ + world.battle_showing = true; + return outcome_failed("walk_stopped"); + })); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (report.completed || report.failure.failure != "too_many_interrupts"){ + return std::format("Expected to give up after 2 interrupts:{}", lines.all()); + } + return true; +} + + +// 00.04 after the catch, shortened: Potions, save, then a walk north that +// fails on the first run. The reload restores the world as saved. +Checkpoint post_catch(World& world, World& saved){ + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(talk_to_lady(world)); + Event save = make_event("save_on_202", [&world, &saved](RunState&){ + world.trace.push_back("save"); + world.map = "Route 202"; + saved = world; + return outcome_ok(); + }); + save.skip_if.push_back(has_potions(world)); + save.skip_if.push_back(condition("on Route 202", [&world](RunState&){ return world.map == "Route 202"; })); + checkpoint.events.push_back(std::move(save)); + checkpoint.events.push_back(make_event("train", record("train", world))); + checkpoint.events.push_back(make_event("walk_north", [&world](RunState&){ + world.trace.push_back("walk"); + if (world.walk_failures > 0){ + world.walk_failures--; + return outcome_failed("blocked_unexplained"); + } + world.map = "Jubilife City"; + return outcome_ok(); + })); + checkpoint.end.push_back(condition("in Jubilife", [&world](RunState&){ return world.map == "Jubilife City"; })); + return checkpoint; +} + +UnitTestResult test_resume_after_reload(){ + World world; + world.map = "Route 201"; + world.walk_failures = 1; + World saved; + Checkpoint checkpoint = post_catch(world, saved); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport first = run_checkpoint(state, checkpoint, log); + if (first.completed || first.failed_event != 4){ + return std::format("Expected the first run to fail at the walk:{}", lines.all()); + } + world = saved; // Reload: the save has the Potions and stands on Route 202. + world.walk_failures = 0; // Whatever blocked the walk has moved on. + world.trace.clear(); + RunState reloaded; + const CheckpointReport second = run_checkpoint(reloaded, checkpoint, log); + if (!second.completed || second.events_skipped != 2 || second.events_run != 2){ + return std::format("Expected the Potions and the save skipped:{}", lines.all()); + } + if (world.trace != std::vector{"train", "walk"} || world.potions != 10){ + return "Expected only the training and the walk again."; + } + return true; +} + +UnitTestResult test_start_end_and_save(){ + World world; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.start.push_back(has_potions(world)); + checkpoint.events.push_back(make_event("walk", record("walk", world))); + checkpoint.end.push_back(condition("parcel in the Bag", [&world](RunState&){ return world.parcel; })); + checkpoint.save = record("save", world); + RunState state; + Lines lines; + EventLogger log = lines.logger(); + CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (report.completed || report.failure.failure != "start_failed" || !world.trace.empty()){ + return "Expected the start check to stop before any event."; + } + world.potions = 1; + report = run_checkpoint(state, checkpoint, log); + if (report.completed || report.failure.failure != "end_failed" || world.trace.size() != 1){ + return "Expected the end check to fail without a save."; + } + world.parcel = true; + report = run_checkpoint(state, checkpoint, log); + if (!report.completed || world.trace.back() != "save"){ + return "Expected a save after the end check."; + } + return true; +} + +UnitTestResult test_pose_certainty(){ + if (!certainty_covers(PoseCertainty::TILE, PoseCertainty::COLUMN) + || certainty_covers(PoseCertainty::ROW, PoseCertainty::COLUMN) + || certainty_covers(PoseCertainty::SET, PoseCertainty::ROW) + || !certainty_covers(PoseCertainty::SET, PoseCertainty::SET) + || certainty_covers(PoseCertainty::UNKNOWN, PoseCertainty::SET) + || !certainty_covers(PoseCertainty::UNKNOWN, PoseCertainty::UNKNOWN) + ){ + return "Wrong certainty order."; + } + RunState state = at_catch_spot(Direction::NORTH); + if (to_string(state.pose) != "Route 202 (10, 20) facing north (tile)"){ + return std::format("Unexpected pose text: {}", to_string(state.pose)); + } + Condition known = pose_known("Route 201", PoseCertainty::SET); + if (known.check(state)){ + return "The pose is on another map."; + } + return true; +} + +// A game without tiles: a point on its map, as Scarlet/Violet would give. +struct PointPose : public Position{ + int x = 0; + int y = 0; + + PointPose(int x, int y) : x(x), y(y){} + virtual std::string describe() const override{ + return std::format("({}, {})", x, y); + } +}; + +Pose at_point(std::string map, int x, int y){ + Pose pose; + pose.map = std::move(map); + pose.certainty = PoseCertainty::TILE; + pose.where = std::make_shared(x, y); + return pose; +} + +// The engine carries whatever position the game gives it: a battle leaves +// it within the set, a lost pose drops it, a learned pose replaces it. +UnitTestResult test_position_is_the_games(){ + World world; + world.walk_failures = 1; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.interrupts.push_back(wild_battle(ResumePolicy::RETRY_EVENT, world)); + Event ride = make_event("ride_to_mesagoza", [&world](RunState&){ + world.trace.push_back("ride"); + if (world.walk_failures > 0){ + world.walk_failures--; + world.battle_showing = true; + return outcome_failed("walk_stopped"); + } + return outcome_ok(); + }); + ride.require.push_back(pose_known("South Province", PoseCertainty::SET)); + ride.pose_learned = at_point("Mesagoza", 7, 8); + checkpoint.events.push_back(std::move(ride)); + RunState state; + state.pose = at_point("South Province", 3, 4); + Lines lines; + EventLogger log = lines.logger(); + const CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (!report.completed || world.trace != std::vector{"ride", "flee", "ride"}){ + return std::format("Expected the ride retried after the battle:{}", lines.all()); + } + if (to_string(state.pose) != "Mesagoza (7, 8) (tile)"){ + return std::format("Expected the learned point: {}", to_string(state.pose)); + } + Interrupt lost = wild_battle(ResumePolicy::RETRY_EVENT, world); + lost.pose = InterruptPose::LOST; + checkpoint.interrupts[0] = std::move(lost); + world.walk_failures = 1; + checkpoint.events[0].pose_learned.reset(); + checkpoint.events[0].require.clear(); + run_checkpoint(state, checkpoint, log); + if (state.pose.where || to_string(state.pose) != "Mesagoza (unknown)"){ + return std::format("Expected the lost pose to drop its position: {}", to_string(state.pose)); + } + return true; +} + +// An action that learns where it ends up returns the pose; the runner +// writes it before the expects, and only when the action succeeded. +UnitTestResult test_outcome_pose(){ + World world; + Checkpoint checkpoint = make_checkpoint(); + Event probe = make_event("probe_for_mom", [&world](RunState&){ + world.trace.push_back("probe"); + Pose found; + found.map = "Player's House"; + found.certainty = PoseCertainty::ROW; + found.where = std::make_shared(std::vector{TilePos{4, 6}, TilePos{5, 6}}); + return world.rows_off == 0 ? outcome_ok(found) : outcome_failed("probe_exhausted", "4 rows"); + }); + probe.expect.push_back(pose_known("Player's House", PoseCertainty::ROW)); + checkpoint.events.push_back(std::move(probe)); + RunState state = at_catch_spot(); + Lines lines; + EventLogger log = lines.logger(); + CheckpointReport report = run_checkpoint(state, checkpoint, log); + if (!report.completed || to_string(state.pose) != "Player's House (4, 6) (5, 6) (row)"){ + return std::format("Expected the found pose written before the expect: {}{}", to_string(state.pose), lines.all()); + } + world.rows_off = 1; + state = at_catch_spot(); + report = run_checkpoint(state, checkpoint, log); + if (report.completed || state.pose.map != "Route 202"){ + return std::format("A failed action should leave the pose alone: {}", to_string(state.pose)); + } + return true; +} + +UnitTestResult test_lint(){ + World world; + Checkpoint checkpoint = make_checkpoint(); + checkpoint.events.push_back(talk_to_mom(world)); + if (!lint_checkpoint(checkpoint).empty()){ + return "A good checkpoint should lint clean."; + } + checkpoint.events.push_back(make_event("talk_mom", nullptr)); + checkpoint.events.back().recoveries.push_back(recovery("", RecoveryKind::STOP, 0)); + checkpoint.events.back().recoveries.push_back(recovery("", RecoveryKind::WAIT, 0)); + const std::vector problems = lint_checkpoint(checkpoint); + // Duplicate name, no action, wait after stop, wait with no attempts. + if (problems.size() != 4){ + std::string text; + for (const std::string& problem : problems){ + text += std::format("\n{}", problem); + } + return std::format("Expected 4 problems:{}", text); + } + return true; +} + + +struct StoryEventTestCase{ + std::string name; + struct Input{ + UnitTestResult (*test)(); + }; + + struct Expectation{ + std::string_view description; + }; + + Input input; + Expectation expectation; +}; + +class Test_StoryEvents : public UnitTest{ +public: + explicit Test_StoryEvents(StoryEventTestCase scenario) + : UnitTest(std::format("Pokemon::StoryEvents - {}", scenario.name)) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_scenario.input.test(); + } + +private: + StoryEventTestCase m_scenario; +}; + +const StoryEventTestCase STORY_EVENT_CASES[] = { + { + .name = "events run in order", .input = {.test = test_runs_events_in_order}, + .expectation = {.description = "executes registered events in sequence and records traces"}, + }, + { + .name = "a done event is skipped", .input = {.test = test_skips_done_event}, + .expectation = {.description = "bypasses event execution when skip condition is satisfied"}, + }, + { + .name = "a failed expect is waited out", .input = {.test = test_expect_failure_waited_out}, + .expectation = {.description = "retries transient expectation failure until timeout"}, + }, + { + .name = "recoveries escalate to a re-anchor", .input = {.test = test_escalates_to_reanchor}, + .expectation = {.description = "escalates recovery strategy to re-anchor when wait fails"}, + }, + { + .name = "a stop names the failed event", .input = {.test = test_stop_names_failed_event}, + .expectation = {.description = "records identifier of the failed event upon stopping"}, + }, + { + .name = "an unanswered failure stops", .input = {.test = test_unmatched_failure_stops}, + .expectation = {.description = "stops checkpoint execution when failure has no handler"}, + }, + { + .name = "a failure names its class", .input = {.test = test_failure_names_its_class}, + .expectation = {.description = "logs the class a game gives its own failure name"}, + }, + { + .name = "a throw names its class", .input = {.test = test_throw_names_its_class}, + .expectation = {.description = "logs operation_failed for an OperationFailedException that goes on"}, + }, + { + .name = "an interrupt mid-event", .input = {.test = test_interrupt_mid_event}, + .expectation = {.description = "handles asynchronous interruption during event execution"}, + }, + { + .name = "an interrupt rechecks the expects", .input = {.test = test_interrupt_recheck_expect}, + .expectation = {.description = "re-evaluates expected conditions after an interrupt clears"}, + }, + { + .name = "too many interrupts", .input = {.test = test_too_many_interrupts}, + .expectation = {.description = "aborts execution when interrupt count exceeds threshold"}, + }, + { + .name = "resume after a reload", .input = {.test = test_resume_after_reload}, + .expectation = {.description = "resumes story execution cleanly following save reload"}, + }, + { + .name = "start, end and save", .input = {.test = test_start_end_and_save}, + .expectation = {.description = "validates start conditions, end conditions, and state save"}, + }, + { + .name = "pose certainty", .input = {.test = test_pose_certainty}, + .expectation = {.description = "tracks and adjusts player pose confidence levels"}, + }, + { + .name = "the position is the game's", .input = {.test = test_position_is_the_games}, + .expectation = {.description = "preserves game-specific coordinate representations"}, + }, + { + .name = "an action returns its pose", .input = {.test = test_outcome_pose}, + .expectation = {.description = "updates run pose from successful event action outcome"}, + }, + { + .name = "lint", .input = {.test = test_lint}, + .expectation = {.description = "validates checkpoint structural integrity and rules"}, + }, +}; + +} // namespace + + +void add_tests_StoryEvents(UnitTestDatabase& database){ + for (const auto& scenario : STORY_EVENT_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.h new file mode 100644 index 0000000000..970de36ba4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.h @@ -0,0 +1,23 @@ +/* Story Events Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryEvents_Tests_H +#define PokemonAutomation_Pokemon_StoryEvents_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for story event sequencing and execution. +void add_tests_StoryEvents(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.cpp new file mode 100644 index 0000000000..11fc343fe9 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.cpp @@ -0,0 +1,294 @@ +/* Story Failure Classes + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_StoryFailureClasses.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +constexpr std::string_view TAG_PREFIX = "class="; + +using C = StoryFailureClass; +using R = StoryFailureClassInfo::Retry; + +// The run and the console. +std::vector run_rows(){ + return { + { + C::GAME_NOT_RUNNING, "game_not_running", + "the Switch HOME menu shows instead of the game", + "the HOME menu read at a step's start or after a failure", + {"game_not_running"}, R::STOP, + }, + { + C::LAUNCH_FAILED, "launch_failed", + "getting from HOME to the game's overworld failed", + "the launch driver: no game tile, a screen that ignores its press, no overworld in time", + {"launch_failed"}, R::STOP, + }, + { + C::WRONG_START, "wrong_start", + "the game is not at the checkpoint's start: another save, an older one, another place", + "the checkpoint's start checks and the preflight", + {"start_failed", "wrong_save", "precondition_failed"}, R::STOP, + }, + { + C::RELOAD_FAILED, "reload_failed", + "reloading the checkpoint's save failed", + "the game's reload hook", + {"reload_failed"}, R::STOP, + }, + { + C::SAVE_FAILED, "save_failed", + "saving at the checkpoint's end failed", + "the game's save hook", + {"save_failed"}, R::RELOAD, + }, + { + C::STORY_ERROR, "story_error", + "the story's data or code is wrong: a step, range or action the program cannot run", + "the engine's lint and lookups, before or as a step starts", + { + "unsupported_step", "unknown_checkpoint", "bad_range", "empty_segment", + "bad_verify_policy", "lint_failed", "no_save_hook", "console_only", + }, + R::STOP, + }, + }; +} + +// Walking. +std::vector walk_rows(){ + return { + { + C::LOST_TAP, "lost_tap", + "a tap the game drops", + "the walker reads the player where the tap started", + {}, R::RETRY_STEP, + }, + { + C::UNSEEN_STEP, "unseen_step", + "a step tap that moved the player, read as not moved", + "the walker finds the player a tile past where it read", + {}, R::RETRY_STEP, + }, + { + C::WALK_SHORT, "walk_short", + "a walk or hold ended short of its tile", + "the walker's position check at a wall or landmark", + {}, R::RETRY_STEP, + }, + { + C::BLOCKED, "blocked", + "something on the way stops the walk: a person, a wall the map does not have", + "the walker's progress check: no tile gained", + {}, R::RETRY_STEP, + }, + { + C::MOUNT_LOST, "mount_lost", + "off the Bicycle (or another mount) at a leg that rides", + "the walker's tiles per tap", + {}, R::RETRY_STEP, + }, + { + C::POSE_LOST, "pose_lost", + "where the player is or faces is unknown or not what the map says", + "the localizer: no pose, another map, another facing", + {}, R::RELOAD, + }, + }; +} + +// Warps and fades. +std::vector warp_rows(){ + return { + { + C::WARP_NO_OP, "warp_no_op", + "a step onto a warp shows the fade's black but does not warp", + "the map or tile after the fade is the one before it", + {}, R::RETRY_STEP, + }, + { + C::LATE_FADE, "late_fade", + "a warp's fade shows late or is missed", + "the fade watcher: the warp unconfirmed, the player on a map the walk did not plan", + {}, R::RETRY_STEP, + }, + { + C::SLOW_FADE_IN, "slow_fade_in", + "a warp's fade-in runs long: a move right after it goes nowhere", + "the first move after a fade does not move the player", + {}, R::RETRY_STEP, + }, + { + C::DARK_MAP, "dark_map", + "a dark map (a cave without Flash) the readers cannot see", + "the floor reads dim; the walker's and the scene's reads fail there", + {}, R::STOP, + }, + }; +} + +// Scenes, talks and battles. +std::vector scene_rows(){ + return { + { + C::SCENE_END_POSE, "scene_end_pose", + "a step whose end the game sets leaves the player on a tile next to the expected one", + "the next walk starts or ends a tile off", + {}, R::RETRY_STEP, + }, + { + C::SCENE_EARLY, "scene_early", + "a scene starts on the last tiles of the walk before it", + "the walk is interrupted by the scene's dialogue", + {}, R::RETRY_STEP, + }, + { + C::BATTLE_OPENING, "battle_opening", + "a battle's opening is still playing when a step starts", + "the step's first read is not the overworld or battle menu it expects", + {}, R::RETRY_STEP, + }, + { + C::WILD_BATTLES, "wild_battles", + "more wild battles than a clean run meets", + "the interrupt handler clears each; too many in a step fail it", + {"too_many_interrupts"}, R::RETRY_STEP, + }, + }; +} + +// Interrupts, reads, menus and checks. +std::vector check_rows(){ + return { + { + C::INTERRUPT_FAILED, "interrupt_failed", + "something interrupted a step and was not cleared", + "the interrupt handler: no handler, a failed clear, the screen not settled", + {"unhandled_interrupt", "interrupt_failed", "interrupt_unsettled", "interrupted"}, R::RELOAD, + }, + { + C::SCREEN_UNREAD, "screen_unread", + "a screen the step waits for (dialogue, banner, overworld, prompt) is not seen", + "the step's detector times out", + {"talk_no_text", "mash_no_overworld"}, R::RELOAD, + }, + { + C::MENU_FAILED, "menu_failed", + "a menu action (mart, PC, item, TM, Fly) did not do what it was to", + "the menu's readers: the item, count or choice not as planned", + {}, R::RELOAD, + }, + { + C::BATTLE_LOST, "battle_lost", + "a battle lost or not won: a blackout", + "the battle's end screen or the blackout's heal spot", + {}, R::RELOAD, + }, + { + C::STATE_CHECK_FAILED, "state_check_failed", + "a check of the game's state failed: an event's expects, the checkpoint's end", + "the event's expects and requires, the checkpoint's end and postconditions", + {"expect_failed", "require_failed", "end_failed", "postconditions_failed"}, R::RELOAD, + }, + { + C::OPERATION_FAILED, "operation_failed", + "a game's action threw, with no class of its own", + "an OperationFailedException out of a step", + {"operation_failed"}, R::RELOAD, + }, + { + C::SIM_MISMATCH, "sim_mismatch", + "a simulated run left the story: the sim and the table disagree", + "the story sim's end checks (sim runs only)", + {}, R::STOP, + }, + }; +} + +// Every class, in the enum's order. Function-local, so a static +// initializer in another file may read it. +const std::vector& class_rows(){ + static const std::vector CLASSES = []{ + std::vector rows; + const auto append = [&rows](std::vector group){ + rows.insert(rows.end(), std::make_move_iterator(group.begin()), std::make_move_iterator(group.end())); + }; + append(run_rows()); + append(walk_rows()); + append(warp_rows()); + append(scene_rows()); + append(check_rows()); + return rows; + }(); + return CLASSES; +} + +// The class whose id is `id`; nothing for an unknown id. +std::optional find_story_failure_class(std::string_view id){ + for (const StoryFailureClassInfo& info : class_rows()){ + if (info.id == id){ + return info.failure_class; + } + } + return std::nullopt; +} + +} // namespace + + +const std::vector& story_failure_classes(){ + return class_rows(); +} + +const StoryFailureClassInfo& story_failure_class_info(StoryFailureClass failure_class){ + const std::vector& classes = class_rows(); + const size_t index = static_cast(failure_class); + if (index >= classes.size() || classes[index].failure_class != failure_class){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, std::format("Story failure class {} has no row in its place.", index) + ); + } + return classes[index]; +} + +std::optional story_failure_class_of_outcome(std::string_view failure){ + for (const StoryFailureClassInfo& info : class_rows()){ + if (std::ranges::find(info.outcomes, failure) != info.outcomes.end()){ + return info.failure_class; + } + } + return std::nullopt; +} + + +std::string story_failure_class_tag(StoryFailureClass failure_class){ + return std::format("{}{}", TAG_PREFIX, story_failure_class_info(failure_class).id); +} + +std::optional read_story_failure_class_tag(std::string_view text){ + const size_t start = text.find(TAG_PREFIX); + if (start == std::string_view::npos){ + return std::nullopt; + } + const std::string_view rest = text.substr(start + TAG_PREFIX.size()); + const size_t end = rest.find_first_not_of("abcdefghijklmnopqrstuvwxyz_"); + return find_story_failure_class(rest.substr(0, end)); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.h new file mode 100644 index 0000000000..6ed2e678b4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.h @@ -0,0 +1,107 @@ +/* Story Failure Classes + * + * From: https://github.com/PokemonAutomation/ + * + * One list of the ways an AutoStory step fails, for every game: what the + * run log and run records name a failure by. Each class is a row of data: + * its id, what it means, how a run sees it, and what a retry should do. + * + * An Outcome's failure name ("expect_failed") is finer than a class: a + * class covers the names that mean the same to a retry. The engine's names + * are mapped here; a game's own names are mapped when it adopts the list. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryFailureClasses_H +#define PokemonAutomation_Pokemon_StoryFailureClasses_H + +#include +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A class of story failure, in story_failure_classes()'s order. +enum class StoryFailureClass{ + GAME_NOT_RUNNING, + LAUNCH_FAILED, + WRONG_START, + RELOAD_FAILED, + SAVE_FAILED, + STORY_ERROR, + LOST_TAP, + UNSEEN_STEP, + WALK_SHORT, + BLOCKED, + MOUNT_LOST, + POSE_LOST, + WARP_NO_OP, + LATE_FADE, + SLOW_FADE_IN, + DARK_MAP, + SCENE_END_POSE, + SCENE_EARLY, + BATTLE_OPENING, + WILD_BATTLES, + INTERRUPT_FAILED, + SCREEN_UNREAD, + MENU_FAILED, + BATTLE_LOST, + STATE_CHECK_FAILED, + OPERATION_FAILED, + // The last: the tests check that every class up to it has a row. + SIM_MISMATCH, +}; + +// One class of failure. +struct StoryFailureClassInfo{ + // What a retry should do after a failure of the class: a hint, the + // program decides. + enum class Retry{ + // Find where the player is and run the step again. + RETRY_STEP, + // Reload the checkpoint's save and run it again. + RELOAD, + // Stop the run: no retry fixes it, a person or a code change must. + STOP, + }; + + StoryFailureClass failure_class; + // The class in logs and run records: "warp_no_op". + std::string_view id; + // What went wrong, in one line. + std::string_view meaning; + // How a run sees it. + std::string_view detected_by; + // The engine's Outcome failure names of this class. + std::vector outcomes; + Retry retry; +}; + +// Every class, in the enum's order. +const std::vector& story_failure_classes(); + +// The row of `failure_class`. Throws InternalProgramError when the list +// has no row for it in the enum's place. +const StoryFailureClassInfo& story_failure_class_info(StoryFailureClass failure_class); + +// The class of an engine Outcome failure name ("expect_failed"); nothing +// for a name no class lists yet, like a game's own. +std::optional story_failure_class_of_outcome(std::string_view failure); + + +// The class as a log line or run record writes it: "class=warp_no_op". +std::string story_failure_class_tag(StoryFailureClass failure_class); + +// The class tagged in `text`, a log line or run record field that holds a +// story_failure_class_tag(); nothing when it holds none or an unknown id. +std::optional read_story_failure_class_tag(std::string_view text); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses_Tests.cpp new file mode 100644 index 0000000000..674c2b97cb --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses_Tests.cpp @@ -0,0 +1,260 @@ +/* Story Failure Classes Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The list's own checks: every sim fault and every engine failure name + * maps to one class, and every class id reads back from the text a log + * line or run record writes. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon_StoryFailureClasses.h" +#include "Pokemon_StoryFailureClasses_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// The class id of `failure_class`, or "none" for nothing: for messages. +std::string_view id_or_none(std::optional failure_class){ + return failure_class ? story_failure_class_info(*failure_class).id : "none"; +} + + +// An engine Outcome failure name and the class it maps to. +struct OutcomeClassTestCase{ + struct Input{ + std::string_view failure; + }; + + struct Expectation{ + std::optional failure_class; + }; + + std::string name; + Input input; + Expectation expectation; +}; + +class Test_OutcomeClass : public UnitTest{ +public: + explicit Test_OutcomeClass(OutcomeClassTestCase test_case) + : UnitTest(std::format("Pokemon::StoryFailureClasses - outcome: {}", test_case.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::optional got = story_failure_class_of_outcome(m_case.input.failure); + if (got != m_case.expectation.failure_class){ + return std::format( + "\"{}\": expected {}, got {}", + m_case.input.failure, id_or_none(m_case.expectation.failure_class), id_or_none(got) + ); + } + return true; + } + +private: + const OutcomeClassTestCase m_case; +}; + +using C = StoryFailureClass; + +// Every failure name the engine's code returns (autostory/engine), and +// #477's launch_failed. +const OutcomeClassTestCase OUTCOME_CASES[] = { + {.name = "HOME menu", .input = {"game_not_running"}, .expectation = {C::GAME_NOT_RUNNING}}, + {.name = "launch", .input = {"launch_failed"}, .expectation = {C::LAUNCH_FAILED}}, + {.name = "start checks", .input = {"start_failed"}, .expectation = {C::WRONG_START}}, + {.name = "another save", .input = {"wrong_save"}, .expectation = {C::WRONG_START}}, + {.name = "preflight", .input = {"precondition_failed"}, .expectation = {C::WRONG_START}}, + {.name = "reload", .input = {"reload_failed"}, .expectation = {C::RELOAD_FAILED}}, + {.name = "save", .input = {"save_failed"}, .expectation = {C::SAVE_FAILED}}, + {.name = "unsupported step", .input = {"unsupported_step"}, .expectation = {C::STORY_ERROR}}, + {.name = "unknown checkpoint", .input = {"unknown_checkpoint"}, .expectation = {C::STORY_ERROR}}, + {.name = "bad range", .input = {"bad_range"}, .expectation = {C::STORY_ERROR}}, + {.name = "empty segment", .input = {"empty_segment"}, .expectation = {C::STORY_ERROR}}, + {.name = "bad verify policy", .input = {"bad_verify_policy"}, .expectation = {C::STORY_ERROR}}, + {.name = "lint", .input = {"lint_failed"}, .expectation = {C::STORY_ERROR}}, + {.name = "no save hook", .input = {"no_save_hook"}, .expectation = {C::STORY_ERROR}}, + {.name = "console only", .input = {"console_only"}, .expectation = {C::STORY_ERROR}}, + {.name = "too many interrupts", .input = {"too_many_interrupts"}, .expectation = {C::WILD_BATTLES}}, + {.name = "unhandled interrupt", .input = {"unhandled_interrupt"}, .expectation = {C::INTERRUPT_FAILED}}, + {.name = "interrupt not cleared", .input = {"interrupt_failed"}, .expectation = {C::INTERRUPT_FAILED}}, + {.name = "interrupt unsettled", .input = {"interrupt_unsettled"}, .expectation = {C::INTERRUPT_FAILED}}, + {.name = "interrupted", .input = {"interrupted"}, .expectation = {C::INTERRUPT_FAILED}}, + {.name = "talk without text", .input = {"talk_no_text"}, .expectation = {C::SCREEN_UNREAD}}, + {.name = "mash without overworld", .input = {"mash_no_overworld"}, .expectation = {C::SCREEN_UNREAD}}, + {.name = "expect", .input = {"expect_failed"}, .expectation = {C::STATE_CHECK_FAILED}}, + {.name = "require", .input = {"require_failed"}, .expectation = {C::STATE_CHECK_FAILED}}, + {.name = "checkpoint end", .input = {"end_failed"}, .expectation = {C::STATE_CHECK_FAILED}}, + {.name = "postconditions", .input = {"postconditions_failed"}, .expectation = {C::STATE_CHECK_FAILED}}, + {.name = "operation", .input = {"operation_failed"}, .expectation = {C::OPERATION_FAILED}}, + {.name = "a game's own name", .input = {"no_banner"}, .expectation = {std::nullopt}}, + {.name = "empty", .input = {""}, .expectation = {std::nullopt}}, +}; + + +// A check over the whole list. +struct ListCheckTestCase{ + // The check, run over story_failure_classes(). + struct Input{ + UnitTestResult (*check)(); + }; + + // What holds when the check passes. + struct Expectation{ + std::string_view holds; + }; + + std::string name; + Input input; + Expectation expectation; +}; + +class Test_ListCheck : public UnitTest{ +public: + explicit Test_ListCheck(ListCheckTestCase test_case) + : UnitTest(std::format("Pokemon::StoryFailureClasses - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_case.input.check(); + } + +private: + const ListCheckTestCase m_case; +}; + +UnitTestResult rows_in_enum_order(){ + const std::vector& classes = story_failure_classes(); + for (size_t c = 0; c < classes.size(); c++){ + if (static_cast(classes[c].failure_class) != c){ + return std::format("row {} ({}) is out of the enum's order", c, classes[c].id); + } + } + return true; +} + +UnitTestResult every_class_has_a_row(){ + const size_t count = static_cast(StoryFailureClass::SIM_MISMATCH) + 1; + if (story_failure_classes().size() != count){ + return std::format("{} rows for {} classes", story_failure_classes().size(), count); + } + try{ + story_failure_class_info(static_cast(count)); + }catch (const InternalProgramError&){ + return true; + } + return std::string("a class past the last row did not throw"); +} + +UnitTestResult no_outcome_in_two_classes(){ + std::map seen; + for (const StoryFailureClassInfo& info : story_failure_classes()){ + for (std::string_view failure : info.outcomes){ + const auto [iter, added] = seen.emplace(failure, info.id); + if (!added){ + return std::format("\"{}\" is in {} and {}", failure, iter->second, info.id); + } + } + } + return true; +} + +UnitTestResult ids_round_trip(){ + std::set ids; + for (const StoryFailureClassInfo& info : story_failure_classes()){ + if (!ids.insert(info.id).second){ + return std::format("id \"{}\" is in two rows", info.id); + } + const std::optional got = read_story_failure_class_tag(story_failure_class_tag(info.failure_class)); + if (got != info.failure_class){ + return std::format("id \"{}\" reads back as {}", info.id, id_or_none(got)); + } + } + return true; +} + +UnitTestResult tags_round_trip_through_a_log_line(){ + for (const StoryFailureClassInfo& info : story_failure_classes()){ + const std::string line = std::format( + "[Checkpoint] 00.04: failed at 2 talk_mom: expect_failed: has_parcel ({})", + story_failure_class_tag(info.failure_class) + ); + const std::optional got = read_story_failure_class_tag(line); + if (got != info.failure_class){ + return std::format("\"{}\" reads back as {}", line, id_or_none(got)); + } + } + return true; +} + +UnitTestResult tags_round_trip_through_a_run_record(){ + for (const StoryFailureClassInfo& info : story_failure_classes()){ + const std::string field = std::format("\"failure\": \"{}\"", story_failure_class_tag(info.failure_class)); + const std::optional got = read_story_failure_class_tag(field); + if (got != info.failure_class){ + return std::format("{} reads back as {}", field, id_or_none(got)); + } + } + return true; +} + +UnitTestResult no_class_without_a_tag(){ + const std::string_view lines[] = { + "[Checkpoint] 00.04: failed at 2 talk_mom: expect_failed: has_parcel", + "[Checkpoint] 00.04: failed (class=no_such_class)", + "class=", + }; + for (std::string_view line : lines){ + const std::optional got = read_story_failure_class_tag(line); + if (got){ + return std::format("\"{}\" reads as {}", line, id_or_none(got)); + } + } + return true; +} + +const ListCheckTestCase LIST_CHECKS[] = { + {.name = "rows in the enum's order", .input = {rows_in_enum_order}, .expectation = {"story_failure_class_info() indexes by the enum"}}, + {.name = "every class has a row", .input = {every_class_has_a_row}, .expectation = {"no class reads past the table"}}, + {.name = "no outcome name in two classes", .input = {no_outcome_in_two_classes}, .expectation = {"a failure name has one class"}}, + {.name = "ids round-trip", .input = {ids_round_trip}, .expectation = {"each id is unique and its tag alone reads back"}}, + {.name = "tags round-trip through a log line", .input = {tags_round_trip_through_a_log_line}, .expectation = {"the run log names the class"}}, + {.name = "tags round-trip through a run record", .input = {tags_round_trip_through_a_run_record}, .expectation = {"a run record names the class"}}, + {.name = "no class without a tag", .input = {no_class_without_a_tag}, .expectation = {"untagged or unknown text has no class"}}, +}; + +} // namespace + + +void add_tests_StoryFailureClasses(UnitTestDatabase& database){ + for (const OutcomeClassTestCase& test_case : OUTCOME_CASES){ + database.add(test_case); + } + for (const ListCheckTestCase& test_case : LIST_CHECKS){ + database.add(test_case); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses_Tests.h new file mode 100644 index 0000000000..c14ff5bca4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses_Tests.h @@ -0,0 +1,23 @@ +/* Story Failure Classes Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryFailureClasses_Tests_H +#define PokemonAutomation_Pokemon_StoryFailureClasses_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the shared story failure classes. +void add_tests_StoryFailureClasses(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp new file mode 100644 index 0000000000..5fed3725bf --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp @@ -0,0 +1,85 @@ +/* Story Log + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryLog.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +std::string resets_text(size_t attempt){ + if (attempt <= 1){ + return "one-shot"; + } + return std::format("{} reset{}", attempt - 1, attempt == 2 ? "" : "s"); +} + +// "[Checkpoint] 00.04", or the game's own checkpoint text unchanged. +std::string checkpoint_prefix(std::string_view checkpoint, bool add_checkpoint_prefix){ + if (!add_checkpoint_prefix){ + return std::string(checkpoint); + } + return std::format("[Checkpoint] {}", checkpoint); +} + +} // namespace + + +std::string checkpoint_start_line( + std::string_view checkpoint, std::optional events, bool add_checkpoint_prefix +){ + const std::string prefix = checkpoint_prefix(checkpoint, add_checkpoint_prefix); + if (!events){ + return std::format("{}: start", prefix); + } + return std::format("{}: start, {} events", prefix, *events); +} + +std::string checkpoint_attempt_line( + std::string_view checkpoint, size_t attempt, std::optional attempts, bool add_checkpoint_prefix +){ + const std::string prefix = checkpoint_prefix(checkpoint, add_checkpoint_prefix); + if (!attempts){ + return std::format("{}: attempt {}", prefix, attempt); + } + return std::format("{}: attempt {}/{}", prefix, attempt, *attempts); +} + +std::string checkpoint_pass_line(std::string_view checkpoint, size_t attempt, bool add_checkpoint_prefix){ + return std::format( + "{}: passed on attempt {} ({})", + checkpoint_prefix(checkpoint, add_checkpoint_prefix), attempt, resets_text(attempt) + ); +} + +std::string checkpoint_reset_line( + std::string_view checkpoint, size_t next_attempt, std::optional attempts, bool add_checkpoint_prefix +){ + const std::string prefix = checkpoint_prefix(checkpoint, add_checkpoint_prefix); + if (!attempts){ + return std::format("{}: failed, resetting for attempt {}", prefix, next_attempt); + } + return std::format("{}: failed, resetting for attempt {}/{}", prefix, next_attempt, *attempts); +} + +std::string story_short_line(std::string_view line){ + if (!line.starts_with('[')){ + return std::string(line); + } + const size_t end = line.find("] "); + if (end == std::string_view::npos){ + return std::string(line); + } + return std::string(line.substr(end + 2)); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h new file mode 100644 index 0000000000..11bfb009d2 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h @@ -0,0 +1,85 @@ +/* Story Log + * + * From: https://github.com/PokemonAutomation/ + * + * A story is split at three levels: a segment is a chapter of + * checkpoints, a checkpoint is the stretch between two saves and the unit + * a run retries, and an event is one step inside a checkpoint. This file + * writes the checkpoint lines: start, attempt, reset and pass, in one + * format for every game, so the program developer and user find each + * checkpoint's attempts the same way in any game's log. Nothing here runs + * a story. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryLog_H +#define PokemonAutomation_Pokemon_StoryLog_H + +#include +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The lines below start with "[Checkpoint] " and then `checkpoint`. A game +// whose checkpoint text already says it is a checkpoint (SV's +// "Checkpoint:: 004 - 02 ...") passes that text as `checkpoint` and +// `add_checkpoint_prefix` false, and the line starts with the text alone: +// Checkpoint:: 004 - 02 ...: start + +// A checkpoint starts; the story engine also says it has `events` events: +// [Checkpoint] 00.04: start +// [Checkpoint] 00.04: start, 3 events +std::string checkpoint_start_line( + std::string_view checkpoint, + std::optional events = std::nullopt, + bool add_checkpoint_prefix = true +); + +// An attempt at a checkpoint starts, counting from 1, out of the +// program's limit of `attempts` if it has one: +// [Checkpoint] 00.04: attempt 2 +// [Checkpoint] 00.04: attempt 2/3 +std::string checkpoint_attempt_line( + std::string_view checkpoint, + size_t attempt, + std::optional attempts = std::nullopt, + bool add_checkpoint_prefix = true +); + +// A checkpoint passed on attempt `attempt`, counting from 1; every attempt +// before it ended in a reset: +// [Checkpoint] 00.03: passed on attempt 1 (one-shot) +// [Checkpoint] 00.04: passed on attempt 3 (2 resets) +std::string checkpoint_pass_line( + std::string_view checkpoint, + size_t attempt, + bool add_checkpoint_prefix = true +); + +// An attempt failed and the game resets to the checkpoint's save for +// attempt `next_attempt`, out of the limit of `attempts` if it has one: +// [Checkpoint] 00.04: failed, resetting for attempt 2 +// [Checkpoint] 00.04: failed, resetting for attempt 2/3 +std::string checkpoint_reset_line( + std::string_view checkpoint, + size_t next_attempt, + std::optional attempts = std::nullopt, + bool add_checkpoint_prefix = true +); + +// The full lines above go to the log. The video overlay, which wraps its +// lines, shows each one short, without its leading "[Tag] ": +// [Checkpoint] 12.03: start, 18 events -> 12.03: start, 18 events +// Any line with a leading "[Tag] " is shortened the same way. A line +// without a tag, like SV's checkpoint text, is returned unchanged. +std::string story_short_line(std::string_view line); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp new file mode 100644 index 0000000000..759ed9b3d7 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp @@ -0,0 +1,167 @@ +/* Story Log Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_StoryLog.h" +#include "Pokemon_StoryLog_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +// One formatter call and the line it must make. +struct StoryLogTestCase{ + // A formatter's line, made when the table is built. + struct Input{ + std::string line; + }; + + // The exact line: the lab watcher and the engine tests read these. + struct Expectation{ + std::string line; + }; + + std::string name; + Input input; + Expectation expectation; +}; + +class Test_StoryLog : public UnitTest{ +public: + Test_StoryLog(StoryLogTestCase test_case) + : UnitTest(std::format("Pokemon::StoryLog - {}", test_case.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + if (m_case.input.line != m_case.expectation.line){ + return std::format("Expected \"{}\", got \"{}\"", m_case.expectation.line, m_case.input.line); + } + return true; + } + +private: + const StoryLogTestCase m_case; +}; + +// SV's text for a checkpoint, which already says "Checkpoint::". +constexpr std::string_view SV_TEXT = "Checkpoint:: 004 - 02. Start point: X"; + +const StoryLogTestCase STORY_LOG_CASES[] = { + { + .name = "checkpoint start", + .input = {.line = checkpoint_start_line("00.04")}, + .expectation = {.line = "[Checkpoint] 00.04: start"}, + }, + { + .name = "checkpoint start with its events", + .input = {.line = checkpoint_start_line("00.04", /*events=*/3)}, + .expectation = {.line = "[Checkpoint] 00.04: start, 3 events"}, + }, + { + .name = "attempt", + .input = {.line = checkpoint_attempt_line("00.04", 2)}, + .expectation = {.line = "[Checkpoint] 00.04: attempt 2"}, + }, + { + .name = "attempt out of a limit", + .input = {.line = checkpoint_attempt_line("00.04", 2, /*attempts=*/3)}, + .expectation = {.line = "[Checkpoint] 00.04: attempt 2/3"}, + }, + { + .name = "one-shot pass", + .input = {.line = checkpoint_pass_line("00.03", 1)}, + .expectation = {.line = "[Checkpoint] 00.03: passed on attempt 1 (one-shot)"}, + }, + { + .name = "pass after one reset", + .input = {.line = checkpoint_pass_line("00.04", 2)}, + .expectation = {.line = "[Checkpoint] 00.04: passed on attempt 2 (1 reset)"}, + }, + { + .name = "pass after resets", + .input = {.line = checkpoint_pass_line("00.04", 3)}, + .expectation = {.line = "[Checkpoint] 00.04: passed on attempt 3 (2 resets)"}, + }, + { + .name = "reset", + .input = {.line = checkpoint_reset_line("00.04", 2)}, + .expectation = {.line = "[Checkpoint] 00.04: failed, resetting for attempt 2"}, + }, + { + .name = "reset out of a limit", + .input = {.line = checkpoint_reset_line("00.04", 2, /*attempts=*/3)}, + .expectation = {.line = "[Checkpoint] 00.04: failed, resetting for attempt 2/3"}, + }, + { + .name = "start without the checkpoint prefix", + .input = {.line = checkpoint_start_line(SV_TEXT, /*events=*/std::nullopt, /*add_checkpoint_prefix=*/false)}, + .expectation = {.line = "Checkpoint:: 004 - 02. Start point: X: start"}, + }, + { + .name = "attempt without the checkpoint prefix", + .input = {.line = checkpoint_attempt_line(SV_TEXT, 2, /*attempts=*/100, /*add_checkpoint_prefix=*/false)}, + .expectation = {.line = "Checkpoint:: 004 - 02. Start point: X: attempt 2/100"}, + }, + { + .name = "pass without the checkpoint prefix", + .input = {.line = checkpoint_pass_line(SV_TEXT, 2, /*add_checkpoint_prefix=*/false)}, + .expectation = {.line = "Checkpoint:: 004 - 02. Start point: X: passed on attempt 2 (1 reset)"}, + }, + { + .name = "reset without the checkpoint prefix", + .input = {.line = checkpoint_reset_line(SV_TEXT, 2, /*attempts=*/std::nullopt, /*add_checkpoint_prefix=*/false)}, + .expectation = {.line = "Checkpoint:: 004 - 02. Start point: X: failed, resetting for attempt 2"}, + }, + { + .name = "short checkpoint start", + .input = {.line = story_short_line("[Checkpoint] 12.03: start, 18 events")}, + .expectation = {.line = "12.03: start, 18 events"}, + }, + { + .name = "short line with another tag", + .input = {.line = story_short_line("[Tag] 12.03: some text")}, + .expectation = {.line = "12.03: some text"}, + }, + { + .name = "short line without the checkpoint prefix", + .input = {.line = story_short_line( + checkpoint_start_line(SV_TEXT, /*events=*/std::nullopt, /*add_checkpoint_prefix=*/false) + )}, + .expectation = {.line = "Checkpoint:: 004 - 02. Start point: X: start"}, + }, + { + .name = "short line with an unclosed tag", + .input = {.line = story_short_line("[Tag 12.03")}, + .expectation = {.line = "[Tag 12.03"}, + }, + { + .name = "short empty line", + .input = {.line = story_short_line("")}, + .expectation = {.line = ""}, + }, +}; + + +} // namespace + + +void add_tests_StoryLog(UnitTestDatabase& database){ + for (const StoryLogTestCase& test_case : STORY_LOG_CASES){ + database.add(test_case); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.h new file mode 100644 index 0000000000..822a222b31 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.h @@ -0,0 +1,23 @@ +/* Story Log Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryLog_Tests_H +#define PokemonAutomation_Pokemon_StoryLog_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the shared checkpoint log lines. +void add_tests_StoryLog(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcome.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcome.h new file mode 100644 index 0000000000..66a1e1a083 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcome.h @@ -0,0 +1,76 @@ +/* Story Outcome + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_StoryEvents.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryOutcome_H +#define PokemonAutomation_Pokemon_StoryOutcome_H + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon_StoryFailureClasses.h" +#include "Pokemon_StoryLog.h" +#include "Pokemon_StoryPose.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How an action or a check ended: empty `failure` is success; otherwise a +// name that recoveries match (e.g. "probe_exhausted"). A succeeded action +// that knows where it left the player sets `pose`; the runner writes it +// into the run before the event's expects are checked. +struct Outcome{ + std::string failure; + std::string detail; + std::optional pose; + // A succeeded action that left the game as it found it: a read, a + // check, a TM the lead already knows. A reload of the same save undoes + // nothing it did. + bool changed_nothing = false; + // The failure's class, when the action knows it: a game's own failure + // name ("probe_exhausted") has none in the shared list until the game + // gives it one here. Nothing: the class the list gives `failure`. + std::optional failure_class = std::nullopt; + + bool succeeded() const; +}; +// Constructs a successful event outcome, updating the run pose when given one. +Outcome outcome_ok(std::optional pose = std::nullopt); +// outcome_ok() with `changed_nothing`. +Outcome outcome_unchanged(); +// Constructs a failed event outcome with reason and optional diagnostic detail. +// `failure_class` is for a name the shared list does not class (a game's +// own); without it the list's class for `failure` holds. +Outcome outcome_failed( + std::string failure, std::string detail = "", + std::optional failure_class = std::nullopt +); +// "probe_exhausted: 4 rows": the failure and its detail, if any. +std::string to_string(const Outcome& outcome); + +// The failure of a step that found the Switch's HOME menu instead of the +// game. Nothing in the story can answer it, as every press goes to the +// console's menus: no recovery runs and no reload, the run stops. +inline constexpr std::string_view GAME_NOT_RUNNING = "game_not_running"; +// GAME_NOT_RUNNING, saying so for the run log. +Outcome outcome_game_not_running(); + + +// Callable action executed for a story event. +using Act = MoveOnlyFunction; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.cpp new file mode 100644 index 0000000000..064bb87ee4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.cpp @@ -0,0 +1,35 @@ +/* Story Outcome Class + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryOutcomeClass.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::optional failure_class_of(const Outcome& outcome){ + if (outcome.succeeded()){ + return std::nullopt; + } + if (outcome.failure_class){ + return outcome.failure_class; + } + return story_failure_class_of_outcome(outcome.failure); +} + +std::string to_string_with_class(const Outcome& outcome){ + const std::optional failure_class = failure_class_of(outcome); + if (!failure_class){ + return to_string(outcome); + } + return std::format("{} ({})", to_string(outcome), story_failure_class_tag(*failure_class)); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.h new file mode 100644 index 0000000000..ec692db6ab --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.h @@ -0,0 +1,35 @@ +/* Story Outcome Class + * + * From: https://github.com/PokemonAutomation/ + * + * The class (Pokemon_StoryFailureClasses.h) of a failed Outcome, and the + * text a failure's log line ends with. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryOutcomeClass_H +#define PokemonAutomation_Pokemon_StoryOutcomeClass_H + +#include +#include +#include "Pokemon_StoryFailureClasses.h" +#include "Pokemon_StoryOutcome.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The class of a failed `outcome`: its own, else the shared list's for its +// name. Nothing for a success or a name no class lists. +std::optional failure_class_of(const Outcome& outcome); + +// to_string() and the class, as a failure's log line ends: +// "expect_failed: has_parcel (class=state_check_failed)"; without a class, +// to_string() alone. +std::string to_string_with_class(const Outcome& outcome); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h new file mode 100644 index 0000000000..b9c0eb53db --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h @@ -0,0 +1,79 @@ +/* Story Pose + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_StoryEvents.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryPose_H +#define PokemonAutomation_Pokemon_StoryPose_H + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon_StoryLog.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How much of the pose is known. COLUMN and ROW pin one axis (a wall, a +// door); SET means one of the positions the pose holds. +enum class PoseCertainty{ + TILE, + COLUMN, + ROW, + SET, + UNKNOWN, +}; +// Returns the string label for a pose certainty level. +std::string certainty_name(PoseCertainty certainty); + +// Whether a pose known to `have` is good enough for an event that needs `need`. +bool certainty_covers(PoseCertainty have, PoseCertainty need); + +// Where on a map the player is, in the game's own terms: tiles and a +// facing in a 2D game (Pokemon_TilePose.h), a map point or a fly point in +// an open-world one. The engine only carries and prints it; the game's +// actions read it back. +struct Position{ + virtual ~Position() = default; + // The text after the map in a log line, e.g. "(10, 20) facing north"; + // none for a game that has nothing to say beyond the map. + virtual std::string describe() const{ + return ""; + } +}; + +// Where the player is believed to be. The screen is read; the pose is +// tracked, and only an anchor (a wall, a door, an NPC who answered) makes +// it certain. `where` is null until the game learns a position and after +// the pose is lost; it is shared because poses are copied (an event's +// learned pose into the run) and never changed in place. +struct Pose{ + std::string map; + PoseCertainty certainty = PoseCertainty::UNKNOWN; + std::shared_ptr where; +}; +// Formats a Pose as a human-readable string. +std::string to_string(const Pose& pose); + + +// What a run knows. Flags are set only by confirmed effects and are lost +// on a reload. +struct RunState{ + Pose pose; + std::set flags; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp new file mode 100644 index 0000000000..ee108c1f20 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp @@ -0,0 +1,181 @@ +/* Story Step Executor + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Pokemon_BuiltinStoryActions.h" +#include "Pokemon_StoryStepExecutor.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +Pose pose_of(const GridPose& pose){ + return tile_pose(pose.map, pose.tiles, pose.facing); +} + +GridPose grid_pose_of(const DeclaredPose& pose){ + if (const TileDeclared* tile = std::get_if(&pose)){ + return GridPose{.map = tile->map, .tiles = tile->tiles, .facing = tile->facing}; + } + return GridPose{.map = std::get(pose).place, .tiles = {}, .facing = std::nullopt}; +} + +Pose pose_of(const DeclaredPose& pose){ + return pose_of(grid_pose_of(pose)); +} + +Outcome unsupported_step(const StoryStep& step){ + return outcome_failed("unsupported_step", std::format("{} {}", story_step_kind_name(step.kind), step.name)); +} + + +void StoryStepExecutor::begin_attempt(const StoryCheckpoint&){} + +bool StoryStepExecutor::holds(std::string_view condition, RunState& state){ + return state.flags.contains(std::string(condition)); +} + + +Event story_event(const StoryStep& step, StoryStepExecutor& executor){ + Event event; + event.name = step.name; + event.why = step.why; + for (const std::string& name : step.skip_if){ + event.skip_if.push_back(condition(name, [&executor, name](RunState& state){ + return executor.holds(name, state); + })); + } + event.act = [&executor, &step](RunState& state){ + return executor.run(step, state); + }; + if (step.pose_after){ + event.pose_learned = pose_of(*step.pose_after); + } + return event; +} + +namespace{ + +// The first event of a checkpoint that starts from a save: where the save +// leaves the player, for a run that reloaded it. +Event from_save_event(const Pose& start){ + Event event; + event.name = "from_save"; + event.why = "where the checkpoint's save leaves the player"; + event.act = [](RunState&){ return outcome_ok(); }; + event.pose_learned = start; + return event; +} + +} // namespace + +namespace{ + +// `event`, for a once_per_save step known in `prepared` as `key`: skipped +// while `prepared` has it, and added to it when it succeeds changing +// nothing. +void run_once_per_save(std::string key, Event& event, PreparedSteps& prepared){ + event.skip_if.push_back(condition("done_from_this_save", [&prepared, key](RunState&){ + return prepared.contains(key); + })); + event.act = [act = std::move(event.act), &prepared, key](RunState& state) mutable{ + Outcome outcome = act(state); + if (outcome.succeeded() && outcome.changed_nothing){ + prepared.insert(key); + } + return outcome; + }; +} + +} // namespace + +Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor& executor, PreparedSteps* prepared){ + executor.begin_attempt(data); + Checkpoint checkpoint; + checkpoint.id = data.id; + if (data.start){ + checkpoint.events.push_back(from_save_event(pose_of(*data.start))); + } + for (size_t index = 0; index < data.steps.size(); index++){ + const StoryStep& step = data.steps[index]; + checkpoint.events.push_back(story_event(step, executor)); + if (StoryPausePoints* pause = executor.pause_points()){ + checkpoint.events.back().act = [ + act = std::move(checkpoint.events.back().act), pause, label = story_step_pause_label(data.id, index, step.name) + ](RunState& state) mutable{ + pause->before_step(label); + return act(state); + }; + } + if (prepared != nullptr && step.once_per_save){ + run_once_per_save(std::format("{}/{}", data.id, step.name), checkpoint.events.back(), *prepared); + } + } + return checkpoint; +} + + +namespace{ + +// What is wrong with a step's action and args, each as a line: a GAME +// step without an action, args that don't fit a built-in action's spec, +// an empty leg. +std::vector action_problems(const StoryStep& step){ + if (step.kind == StoryStepKind::GAME){ + return step.action.empty() ? std::vector{"no action"} : std::vector{}; + } + const StoryActionSpec* spec = find_story_action(builtin_story_actions(), step.kind, step.action); + if (spec == nullptr){ + // A game's own action: the game checks it when it loads the step. + return {}; + } + std::vector problems = story_args_errors(*spec, step.args); + const std::vector* legs = value_if_at_it>(step.args, step.args.find("legs")); + if (legs != nullptr && legs->empty()){ + problems.emplace_back("no legs"); + } + for (const StoryLeg& leg : legs ? *legs : std::vector{}){ + if (leg.tiles <= 0){ + problems.emplace_back("a leg of no tiles"); + } + } + return problems; +} + +} // namespace + +std::vector lint_story_checkpoint(const StoryCheckpoint& data){ + std::vector problems; + if (data.id.empty()){ + problems.emplace_back("a checkpoint has no id"); + } + std::set names; + for (size_t c = 0; c < data.steps.size(); c++){ + const StoryStep& step = data.steps[c]; + const std::string where = std::format("{} step {}", data.id, c + 1); + if (step.name.empty()){ + problems.emplace_back(std::format("{}: no name", where)); + }else if (!names.insert(step.name).second){ + problems.emplace_back(std::format("{}: a second step named {}", where, step.name)); + } + for (const std::string& problem : action_problems(step)){ + problems.emplace_back(std::format("{} {}: {} {}", where, step.name, story_step_kind_name(step.kind), problem)); + } + // skip_if's conditions must all hold; once per save is one more. + if (step.once_per_save && !step.skip_if.empty()){ + problems.emplace_back(std::format("{} {}: once per save with skip_if", where, step.name)); + } + } + return problems; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h new file mode 100644 index 0000000000..dfc22dd35b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h @@ -0,0 +1,132 @@ +/* Story Step Executor + * + * From: https://github.com/PokemonAutomation/ + * + * One vocabulary of story steps for the tile games (FRLG, BDSP): a route, + * a fixed walk, a step onto a trigger, a talk, a YES/NO, a scene, a + * battle, the nurse, a shop, a save, and so on. A checkpoint is a list of + * such steps, plain data (Types/), so a game's story is a table its unit + * tests can plan without a console. + * + * build_story_checkpoint() turns a table row into engine events + * (Pokemon_StoryEvents.h). Each event's action asks the game's + * StoryStepExecutor to do its step; a game implements the kinds it uses, + * and a step it has no way of doing fails by name (unsupported_step()) + * instead of doing something else. + * + * Steps never match dialogue or menu text: they look for screen state (a + * dialogue box, an arrow, a fade, a battle menu, colours, positions). The + * few reads that need text (item names in a shop or the Bag) take the + * game's language from the program's options (StoryRunOptions), and with + * no reader for it fall back to checks that need none (a row's position, + * digits, a changed screen), so a run never fails because its language + * is not supported. + * + * Poses are the game's own (Pose, with a TilePose for these games): a + * checkpoint's start, a scene's end and a route's target are poses, and + * an executor that knows where a step left the player says so in its + * Outcome, which the engine writes into the run. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStepExecutor_H +#define PokemonAutomation_Pokemon_StoryStepExecutor_H + +#include +#include +#include +#include +#include "Pokemon_StoryEvents.h" +#include "Pokemon_TilePose.h" +#include "Types/Pokemon_DeclaredPose.h" +#include "Types/Pokemon_GridPose.h" +#include "Types/Pokemon_StoryBreakpoints.h" +#include "Types/Pokemon_StoryCheckpoint.h" +#include "Types/Pokemon_StoryStep.h" +#include "Types/Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How a game does its story steps: an interface with no data. run() is the +// game's: it does the step's kind its own way (FRLG and BDSP bind kinds and +// action names to handlers in a table), and returns unsupported_step() for a +// kind it has no way of doing. +class StoryStepExecutor{ +public: + virtual ~StoryStepExecutor() = default; + + // A checkpoint is being built for a new attempt: build_story_checkpoint() + // calls this first, so a game can start the attempt afresh (trainers + // who can see us again, the row's own settings). Does nothing by default. + virtual void begin_attempt(const StoryCheckpoint& data); + + // Does `step`, from the run so far. A SAVE step must save only when + // the run's save mode allows a save part-way (PER_CHECKPOINT): nothing + // here knows the mode. The story engine's own SAVE action does this + // for a game on the engine. + virtual Outcome run(const StoryStep& step, RunState& state) = 0; + + // Whether the condition named in a step's skip_if holds: by default, + // whether the run has the flag (set by an earlier step's action). + virtual bool holds(std::string_view condition, RunState& state); + + // The game's pause points (Pokemon_StoryBreakpoints.h), which the + // checkpoints built for this executor call before each of their steps. + // The game owns them and sets them before it builds a checkpoint; it + // calls before_leg() from its own leg loops. None by default: no pauses. + void set_pause_points(StoryPausePoints* pause){ + m_pause = pause; + } + StoryPausePoints* pause_points() const{ + return m_pause; + } + +private: + StoryPausePoints* m_pause = nullptr; +}; + +// `pose` as the engine's Pose: a TilePose, TILE for one tile, SET for several. +Pose pose_of(const GridPose& pose); + +// A declared pose as a grid pose: a place reads as a map with no tiles. +GridPose grid_pose_of(const DeclaredPose& pose); + +// pose_of(grid_pose_of(pose)). +Pose pose_of(const DeclaredPose& pose); + +// "unsupported_step: TRAIN train_in_grass": what an executor without the kind returns. +Outcome unsupported_step(const StoryStep& step); + + +// The step as an event that runs it with `executor`. Both must outlive +// the event. +Event story_event(const StoryStep& step, StoryStepExecutor& executor); + +// The once_per_save steps done from the save the game is on that changed +// nothing, as "/". The game keeps it across reloads and +// empties it when it saves or loads another save. +using PreparedSteps = std::set; + +// The checkpoint `data` as events: "from_save" first when it has a start +// (the start pose, for a run that reloaded its save), then one event per +// step. `data` and `executor` must outlive the checkpoint. Saving is the +// game's: it sets the checkpoint's save, or adds a SAVE step. +// With `prepared`, each once_per_save step is skipped while `prepared` has +// it, and added to it when it succeeds changing nothing; `prepared` must +// then outlive the checkpoint. Without, once_per_save steps run every time. +Checkpoint build_story_checkpoint( + const StoryCheckpoint& data, StoryStepExecutor& executor, PreparedSteps* prepared = nullptr +); + +// Problems an author should fix before running: an empty id, unnamed or +// repeated steps, a GAME step without an action, a built-in action's args +// that don't fit its spec (a route without a target), empty legs. +std::vector lint_story_checkpoint(const StoryCheckpoint& data); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp new file mode 100644 index 0000000000..ade175345d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp @@ -0,0 +1,451 @@ +/* Story Steps Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Story tables built into checkpoints and run against a fake executor + * that writes down each step it is asked to do: the order of the events, + * skipped steps, the pose each step leaves, and how a failure is named. + * Nothing here belongs to one game. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_BuiltinStoryActions.h" +#include "Pokemon_StoryStepExecutor.h" +#include "Pokemon_TilePose.h" +#include "Pokemon_StoryStepExecutor_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// A world of two maps. Routes arrive on their target; a step moves a tile +// from the run's pose. Each step it does is written down as "KIND name", +// with the pose it started from when that is known. +class FakeExecutor : public StoryStepExecutor{ +public: + std::vector trace; + std::set> conditions; + // Steps by name that always fail, and how. + std::set failing; + // Steps by name that fail this many more times, then pass. + std::map failures_left; + // The pose each step started from, by name. + std::vector> poses_seen; + // The checkpoints begun, one per attempt. + std::vector attempts; + // Game steps by name that change nothing in the game. + std::set unchanged; + + virtual void begin_attempt(const StoryCheckpoint& data) override{ + attempts.push_back(data.id); + } + + virtual Outcome run(const StoryStep& step, RunState& state) override{ + poses_seen.emplace_back(step.name, to_string(state.pose)); + trace.push_back(std::format("{} {}", story_step_kind_name(step.kind), step.name)); + if (failing.contains(step.name)){ + return outcome_failed("blocked", std::format("{} was blocked", step.name)); + } + size_t& left = failures_left[step.name]; + if (left > 0){ + left--; + return outcome_failed("blocked", std::format("{} was blocked", step.name)); + } + return run_kind(step, state); + } + + virtual bool holds(std::string_view condition, RunState& state) override{ + return conditions.contains(condition) || StoryStepExecutor::holds(condition, state); + } + +private: + // The kinds this world has; any other is unsupported. + Outcome run_kind(const StoryStep& step, RunState& state){ + switch (step.kind){ + case StoryStepKind::ROUTE: + return outcome_ok(pose_of(story_arg(step.args, "target"))); + case StoryStepKind::STEP: + return step_one_tile(step, state); + case StoryStepKind::TALK: + case StoryStepKind::MASH: + return outcome_ok(); + case StoryStepKind::BATTLE: + // The first battle is lost; a step that may lose goes on. + return story_arg(step.args, "may_lose") ? outcome_ok() : outcome_failed("blackout"); + case StoryStepKind::SHOP: + return shop(step); + case StoryStepKind::GAME: + return game(step, state); + default: + return unsupported_step(step); + } + } + + Outcome step_one_tile(const StoryStep& step, const RunState& state){ + const std::vector tiles = tiles_of(state.pose); + if (tiles.size() != 1){ + return outcome_failed("no_pose", to_string(state.pose)); + } + const Direction direction = story_arg(step.args, "direction"); + return outcome_ok(tile_pose(state.pose.map, {tiles[0].next(direction)}, direction)); + } + + Outcome shop(const StoryStep& step){ + for (const StoryItem& item : story_arg>(step.args, "items")){ + trace.push_back(std::format(" bought {} {}", item.quantity, item.item)); + } + return outcome_ok(); + } + + // A game step sets a run flag named for its action. + Outcome game(const StoryStep& step, RunState& state){ + trace.push_back(std::format(" game {}", step.action)); + state.flags.insert(step.action); + return unchanged.contains(step.name) ? outcome_unchanged() : outcome_ok(); + } +}; + +StoryStep make(StoryStepKind kind, std::string name){ + StoryStep step; + step.kind = kind; + step.name = std::move(name); + // As loading it would: the kind's built-in action's fallbacks. + if (const StoryActionSpec* spec = find_story_action(builtin_story_actions(), kind, "")){ + step.args = with_fallbacks(*spec, {}); + } + return step; +} + +// A grid pose on one tile. +GridPose grid(std::string map, TilePos tile, Direction facing){ + return GridPose{.map = std::move(map), .tiles = {tile}, .facing = facing}; +} + +// A declared pose on one tile. +TileDeclared declared(std::string map, TilePos tile, Direction facing){ + return TileDeclared{.map = std::move(map), .tiles = {tile}, .facing = facing}; +} + +StoryStep route_to(std::string name, GridPose target){ + StoryStep step = make(StoryStepKind::ROUTE, std::move(name)); + step.args = {{"target", std::move(target)}, {"fight_wild", false}}; + return step; +} + +StoryStep step_into(std::string name, Direction direction){ + StoryStep step = make(StoryStepKind::STEP, std::move(name)); + step.args = {{"direction", direction}}; + return step; +} + +StoryStep scene(std::string name, std::optional pose_after){ + StoryStep step = make(StoryStepKind::MASH, std::move(name)); + step.pose_after = std::move(pose_after); + return step; +} + +// A lab checkpoint: to the table, a trigger, the scene into the lab, a +// talk, a shop, a game step. +StoryCheckpoint lab_checkpoint(){ + StoryStep shop = make(StoryStepKind::SHOP, "potions"); + shop.args = {{"items", std::vector{{.item = "potion", .quantity = 5}, {.item = "antidote", .quantity = 3}}}}; + StoryStep game = make(StoryStepKind::GAME, "dance"); + game.action = "dance"; + return StoryCheckpoint{ + .id = "00.03", + .title = "to the lab", + .start = declared("Town", {6, 8}, Direction::SOUTH), + .steps = { + route_to("below_trigger", grid("Town", {12, 2}, Direction::NORTH)), + step_into("trigger", Direction::NORTH), + scene("to_the_lab", declared("Lab", {6, 4}, Direction::NORTH)), + make(StoryStepKind::TALK, "talk_oak"), + shop, + game, + }, + }; +} + +struct Run{ + CheckpointReport report; + RunState state; + std::vector lines; +}; + +Run run(const StoryCheckpoint& data, StoryStepExecutor& executor){ + Run ret; + Checkpoint checkpoint = build_story_checkpoint(data, executor); + EventLogger log = [&ret](const std::string& line){ ret.lines.push_back(line); }; + ret.report = run_checkpoint(ret.state, checkpoint, log); + return ret; +} + +std::string joined(std::span lines){ + std::string text; + for (const std::string& line : lines){ + text += std::format("\n {}", line); + } + return text; +} + + +UnitTestResult test_events_in_table_order(){ + const StoryCheckpoint data = lab_checkpoint(); + FakeExecutor executor; + const Run result = run(data, executor); + const std::vector expected{ + "ROUTE below_trigger", + "STEP trigger", + "MASH to_the_lab", + "TALK talk_oak", + "SHOP potions", + " bought 5 potion", + " bought 3 antidote", + "GAME dance", + " game dance", + }; + if (!result.report.completed || executor.trace != expected){ + return std::format("Expected the steps in table order:{}\nbut ran:{}", joined(expected), joined(executor.trace)); + } + // "from_save" is the engine's own event: the executor is not asked. + const std::string first = event_log_line("00.03", 1, "from_save", "start"); + if (result.lines.empty() || std::find(result.lines.begin(), result.lines.end(), first) == result.lines.end()){ + return std::format("Expected the from_save event first:{}", joined(result.lines)); + } + return true; +} + +UnitTestResult test_skip_if(){ + StoryCheckpoint data = lab_checkpoint(); + data.steps[0].skip_if = {"has_parcel"}; + data.steps[3].skip_if = {"has_parcel", "talked"}; + FakeExecutor executor; + executor.conditions = {"has_parcel"}; + // The route is skipped; the talk needs both conditions, so it runs. + const Run result = run(data, executor); + if (!result.report.completed || result.report.events_skipped != 1){ + return std::format("Expected one step skipped, got {}:{}", result.report.events_skipped, joined(result.lines)); + } + if (std::find(executor.trace.begin(), executor.trace.end(), "ROUTE below_trigger") != executor.trace.end()){ + return std::format("Expected the route skipped:{}", joined(executor.trace)); + } + if (std::find(executor.trace.begin(), executor.trace.end(), "TALK talk_oak") == executor.trace.end()){ + return std::format("Expected the talk run, one of its conditions not holding:{}", joined(executor.trace)); + } + + // By default a condition is a run flag: the game step "dance" sets + // one, and a talk after it that needs it is skipped. + StoryStep after = make(StoryStepKind::TALK, "talk_after_dance"); + after.skip_if = {"dance"}; + data = lab_checkpoint(); + data.steps.push_back(after); + FakeExecutor plain; + const Run flagged = run(data, plain); + if (!flagged.report.completed || flagged.report.events_skipped != 1 || plain.trace.back() != " game dance"){ + return std::format("Expected the talk after the dance skipped on its flag:{}", joined(plain.trace)); + } + return true; +} + +UnitTestResult test_pose_propagation(){ + const StoryCheckpoint data = lab_checkpoint(); + FakeExecutor executor; + const Run result = run(data, executor); + // Each step starts where the one before left the player: the save, the + // route's target, a tile north of it, the scene's end, and the scene's + // end again after a talk that says nothing of where it leaves us. + const std::vector> expected{ + {"below_trigger", "Town (6, 8) facing south (tile)"}, + {"trigger", "Town (12, 2) facing north (tile)"}, + {"to_the_lab", "Town (12, 1) facing north (tile)"}, + {"talk_oak", "Lab (6, 4) facing north (tile)"}, + {"potions", "Lab (6, 4) facing north (tile)"}, + {"dance", "Lab (6, 4) facing north (tile)"}, + }; + if (!result.report.completed || executor.poses_seen != expected){ + std::string text; + for (const auto& item : executor.poses_seen){ + text += std::format("\n {}: {}", item.first, item.second); + } + return std::format("Unexpected poses at the steps' starts:{}", text); + } + if (to_string(result.state.pose) != "Lab (6, 4) facing north (tile)"){ + return std::format("Expected the run to end at the scene's end, got {}", to_string(result.state.pose)); + } + return true; +} + +UnitTestResult test_failure_names_the_step(){ + const StoryCheckpoint data = lab_checkpoint(); + FakeExecutor executor; + executor.failing = {"trigger"}; + const Run result = run(data, executor); + // Event 3: from_save is event 1. + if (result.report.completed || result.report.failed_event != 3 || result.report.failed_name != "trigger" + || result.report.failure.failure != "blocked" + ){ + return std::format("Expected a failure at event 3 trigger, blocked:{}", joined(result.lines)); + } + if (executor.trace.size() != 2){ + return std::format("Expected nothing run after the failed step:{}", joined(executor.trace)); + } + return true; +} + +UnitTestResult test_unsupported_and_lost_battles(){ + // The fake has no TRAIN, and loses battles a step may not lose. + StoryStep train = make(StoryStepKind::TRAIN, "train"); + train.args = {{"battles", int64_t(3)}}; + FakeExecutor executor; + Run result = run(StoryCheckpoint{.id = "01", .title = "", .start = std::nullopt, .steps = {train}}, executor); + if (result.report.completed || result.report.failure.failure != "unsupported_step" || result.report.failure.detail != "TRAIN train"){ + return std::format("Expected TRAIN unsupported:{}", joined(result.lines)); + } + StoryStep rival = make(StoryStepKind::BATTLE, "rival"); + rival.args = {{"may_lose", true}}; + StoryStep brock = make(StoryStepKind::BATTLE, "brock"); + result = run(StoryCheckpoint{.id = "02", .title = "", .start = std::nullopt, .steps = {rival, brock}}, executor); + if (result.report.completed || result.report.failed_name != "brock" || result.report.failure.failure != "blackout"){ + return std::format("Expected the rival's battle passed and Brock's lost:{}", joined(result.lines)); + } + return true; +} + +// An executor with pause points pauses before each of its checkpoint's steps, +// labelled with the checkpoint and the step's place; a skipped step does not +// pause, as it does not run. +UnitTestResult test_pause_points(){ + StoryCheckpoint data = lab_checkpoint(); + data.steps[1].skip_if = {"done"}; + std::vector paused; + FakeExecutor executor; + executor.conditions = {"done"}; + StoryPausePoints pause(StoryBreakpoints::STEPS, [&paused](std::string_view label){ + paused.emplace_back(label); + }); + executor.set_pause_points(&pause); + const Run result = run(data, executor); + const std::vector expected{ + "00.03/1 below_trigger", "00.03/3 to_the_lab", "00.03/4 talk_oak", "00.03/5 potions", "00.03/6 dance", + }; + if (paused != expected){ + return std::format("Expected a pause before each step that ran:{}{}", joined(paused), joined(result.lines)); + } + FakeExecutor plain; + const Run quiet = run(data, plain); + return quiet.report.completed ? UnitTestResult(true) : UnitTestResult(joined(quiet.lines)); +} + + +UnitTestResult test_lint(){ + StoryStep no_target = make(StoryStepKind::ROUTE, "walk"); + StoryStep again = make(StoryStepKind::TALK, "walk"); + StoryStep bad_legs = make(StoryStepKind::LEGS, "legs"); + bad_legs.args = {{"legs", std::vector{{.direction = Direction::NORTH, .tiles = 0}}}, {"fight_wild", false}}; + StoryStep no_variant = make(StoryStepKind::GAME, ""); + const StoryCheckpoint data{.id = "", .title = "", .start = std::nullopt, .steps = {no_target, again, bad_legs, no_variant}}; + const std::vector expected{ + "a checkpoint has no id", + " step 1 walk: ROUTE missing argument \"target\" (where to go; with several tiles, any of them)", + " step 2: a second step named walk", + " step 3 legs: LEGS a leg of no tiles", + " step 4: no name", + " step 4 : GAME no action", + }; + const std::vector problems = lint_story_checkpoint(data); + if (problems != expected){ + return std::format("Unexpected lint:{}", joined(problems)); + } + if (!lint_story_checkpoint(lab_checkpoint()).empty()){ + return std::format("Expected the lab checkpoint to lint clean:{}", joined(lint_story_checkpoint(lab_checkpoint()))); + } + return true; +} + + +struct StoryStepTestCase{ + std::string name; + struct Input{ + UnitTestResult (*test)(); + }; + + struct Expectation{ + std::string_view description; + }; + + Input input; + Expectation expectation; +}; + +class Test_StoryStepExecutor : public UnitTest{ +public: + explicit Test_StoryStepExecutor(StoryStepTestCase scenario) + : UnitTest(std::format("Pokemon::StoryStepExecutor - {}", scenario.name)) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_scenario.input.test(); + } + +private: + StoryStepTestCase m_scenario; +}; + +const StoryStepTestCase STORY_STEP_CASES[] = { + { + .name = "steps run in table order", .input = {.test = test_events_in_table_order}, + .expectation = {.description = "executes story steps sequentially as defined in table"}, + }, + { + .name = "skip_if asks the executor", .input = {.test = test_skip_if}, + .expectation = {.description = "delegates skip condition check to executor"}, + }, + { + .name = "each step starts where the last left the player", .input = {.test = test_pose_propagation}, + .expectation = {.description = "propagates player pose across sequential step executions"}, + }, + { + .name = "a failure names its step", .input = {.test = test_failure_names_the_step}, + .expectation = {.description = "records failing step identifier on error"}, + }, + { + .name = "unsupported kinds and lost battles", .input = {.test = test_unsupported_and_lost_battles}, + .expectation = {.description = "flags unsupported step types and handles battle defeat"}, + }, + { + .name = "pause points pause before each step", .input = {.test = test_pause_points}, + .expectation = {.description = "calls the game's pause points before each step that runs"}, + }, + { + .name = "lint", .input = {.test = test_lint}, + .expectation = {.description = "verifies lint validation rules on story checkpoints"}, + }, +}; + +} // namespace + + +void add_tests_StoryStepExecutor(UnitTestDatabase& database){ + for (const auto& scenario : STORY_STEP_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.h new file mode 100644 index 0000000000..d2d6c053e5 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.h @@ -0,0 +1,23 @@ +/* Story Step Executor Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStepExecutor_Tests_H +#define PokemonAutomation_Pokemon_StoryStepExecutor_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for high-level story step dispatching and table conversion. +void add_tests_StoryStepExecutor(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.cpp new file mode 100644 index 0000000000..4d53eeff06 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.cpp @@ -0,0 +1,54 @@ +/* Tile Pose + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Pokemon_TilePose.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +TilePose::TilePose(std::vector tiles, std::optional facing) + : tiles(std::move(tiles)) + , facing(facing) +{} + +std::string TilePose::describe() const{ + std::string text; + for (const TilePos& tile : tiles){ + text += (text.empty() ? "" : " ") + to_string(tile); + } + if (facing){ + text += std::format("{}facing {}", text.empty() ? "" : " ", direction_name(*facing)); + } + return text; +} + +std::vector tiles_of(const Pose& pose){ + const TilePose* position = dynamic_cast(pose.where.get()); + return position ? position->tiles : std::vector{}; +} + +std::optional facing_of(const Pose& pose){ + const TilePose* position = dynamic_cast(pose.where.get()); + return position ? position->facing : std::nullopt; +} + +Pose tile_pose(std::string map, std::vector tiles, std::optional facing){ + Pose pose; + pose.map = std::move(map); + pose.certainty = tiles.empty() ? PoseCertainty::UNKNOWN + : tiles.size() == 1 ? PoseCertainty::TILE : PoseCertainty::SET; + pose.where = std::make_shared(std::move(tiles), facing); + return pose; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.h new file mode 100644 index 0000000000..bf937c3912 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TilePose.h @@ -0,0 +1,49 @@ +/* Tile Pose + * + * From: https://github.com/PokemonAutomation/ + * + * The position a 2D tile game (BDSP, FRLG) gives the story-event engine: + * the tiles the player may stand on and the way they face. The engine + * (Pokemon_StoryEvents.h) does not know tiles; games include this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_TilePose_H +#define PokemonAutomation_Pokemon_TilePose_H + +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "Pokemon_StoryEvents.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// One of `tiles`, facing `facing` if known. +struct TilePose : public Position{ + std::vector tiles; + std::optional facing; + + explicit TilePose(std::vector tiles, std::optional facing = std::nullopt); + // "(10, 20) facing north": the tiles, then the facing, each after a space. + virtual std::string describe() const override; +}; + +// The tiles of a pose: empty when the pose holds no position, or one that +// is not a tile pose. +std::vector tiles_of(const Pose& pose); + +// The facing of a tile pose; nothing for another pose or none. +std::optional facing_of(const Pose& pose); + +// A pose on one of `tiles` of `map`, facing `facing` if set: TILE for one +// tile, SET for several, UNKNOWN for none. +Pose tile_pose(std::string map, std::vector tiles, std::optional facing = std::nullopt); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_DeclaredPose.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_DeclaredPose.h new file mode 100644 index 0000000000..cfcab43d72 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_DeclaredPose.h @@ -0,0 +1,53 @@ +/* Declared Pose + * + * From: https://github.com/PokemonAutomation/ + * + * A pose a checkpoint declares in its data (its start, a step's + * declared_after), as plain data. A tile game (FRLG, BDSP) declares a + * map, tiles and a facing; a game with no tile grid (PLZA) declares a + * place, a spot in it and a heading. Each game reads only its own kind + * (StoryPoseTraits::Declared); the lint fails a checkpoint that declares + * the other. + * + */ + +#ifndef PokemonAutomation_Pokemon_DeclaredPose_H +#define PokemonAutomation_Pokemon_DeclaredPose_H + +#include +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// On one of `tiles` of `map` (any tile when none), facing `facing` if set. +struct TileDeclared{ + std::string map; + std::vector tiles; + std::optional facing; + + bool operator==(const TileDeclared& other) const = default; +}; + +// In `place` ("LumioseCity"), at `spot` in it if set, heading `heading` +// degrees if set. +struct ZoneDeclared{ + std::string place; + std::optional spot; + std::optional heading; + + bool operator==(const ZoneDeclared& other) const = default; +}; + +// Either kind; a game reads only its own (StoryPoseTraits::Declared). +using DeclaredPose = std::variant; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_GridPose.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_GridPose.h new file mode 100644 index 0000000000..3280715da5 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_GridPose.h @@ -0,0 +1,37 @@ +/* Grid Pose + * + * From: https://github.com/PokemonAutomation/ + * + * Where a player stands on a 2D tile grid (FRLG, BDSP): a map, the tiles + * they may be on and the way they face. Games that move on a surface or + * in 3D (PLZA) need their own type. + * + */ + +#ifndef PokemonAutomation_Pokemon_GridPose_H +#define PokemonAutomation_Pokemon_GridPose_H + +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// One of `tiles` of `map`, facing `facing` if set. As a target, any of the +// tiles will do. +struct GridPose{ + std::string map; + std::vector tiles; + std::optional facing; + + bool operator==(const GridPose& other) const = default; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.cpp new file mode 100644 index 0000000000..4adc5dd7d6 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.cpp @@ -0,0 +1,20 @@ +/* Story Action Arg + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryActionArg.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +StoryArgType story_arg_type(const StoryArgValue& value){ + return (StoryArgType)value.index(); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h new file mode 100644 index 0000000000..f1a9fb5d50 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h @@ -0,0 +1,93 @@ +/* Story Action Arg + * + * From: https://github.com/PokemonAutomation/ + * + * A step's action and its arguments (StoryStep::action, StoryStep::args), + * e.g. a Mart step's {"map": "CeruleanCity_Mart", "budget": 3000}. Each + * action declares the arguments it takes (Pokemon_StoryActionSpec.h), with their + * types and defaults; the JSON reader (Data/Pokemon_StoryStepJson.h) + * parses a step's args against them and fills in the defaults, so a typo + * fails at load instead of mid-run and nothing after it reads JSON. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryActionArg_H +#define PokemonAutomation_Pokemon_StoryActionArg_H + +#include +#include +#include +#include +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "Pokemon_GridPose.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A straight leg of a fixed walk. +struct StoryLeg{ + Direction direction = Direction::NORTH; + int tiles = 0; + + bool operator==(const StoryLeg& other) const = default; +}; + +// A leg of a timed walk in a game with no tiles: turn `turn` degrees +// (clockwise, from the way the player faces), then walk for `ms`. +struct StoryTimedLeg{ + int turn = 0; + int ms = 0; + + bool operator==(const StoryTimedLeg& other) const = default; +}; + +// An item and how many to get. +struct StoryItem{ + std::string item; + size_t quantity = 0; + + bool operator==(const StoryItem& other) const = default; +}; + + +// The type an action declares for an argument, in StoryArgValue's order. +enum class StoryArgType{ + BOOLEAN, + INTEGER, + WORD, + DIRECTION, + GRID_POSE, + LEGS, + WORDS, + ITEMS, + INTEGER_ROWS, + TIMED_LEGS, +}; + +// One argument's value; the index is its StoryArgType. +using StoryArgValue = std::variant< + bool, int64_t, std::string, // BOOLEAN, INTEGER, WORD + Direction, GridPose, // DIRECTION, GRID_POSE + std::vector, // LEGS + std::vector, // WORDS + std::vector, // ITEMS + std::vector>, // INTEGER_ROWS: rows of any length, [[12, 7], [3, 9, 1], []] + std::vector // TIMED_LEGS: [turn degrees, ms] pairs, [[0, 4500], [90, 1200]] +>; +static_assert(std::variant_size_v == (size_t)StoryArgType::TIMED_LEGS + 1, "one StoryArgType per StoryArgValue type"); + +// A step's arguments by key. +using StoryActionArgs = std::map>; + +// The type `value` holds. +StoryArgType story_arg_type(const StoryArgValue& value); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp new file mode 100644 index 0000000000..22a3793a95 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp @@ -0,0 +1,143 @@ +/* Story Action Arg Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Checking a step's args against an action's spec and filling in its + * fallbacks. Built standalone (PA_STORY_DATA_STANDALONE), it runs without + * the application. + * + */ + +#include +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon_StoryActionArg.h" +#ifndef PA_STORY_DATA_STANDALONE +#include "Pokemon_StoryActionArg_Tests.h" +#endif + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// The args a Mart step takes, as a game declares them. +const StoryActionSpec& mart_spec(){ + static const StoryActionSpec spec{.kind = StoryStepKind::GAME, .name = "mart", .args = { + {.key = "map", .type = StoryArgType::WORD, .required = true, .fallback = std::nullopt, .why = "the Mart's map"}, + {.key = "budget", .type = StoryArgType::INTEGER, .required = true, .fallback = std::nullopt, .why = ""}, + {.key = "floor", .type = StoryArgType::INTEGER, .required = false, .fallback = int64_t(0), .why = ""}, + {.key = "if_present", .type = StoryArgType::BOOLEAN, .required = false, .fallback = std::nullopt, .why = ""}, + }}; + return spec; +} + +struct ArgsCase{ + // Args checked against the Mart's spec, then filled in. + std::string_view name; + struct Input{ + StoryActionArgs args; + }; + + // The errors joined by "; ", and the args with their fallbacks. + struct Expectation{ + std::string_view error = {}; + StoryActionArgs filled = {}; + }; + + Input input; + Expectation expectation; +}; + +const ArgsCase CASES[] = { + {.name = "mart", .input = {.args = {{"map", std::string("M")}, {"budget", int64_t(1500)}, {"if_present", true}}}, + .expectation = {.filled = {{"map", std::string("M")}, {"budget", int64_t(1500)}, {"floor", int64_t(0)}, {"if_present", true}}}}, + {.name = "fallback does not override", .input = {.args = {{"map", std::string("M")}, {"budget", int64_t(1)}, {"floor", int64_t(2)}}}, + .expectation = {.filled = {{"map", std::string("M")}, {"budget", int64_t(1)}, {"floor", int64_t(2)}}}}, + {.name = "unknown key", .input = {.args = {{"map", std::string("M")}, {"budget", int64_t(1)}, {"budgte", int64_t(1)}}}, + .expectation = {.error = "unknown argument \"budgte\"", .filled = {{"map", std::string("M")}, {"budget", int64_t(1)}, {"budgte", int64_t(1)}, {"floor", int64_t(0)}}}}, + {.name = "wrong type", .input = {.args = {{"map", std::string("M")}, {"budget", std::string("lots")}}}, + .expectation = {.error = "argument \"budget\" has the wrong type", .filled = {{"map", std::string("M")}, {"budget", std::string("lots")}, {"floor", int64_t(0)}}}}, + {.name = "missing required", .input = {.args = {{"budget", int64_t(1)}}}, + .expectation = {.error = "missing argument \"map\" (the Mart's map)", .filled = {{"budget", int64_t(1)}, {"floor", int64_t(0)}}}}, +}; + + +// "" when `test` reads as expected, else what differs. +std::string check_case(const ArgsCase& test){ + std::string error; + for (const std::string& each : story_args_errors(mart_spec(), test.input.args)){ + error += (error.empty() ? "" : "; ") + each; + } + if (error != test.expectation.error){ + return std::format("expected error \"{}\", got \"{}\"", test.expectation.error, error); + } + if (with_fallbacks(mart_spec(), test.input.args) != test.expectation.filled){ + return "filled in other args"; + } + const StoryActionArgs& args = test.expectation.filled; + const int64_t* floor = value_if_at_it(args, args.find("floor")); + if (floor == nullptr || *floor != story_arg(args, "floor")){ + return "reads floor otherwise"; + } + return ""; +} + + +#ifndef PA_STORY_DATA_STANDALONE + +class StoryActionArgTest : public UnitTest{ +public: + explicit StoryActionArgTest(ArgsCase test) + : UnitTest(std::format("Pokemon::StoryActionArg - {}", test.name)) + , m_case(test) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string error = check_case(m_case); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } + +private: + ArgsCase m_case; +}; + +#endif + + +} // namespace + + +#ifndef PA_STORY_DATA_STANDALONE + +void add_tests_StoryActionArg(UnitTestDatabase& database){ + for (const ArgsCase& test : CASES){ + database.add(test); + } +} + +#endif + + + +} // namespace Pokemon +} // namespace PokemonAutomation + + +#ifdef PA_STORY_DATA_STANDALONE + +int main(){ + int failed = 0; + for (const auto& test : PokemonAutomation::Pokemon::CASES){ + const std::string error = PokemonAutomation::Pokemon::check_case(test); + std::cout << test.name << ": " << (error.empty() ? "PASS" : error) << '\n'; + failed += !error.empty(); + } + return failed != 0; +} + +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.h new file mode 100644 index 0000000000..d20848c4c2 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.h @@ -0,0 +1,23 @@ +/* Story Action Arg Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryActionArg_Tests_H +#define PokemonAutomation_Pokemon_StoryActionArg_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for step args: checking them against an action's spec. +void add_tests_StoryActionArg(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.cpp new file mode 100644 index 0000000000..5839da93a0 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.cpp @@ -0,0 +1,62 @@ +/* Story Action Spec + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Pokemon_StoryActionSpec.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +const StoryArgSpec* find_spec(const StoryActionSpec& action, std::string_view key){ + for (const StoryArgSpec& spec : action.args){ + if (spec.key == key){ + return &spec; + } + } + return nullptr; +} + + +} // namespace + + +std::vector story_args_errors(const StoryActionSpec& spec, const StoryActionArgs& args){ + std::vector errors; + for (const auto& [key, value] : args){ + const StoryArgSpec* arg = find_spec(spec, key); + if (arg == nullptr){ + errors.emplace_back(std::format("unknown argument \"{}\"", key)); + }else if (story_arg_type(value) != arg->type){ + errors.emplace_back(std::format("argument \"{}\" has the wrong type", key)); + } + } + for (const StoryArgSpec& arg : spec.args){ + if (arg.required && args.find(arg.key) == args.end()){ + errors.emplace_back(std::format("missing argument \"{}\"{}", arg.key, arg.why.empty() ? "" : std::format(" ({})", arg.why))); + } + } + return errors; +} + +StoryActionArgs with_fallbacks(const StoryActionSpec& spec, StoryActionArgs args){ + for (const StoryArgSpec& arg : spec.args){ + if (arg.fallback){ + args.try_emplace(arg.key, *arg.fallback); + } + } + return args; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h new file mode 100644 index 0000000000..f9deb09ebb --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h @@ -0,0 +1,56 @@ +/* Story Action Spec + * + * From: https://github.com/PokemonAutomation/ + * + * What an action declares: the kind of step it does, its name and the + * args it takes, with their types and fallbacks (Pokemon_StoryActionArg.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryActionSpec_H +#define PokemonAutomation_Pokemon_StoryActionSpec_H + +#include +#include +#include +#include "Pokemon_StoryActionArg.h" +#include "Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// One argument an action takes. A missing optional one reads as `fallback` +// when it has one. +struct StoryArgSpec{ + std::string key; + StoryArgType type = StoryArgType::WORD; + bool required = false; + std::optional fallback; + // What it is for, shown in lint errors. + std::string why; +}; + +// An action: the kind of step it does, its name and the args it takes. +struct StoryActionSpec{ + StoryStepKind kind = StoryStepKind::GAME; + std::string name; + std::vector args; + // It reads or presses through screens only a console shows (menus, a + // keyboard, a battle AI): the engine refuses it on any other backend + // (StoryBackendKind) with the failure "console_only". + bool console_only = false; +}; + +// Each way `args` don't fit `spec`: a key it doesn't name, a value of +// another type, a required one missing. Empty when they fit. +std::vector story_args_errors(const StoryActionSpec& spec, const StoryActionArgs& args); + +// `args` with each missing optional arg of `spec` set to its fallback. +StoryActionArgs with_fallbacks(const StoryActionSpec& spec, StoryActionArgs args); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryBreakpoints.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryBreakpoints.cpp new file mode 100644 index 0000000000..8298ae45ce --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryBreakpoints.cpp @@ -0,0 +1,91 @@ +/* Story Breakpoints + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Pokemon_StoryBreakpoints.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string story_step_pause_label(std::string_view checkpoint_id, size_t step_index, std::string_view step_name){ + return std::format("{}/{} {}", checkpoint_id, step_index + 1, step_name); +} + +std::string story_leg_pause_label( + size_t index, size_t count, Direction direction, int tiles, const std::optional& destination +){ + std::string label = std::format("leg {}/{} {} {}", index + 1, count, direction_name(direction), tiles); + if (destination){ + label += std::format(" -> ({}, {})", destination->x, destination->y); + } + return label; +} + + +StoryPausePoints::StoryPausePoints(StoryBreakpoints mode, StoryPauseHook hook) + : m_mode(mode) + , m_hook(std::move(hook)) +{} + +void StoryPausePoints::set_log(std::function log){ + m_log = std::move(log); +} + +void StoryPausePoints::before_step(const std::string& label){ + m_step_label = label; + if (m_mode != StoryBreakpoints::OFF){ + pause(label); + } +} + +void StoryPausePoints::before_leg(const std::string& leg_label){ + if (m_mode == StoryBreakpoints::LEGS){ + pause(std::format("{} {}", m_step_label, leg_label)); + } +} + +void StoryPausePoints::pause(const std::string& label){ + if (!m_hook){ + return; + } + if (m_log){ + m_log(std::format("[Break] {}: paused", label)); + } + m_hook(label); + if (m_log){ + m_log(std::format("[Break] {}: continued", label)); + } +} + + +namespace{ + +StoryPauseWait& installed_wait(){ + static StoryPauseWait wait; + return wait; +} + +} // namespace + +void set_story_pause_wait(StoryPauseWait wait){ + installed_wait() = std::move(wait); +} + +StoryPauseHook make_story_pause_hook(CancellableScope& scope){ + if (!installed_wait()){ + return {}; + } + return [&scope](std::string_view label){ + installed_wait()(label, scope); + }; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryBreakpoints.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryBreakpoints.h new file mode 100644 index 0000000000..920e6bf16a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryBreakpoints.h @@ -0,0 +1,97 @@ +/* Story Breakpoints + * + * From: https://github.com/PokemonAutomation/ + * + * A debugger's breakpoints for a story run: the program pauses before each + * step, or before each leg of a walk too, so the user can look at the + * console and then continue. The engine and the walk action call + * StoryPausePoints at those points; what a pause does is the game's + * StoryGame::pause_point hook. A normal build installs no wait + * (set_story_pause_wait()), so a pause point costs a log line and never + * blocks; a lab build installs one that waits for the user. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryBreakpoints_H +#define PokemonAutomation_Pokemon_StoryBreakpoints_H + +#include +#include +#include +#include +#include "Common/Cpp/CancellableScope.h" +#include "Pokemon/Navigation/Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Where a run pauses. +enum class StoryBreakpoints{ + // Nowhere. + OFF, + // Before each step. + STEPS, + // Before each step and each leg of a walk. + LEGS, +}; + +// "12.03/5 pallet_shore": the checkpoint, the step's place in it (from 1) +// and its name. +std::string story_step_pause_label(std::string_view checkpoint_id, size_t step_index, std::string_view step_name); + +// "leg 2/5 east 4 -> (10, 10)": leg `index` (from 0) of `count`, and the +// tile it ends on when the walk started on one known tile. +std::string story_leg_pause_label( + size_t index, size_t count, Direction direction, int tiles, const std::optional& destination +); + + +// What a pause point does when it is reached, given its full label. It +// returns when the run goes on, or when `scope` is cancelled. +using StoryPauseHook = std::function; + +// The pause points of one run. The engine owns it and hands it to actions. +class StoryPausePoints{ +public: + StoryPausePoints() = default; + StoryPausePoints(StoryBreakpoints mode, StoryPauseHook hook); + + // Where the engine logs "[Break]" lines. + void set_log(std::function log); + + // A step is about to run. Remembers `label` for the legs of the step + // and pauses when the mode asks for steps. + void before_step(const std::string& label); + // A leg is about to be walked: pauses, as " ", + // only in LEGS mode. + void before_leg(const std::string& leg_label); + // The label of the step under way ("12.03/5 pallet_shore"); empty before the first. + const std::string& step_label() const{ return m_step_label; } + +private: + void pause(const std::string& label); + + StoryBreakpoints m_mode = StoryBreakpoints::OFF; + StoryPauseHook m_hook; + std::function m_log; + std::string m_step_label; +}; + + +// The wait a lab build installs, called with the label and the run's scope. +// It returns when the user continues or `scope` is cancelled. Set once, +// before any program runs. Not installed: pause points do not block. +using StoryPauseWait = std::function; +// Installs it; an empty wait removes it. +void set_story_pause_wait(StoryPauseWait wait); + +// The hook for StoryGame::pause_point: the installed wait on `scope`, or +// nothing when none is installed. `scope` must outlive the hook. +StoryPauseHook make_story_pause_hook(CancellableScope& scope); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.cpp new file mode 100644 index 0000000000..aade2b3809 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.cpp @@ -0,0 +1,32 @@ +/* Story Checks + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryCheckLevel.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string story_check_level_name(StoryCheckLevel level){ + switch (level){ + case StoryCheckLevel::TESTING: + return "testing"; + case StoryCheckLevel::THOROUGH: + return "thorough"; + case StoryCheckLevel::DEFAULT: + return "default"; + case StoryCheckLevel::FAST: + return "fast"; + case StoryCheckLevel::SPEEDRUN: + return "speedrun"; + } + return "?"; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h new file mode 100644 index 0000000000..86de9f8c76 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h @@ -0,0 +1,43 @@ +/* Story Check Level + * + * From: https://github.com/PokemonAutomation/ + * + * How much a story step reads the screen to confirm what it did. The + * program's options choose it (StoryRunOptions); each game decides what + * its steps check at each level. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryCheckLevel_H +#define PokemonAutomation_Pokemon_StoryCheckLevel_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How much a step reads the screen to confirm what it did. +enum class StoryCheckLevel{ + // Everything THOROUGH checks, each checkpoint run 3 times by default to + // make sure it really passes. + TESTING, + // Check everything for the user: Bag items, Pokemon stats, + // preconditions. + THOROUGH, + // Assume most things are fine; check the most important ones. + DEFAULT, + // Minimal checks. + FAST, + // Almost no checks, to be as fast as possible. + SPEEDRUN, +}; + +// Returns the readable string representation of a story check level. +std::string story_check_level_name(StoryCheckLevel level); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h new file mode 100644 index 0000000000..21de004f19 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h @@ -0,0 +1,48 @@ +/* Story Checkpoint + * + * From: https://github.com/PokemonAutomation/ + * + * A checkpoint of a tile game's story table as plain data: where its save + * leaves the player and its steps in order. build_story_checkpoint() + * (Pokemon_StoryStepExecutor.h) turns it into engine events. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryCheckpoint_H +#define PokemonAutomation_Pokemon_StoryCheckpoint_H + +#include +#include +#include +#include "Pokemon_DeclaredPose.h" +#include "Pokemon_StoryCheckpointMetadata.h" +#include "Pokemon_StoryPostconditions.h" +#include "Pokemon_StoryStep.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Milestone row in the story table grouping related steps and starting pose. +struct StoryCheckpoint{ + std::string id; + std::string title; + // Where its starting save leaves the player; none for a new game. + std::optional start; + std::vector steps; + // The steps' JSON ("events") as read, dumped compactly; what + // story_steps_hash() hashes. Empty for a checkpoint built in code. + std::string steps_json = {}; + // What must hold when it is done; checked on its own after a run. + // JSON: "metadata": {"postconditions": ...}. + StoryPostconditions postconditions = {}; + // Its phase and verification (JSON "metadata"), which decide when a + // run of it may save. + StoryCheckpointMetadata metadata = {}; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.cpp new file mode 100644 index 0000000000..fb6eac85fd --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.cpp @@ -0,0 +1,37 @@ +/* Story Checkpoint Metadata + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryCheckpointMetadata.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string story_phase_name(StoryPhase phase){ + switch (phase){ + case StoryPhase::TESTING: + return "testing"; + case StoryPhase::VERIFICATION: + return "verification"; + case StoryPhase::REPRODUCTION: + return "reproduction"; + } + return "?"; +} + +std::optional read_story_phase(std::string_view name){ + for (StoryPhase phase : {StoryPhase::TESTING, StoryPhase::VERIFICATION, StoryPhase::REPRODUCTION}){ + if (story_phase_name(phase) == name){ + return phase; + } + } + return std::nullopt; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h new file mode 100644 index 0000000000..0a305e0591 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h @@ -0,0 +1,69 @@ +/* Story Checkpoint Metadata + * + * From: https://github.com/PokemonAutomation/ + * + * What a checkpoint's JSON says about the checkpoint rather than how to + * play it: its phase (autostory/SAVE_POLICY.md on the notes branch), the + * steps it was verified with, and where it came from. The engine picks + * the save mode from the phase, and only while the steps still hash to + * the verified ones (Engine/Pokemon_StoryEnginePolicy.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryCheckpointMetadata_H +#define PokemonAutomation_Pokemon_StoryCheckpointMetadata_H + +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Where a checkpoint stands. It moves forward only on passes; a change to +// its steps moves it back to TESTING. +enum class StoryPhase{ + // New or changed: one run, never saves. + TESTING, + // Passed its test: 2-3 runs from the same start save, then one save. + VERIFICATION, + // Verified: a playthrough saves at its end. + REPRODUCTION, +}; + +// The wire and log name of a phase: "testing", "verification", "reproduction". +std::string story_phase_name(StoryPhase phase); + +// The phase named `name`; none for another name. +std::optional read_story_phase(std::string_view name); + +// The runs that moved the checkpoint out of testing, as recorded. +struct StoryVerification{ + // story_steps_hash() of the steps those runs ran: "sha256:". + std::string steps_hash = {}; + // The build those runs used (a commit). + std::string build = {}; + std::string date = {}; + // Passes out of runs, e.g. "3/3". + std::string runs = {}; + + bool operator==(const StoryVerification& other) const = default; +}; + +// A checkpoint's "metadata" object, less its postconditions, which the +// checkpoint keeps beside its steps (StoryCheckpoint::postconditions). +struct StoryCheckpointMetadata{ + StoryPhase phase = StoryPhase::TESTING; + std::optional verified = std::nullopt; + // Where the steps came from: a walkthrough, a console recording. + std::string source = {}; + + bool operator==(const StoryCheckpointMetadata& other) const = default; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryPostconditions.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryPostconditions.h new file mode 100644 index 0000000000..5b3cd7df37 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryPostconditions.h @@ -0,0 +1,43 @@ +/* Story Postconditions + * + * From: https://github.com/PokemonAutomation/ + * + * What must hold once a checkpoint is done, as plain data from its plan: + * where the player stands, what the Bag holds, which story flags moved. + * check_postconditions() (Pokemon_StoryPostconditionCheck.h) checks them + * against what the game read, as a step of its own after the run. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryPostconditions_H +#define PokemonAutomation_Pokemon_StoryPostconditions_H + +#include +#include +#include +#include "Pokemon_GridPose.h" +#include "Pokemon_StoryActionArg.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The end state a checkpoint's plan promises: position, Bag items and flags. +struct StoryPostconditions{ + // Where the checkpoint ends; unset, it is the last step's target + // (checkpoint_end_pose()). + std::optional position; + // Each item's count in the Bag, exactly, by the game's item id + // ("LIFT_KEY", "RARE_CANDY"). + std::vector items; + // Story flags that must be set: a trainer beaten, a door open. + std::vector flags; + + bool operator==(const StoryPostconditions& other) const = default; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.cpp new file mode 100644 index 0000000000..7fbeebf500 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.cpp @@ -0,0 +1,43 @@ +/* Story Save Mode + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StorySaveMode.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string story_save_mode_name(StorySaveMode mode){ + switch (mode){ + case StorySaveMode::NONE: + return "none"; + case StorySaveMode::AFTER_VERIFICATION: + return "after_verification"; + case StorySaveMode::PER_CHECKPOINT: + return "per_checkpoint"; + } + return "?"; +} + +bool story_save_allowed(StorySaveMode mode, CheckpointVerdict verdict, SavePoint point){ + if (verdict != CheckpointVerdict::PASSED){ + return false; + } + switch (mode){ + case StorySaveMode::NONE: + return false; + case StorySaveMode::AFTER_VERIFICATION: + return point == SavePoint::RUN_END; + case StorySaveMode::PER_CHECKPOINT: + return true; + } + return false; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.h new file mode 100644 index 0000000000..c06b0f52c5 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.h @@ -0,0 +1,59 @@ +/* Story Save Mode + * + * From: https://github.com/PokemonAutomation/ + * + * When an AutoStory run may save the game. A run's own verdict can be + * wrong (a warp confirmed on the next floor while the player is still on + * the one before), and a save made then overwrites the only good one. So a segment + * under test never saves, a verified one saves once at its end, and only + * a playthrough of verified segments saves at each checkpoint. + * + */ + +#ifndef PokemonAutomation_Pokemon_StorySaveMode_H +#define PokemonAutomation_Pokemon_StorySaveMode_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// When a run saves. A failed run never saves, in any mode. +enum class StorySaveMode{ + // Testing: never save; the save the run started from stays. + NONE, + // Verification: save once, at the end of a run that passed. + AFTER_VERIFICATION, + // Reproduction (a playthrough of verified segments): save at the end + // of each checkpoint that passed. + PER_CHECKPOINT, +}; + +// Returns the wire and log name of a save mode: "none", "after_verification", "per_checkpoint". +std::string story_save_mode_name(StorySaveMode mode); + +// How a checkpoint ended: passed (and its postconditions, where checked, +// did not fail) or not. +enum class CheckpointVerdict{ + PASSED, + FAILED, +}; + +// Where a save would be made. +enum class SavePoint{ + // A checkpoint's end, with more checkpoints of the run after it. + CHECKPOINT_END, + // The last checkpoint's end: the run's end state. + RUN_END, +}; + +// Whether a run in `mode` saves at `point` after a checkpoint that ended +// as `verdict`. +bool story_save_allowed(StorySaveMode mode, CheckpointVerdict verdict, SavePoint point); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.cpp new file mode 100644 index 0000000000..cd935cb96e --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.cpp @@ -0,0 +1,38 @@ +/* Story Segment Types + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StorySegmentTypes.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +void record_story_counts(const StoryRunCounts& counts, AutoStoryStats& stats){ + stats.m_segments_started += counts.segments; + stats.m_checkpoints_started += counts.checkpoints; + stats.m_resets += counts.resets; +} + +bool CheckpointRun::one_shot() const{ + return passed && attempts == 1; +} + +size_t SegmentReport::one_shot_passes() const{ + size_t count = 0; + for (const CheckpointRun& run : runs){ + count += run.one_shot() ? 1 : 0; + } + return count; +} + +StoryRunCounts SegmentReport::story_counts() const{ + return StoryRunCounts{.segments = 1, .checkpoints = runs.size(), .resets = reloads}; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h new file mode 100644 index 0000000000..898690f9eb --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h @@ -0,0 +1,91 @@ +/* Story Segment Types + * + * From: https://github.com/PokemonAutomation/ + * + * The plain data of a segment run (Pokemon_StorySegments.h): its policy, + * the range of checkpoints to run and the report of what happened. + * + */ + +#ifndef PokemonAutomation_Pokemon_StorySegmentTypes_H +#define PokemonAutomation_Pokemon_StorySegmentTypes_H + +#include +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_AutoStoryStats.h" +#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" +#include "Pokemon_StorySaveMode.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Retry and timeout configuration for story segment execution. +struct SegmentPolicy{ + // Runs of one checkpoint, reloading its save between them, before the + // segment stops. 1 stops at the first failure without reloading, leaving + // the game where it failed for a look. + size_t attempts_per_checkpoint = 3; + // When the run saves. In the other modes no checkpoint after the first + // has a save at its start, so only the first is retried with a reload. + // The options' default is NONE; the engine's stays the playthrough's. + StorySaveMode save_mode = StorySaveMode::PER_CHECKPOINT; +}; + +// The checkpoints to run, by id, both inclusive. An unset end is the +// segment's first or last checkpoint. +struct SegmentRange{ + std::optional from; + std::optional to; +}; + + +// What a story run adds to the program's stats. +struct StoryRunCounts{ + size_t segments = 0; + // Checkpoints started, passed or not. + size_t checkpoints = 0; + // Game resets or reloads after failed attempts. + size_t resets = 0; +}; + +// Adds `counts` to the shared AutoStory stats. +void record_story_counts(const StoryRunCounts& counts, AutoStoryStats& stats); + + +// Summary of checkpoint attempts and pass status. +struct CheckpointRun{ + std::string id; + bool passed = false; + size_t attempts = 0; + + bool one_shot() const; +}; + +// Execution results and failure diagnostics for a story segment run. +struct SegmentReport{ + bool completed = false; + // Both empty when nothing failed; the event is empty when a start + // check, an end check, a save or a reload failed. + std::string failed_checkpoint; + std::string failed_event; + Outcome failure; + size_t checkpoints_run = 0; + // Reloads after failed attempts. + size_t reloads = 0; + // Each checkpoint run, in order, the failed one last. + std::vector runs; + + size_t one_shot_passes() const; + // What the run adds to the program's stats (record_story_counts()): + // the segment, each checkpoint it started, each reload. + StoryRunCounts story_counts() const; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h new file mode 100644 index 0000000000..4500111b71 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h @@ -0,0 +1,60 @@ +/* Story Step + * + * From: https://github.com/PokemonAutomation/ + * + * One step of a tile game's story (FRLG, BDSP) as plain data: its kind, + * the action that does it and the action's args. A game's executor does it + * (Pokemon_StoryStepExecutor.h); the shared JSON reads and writes it + * (Data/Pokemon_StoryStepJson.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStep_H +#define PokemonAutomation_Pokemon_StoryStep_H + +#include +#include +#include +#include "Pokemon_DeclaredPose.h" +#include "Pokemon_StoryActionArg.h" +#include "Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Specification of an atomic story task with actions and postconditions. +struct StoryStep{ + StoryStepKind kind = StoryStepKind::TALK; + std::string name; + std::string why; + + // How the step does its kind: one of the built-in actions + // (Pokemon_BuiltinStoryActions.h) or the game's own; for a GAME step, the + // game's action. Empty is the kind's default action. + std::string action; + // The arguments the action reads, parsed against its spec when the + // game loads the step, with the spec's fallbacks filled in. + StoryActionArgs args; + + // Skipped when all of these hold (and there is at least one): names + // the game's executor answers (StoryStepExecutor::holds()), run flags + // unless the game reads them off the screen. + std::vector skip_if; + // Preparation for what follows, done once per save: a TEACH, a check, + // a read. Once it has succeeded and changed nothing + // (Outcome::changed_nothing), the attempts after a reload of the same + // save skip it, so a retry goes from the reload straight to the + // battle. One that changed the game (a TM taught) runs again, as the + // reload undid it. Only with build_story_checkpoint()'s PreparedSteps. + bool once_per_save = false; + // Where the step leaves the player, when its action does not say: the + // end of a scene that moves the player. + std::optional pose_after; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp new file mode 100644 index 0000000000..28b755779b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp @@ -0,0 +1,52 @@ +/* Story Step Kind + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string story_step_kind_name(StoryStepKind kind){ + switch (kind){ + case StoryStepKind::NEW_GAME: + return "NEW_GAME"; + case StoryStepKind::OPTIONS: + return "OPTIONS"; + case StoryStepKind::ROUTE: + return "ROUTE"; + case StoryStepKind::LEGS: + return "LEGS"; + case StoryStepKind::STEP: + return "STEP"; + case StoryStepKind::TALK: + return "TALK"; + case StoryStepKind::ANSWER: + return "ANSWER"; + case StoryStepKind::MASH: + return "MASH"; + case StoryStepKind::BATTLE: + return "BATTLE"; + case StoryStepKind::TRAIN: + return "TRAIN"; + case StoryStepKind::HEAL: + return "HEAL"; + case StoryStepKind::SHOP: + return "SHOP"; + case StoryStepKind::SAVE: + return "SAVE"; + case StoryStepKind::READY: + return "READY"; + case StoryStepKind::GAME: + return "GAME"; + } + return "?"; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h new file mode 100644 index 0000000000..a3670b8c6c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h @@ -0,0 +1,45 @@ +/* Story Step Kind + * + * From: https://github.com/PokemonAutomation/ + * + * The kinds of story step the tile games (FRLG, BDSP) share. A game's + * executor does each kind its own way (Pokemon_StoryStepExecutor.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStepKind_H +#define PokemonAutomation_Pokemon_StoryStepKind_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Action category classification for individual story steps. +enum class StoryStepKind{ + NEW_GAME, // title screen (no save) to the first room + OPTIONS, // the game's options as the story needs them + ROUTE, // plan and walk to `target` + LEGS, // walk `legs` as given + STEP, // one step `direction`: onto a trigger, into a door + TALK, // A at what the player faces + ANSWER, // text to a YES/NO, then `yes` + MASH, // text until the overworld is back: a scene + BATTLE, // text into a battle, fight it, text to the overworld + TRAIN, // fight `battles` wild battles where the player stands + HEAL, // the nurse, from in front of her or of the Center's door + SHOP, // `items` from a shop + SAVE, // save the game where the player stands + READY, // before a big battle: items, and the nurse at `target` if they can't + GAME, // a step only this game has, named by `action` +}; + +// Returns the readable string representation of a story step kind. +std::string story_step_kind_name(StoryStepKind kind); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.cpp new file mode 100644 index 0000000000..0663f79588 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.cpp @@ -0,0 +1,30 @@ +/* Direction + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_Direction.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string direction_name(Direction direction){ + switch (direction){ + case Direction::NORTH: + return "north"; + case Direction::EAST: + return "east"; + case Direction::SOUTH: + return "south"; + case Direction::WEST: + return "west"; + } + return "?"; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.h new file mode 100644 index 0000000000..5024b3ec69 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Direction.h @@ -0,0 +1,36 @@ +/* Direction + * + * From: https://github.com/PokemonAutomation/ + * + * The four cardinal directions the player can face or move in. + * + */ + +#ifndef PokemonAutomation_Pokemon_Direction_H +#define PokemonAutomation_Pokemon_Direction_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Row 0 is the top of a map, so SOUTH increases y. +enum class Direction{ + NORTH, + EAST, + SOUTH, + WEST, +}; +// Array containing all four cardinal directions. +constexpr Direction ALL_DIRECTIONS[] = { + Direction::NORTH, Direction::EAST, Direction::SOUTH, Direction::WEST, +}; +// Returns the lowercase name string of a cardinal direction. +std::string direction_name(Direction direction); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.cpp new file mode 100644 index 0000000000..84fa47bcb1 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.cpp @@ -0,0 +1,35 @@ +/* Grid + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +TilePos TilePos::next(Direction direction) const{ + switch (direction){ + case Direction::NORTH: + return {x, y - 1}; + case Direction::EAST: + return {x + 1, y}; + case Direction::SOUTH: + return {x, y + 1}; + case Direction::WEST: + return {x - 1, y}; + } + return *this; +} + +std::string to_string(const TilePos& pos){ + return std::format("({}, {})", pos.x, pos.y); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.h new file mode 100644 index 0000000000..6fda4044c8 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.h @@ -0,0 +1,78 @@ +/* Grid + * + * From: https://github.com/PokemonAutomation/ + * + * Tiles on an overworld grid, shared by the games that + * move the player a tile at a time. + * + */ + +#ifndef PokemonAutomation_Pokemon_Grid_H +#define PokemonAutomation_Pokemon_Grid_H + +#include +#include +#include +#include +#include +#include "Pokemon_Direction.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Grid coordinate with integer x and y components. +struct TilePos{ + int x = 0; + int y = 0; + + TilePos next(Direction direction) const; + bool operator==(const TilePos& other) const = default; + // x, then y: an order for sets and maps of tiles, not a walking order. + auto operator<=>(const TilePos& other) const = default; +}; +// Formats a TilePos as "(x, y)". +std::string to_string(const TilePos& pos); + + +// One value per tile of a map, row by row from the top. +template +struct Grid{ + int width = 0; + int height = 0; + std::vector cells; + + bool contains(const TilePos& pos) const{ + return 0 <= pos.x && pos.x < width && 0 <= pos.y && pos.y < height; + } + // `pos` must be inside the grid. + const Cell& at(const TilePos& pos) const{ + return cells[(size_t)pos.y * width + pos.x]; + } +}; +// The cell at `pos` of `grid`, to change it; `pos` must be inside the grid. +// A free function, so that Grid stays a plain value whose methods only read. +template +Cell& cell_at(const TilePos& pos, Grid& grid); + +template +Cell& cell_at(const TilePos& pos, Grid& grid){ + return grid.cells[(size_t)pos.y * grid.width + pos.x]; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation + + +// Hash specialization for TilePos. +template <> +struct std::hash{ + size_t operator()(const PokemonAutomation::Pokemon::TilePos& pos) const{ + return std::hash()(((long long)pos.x << 32) ^ (unsigned)pos.y); + } +}; + + +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index f534e8dd22..5d01544c0d 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -912,6 +912,13 @@ file(GLOB LIBRARY_SOURCES Source/CommonTools/Options/TrainOCRModeOption.h Source/CommonTools/Resources/SpriteDatabase.cpp Source/CommonTools/Resources/SpriteDatabase.h + Source/CommonTools/ScreenEvents/ScreenEventLog.h + Source/CommonTools/ScreenEvents/ScreenEvents.cpp + Source/CommonTools/ScreenEvents/ScreenEvents.h + Source/CommonTools/ScreenEvents/ScreenEvents_Tests.cpp + Source/CommonTools/ScreenEvents/ScreenEvents_Tests.h + Source/CommonTools/ScreenEvents/ScreenEventTypes.h + Source/CommonTools/ScreenEvents/ScreenFades.h Source/CommonTools/StartupChecks/StartProgramChecks.cpp Source/CommonTools/StartupChecks/StartProgramChecks.h Source/CommonTools/StartupChecks/VideoResolutionCheck.cpp @@ -1445,6 +1452,64 @@ 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_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/Pokemon_BuiltinStoryActions.cpp + Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h + Source/Pokemon/AutoStory/Pokemon_MapUtil.h + Source/Pokemon/AutoStory/Pokemon_StoryCheckpointTypes.h + Source/Pokemon/AutoStory/Pokemon_StoryEvent.h + Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp + Source/Pokemon/AutoStory/Pokemon_StoryEvents.h + Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.h + Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.cpp + Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses.h + Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryFailureClasses_Tests.h + Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp + Source/Pokemon/AutoStory/Pokemon_StoryLog.h + Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.h + Source/Pokemon/AutoStory/Pokemon_StoryOutcome.h + Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.cpp + Source/Pokemon/AutoStory/Pokemon_StoryOutcomeClass.h + Source/Pokemon/AutoStory/Pokemon_StoryPose.h + Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp + Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.h + Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.h + Source/Pokemon/AutoStory/Pokemon_TilePose.cpp + Source/Pokemon/AutoStory/Pokemon_TilePose.h + Source/Pokemon/AutoStory/Types/Pokemon_DeclaredPose.h + Source/Pokemon/AutoStory/Types/Pokemon_GridPose.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryBreakpoints.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryBreakpoints.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryPostconditions.h + Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StorySaveMode.h + Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StorySegmentTypes.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h Source/Pokemon/Inference/Pokemon_AbilityReader.cpp Source/Pokemon/Inference/Pokemon_AbilityReader.h Source/Pokemon/Inference/Pokemon_BerryNameReader.cpp @@ -1467,6 +1532,10 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Inference/Pokemon_TrainPokemonOCR.h Source/Pokemon/Inference/Pokemon_TypeReader.cpp Source/Pokemon/Inference/Pokemon_TypeReader.h + Source/Pokemon/Navigation/Pokemon_Direction.cpp + Source/Pokemon/Navigation/Pokemon_Direction.h + Source/Pokemon/Navigation/Pokemon_Grid.cpp + Source/Pokemon/Navigation/Pokemon_Grid.h Source/Pokemon/Options/Pokemon_BoxSortingTable.cpp Source/Pokemon/Options/Pokemon_BoxSortingTable.h Source/Pokemon/Options/Pokemon_EncounterBotOptions.h From 5236786c69bab102ea0c2d3ae048d545994ff574 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 14 Nov 2026 23:44:30 -0800 Subject: [PATCH 7/8] AutoStory tests: register the shared suites through add_tests_AutoStory() Keeps the unit test runner's list under the function length limit. --- .../ComputerPrograms_UnitTestRunner.cpp | 16 +------ .../AutoStory/Pokemon_AutoStory_Tests.h | 42 +++++++++++++++++++ SerialPrograms/cmake/SourceFiles.cmake | 1 + 3 files changed, 45 insertions(+), 14 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index f4665c9940..6cc20db2fc 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -16,15 +16,9 @@ #include "Common/Qt/QtThreadPool_Tests.h" #include "Kernels/Kernels_Tests.h" #include "Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h" +#include "Pokemon/AutoStory/Pokemon_AutoStory_Tests.h" #include "Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.h" #include "Pokemon/AutoStory/Pokemon_CheckpointId_Tests.h" -#include "Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.h" -#include "Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h" -#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.h" -#include "Pokemon/AutoStory/Pokemon_StoryEvents_Tests.h" -#include "Pokemon/AutoStory/Pokemon_StoryFailureClasses_Tests.h" -#include "Pokemon/AutoStory/Pokemon_StoryLog_Tests.h" -#include "Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.h" #include "CommonFramework/AudioPipeline/AudioInfo_Tests.h" #include "CommonFramework/AudioPipeline/Tools/ChannelMixer.h" #include "CommonFramework/AudioPipeline/SinkPipeline_Tests.h" @@ -89,13 +83,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_AutoStorySelect(ret); Pokemon::add_tests_AutoStoryStats(ret); Pokemon::add_tests_CheckpointId(ret); - Pokemon::add_tests_AuthoredCheckpointJson(ret); - Pokemon::add_tests_StoryStepJson(ret); - Pokemon::add_tests_StoryStepExecutor(ret); - Pokemon::add_tests_StoryEvents(ret); - Pokemon::add_tests_StoryFailureClasses(ret); - Pokemon::add_tests_StoryLog(ret); - Pokemon::add_tests_StoryActionArg(ret); + Pokemon::add_tests_AutoStory(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); NintendoSwitch::add_tests_UpdatePopupDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h new file mode 100644 index 0000000000..3e21d5b8ba --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -0,0 +1,42 @@ +/* AutoStory Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The unit tests of the pieces every AutoStory program shares, story + * engine or not. add_tests_AutoStory() is the one entry point the unit + * test runner calls; a new shared AutoStory suite registers there. + * + */ + +#ifndef PokemonAutomation_Pokemon_AutoStory_Tests_H +#define PokemonAutomation_Pokemon_AutoStory_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Data/Pokemon_AuthoredCheckpointJson_Tests.h" +#include "Data/Pokemon_StoryStepJson_Tests.h" +#include "Pokemon_StoryEvents_Tests.h" +#include "Pokemon_StoryFailureClasses_Tests.h" +#include "Pokemon_StoryLog_Tests.h" +#include "Pokemon_StoryStepExecutor_Tests.h" +#include "Types/Pokemon_StoryActionArg_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers every shared AutoStory suite, for the unit test runner. +inline void add_tests_AutoStory(UnitTestDatabase& database){ + add_tests_StoryActionArg(database); + add_tests_StoryLog(database); + add_tests_StoryFailureClasses(database); + add_tests_StoryEvents(database); + add_tests_StoryStepExecutor(database); + add_tests_StoryStepJson(database); + add_tests_AuthoredCheckpointJson(database); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 5d01544c0d..91981fb7db 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1460,6 +1460,7 @@ file(GLOB LIBRARY_SOURCES 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/Pokemon_AutoStory_Tests.h Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.cpp Source/Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h Source/Pokemon/AutoStory/Pokemon_MapUtil.h From 609c6bae949608778daf6eeb900d0f80cdb00d1e Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 15 Nov 2026 12:34:13 -0800 Subject: [PATCH 8/8] AutoStory: drop CheckpointId; nothing in the PLZA chain uses it --- .../ComputerPrograms_UnitTestRunner.cpp | 2 - .../AutoStory/Pokemon_CheckpointId.cpp | 74 ---- .../Pokemon/AutoStory/Pokemon_CheckpointId.h | 67 ---- .../AutoStory/Pokemon_CheckpointId_Tests.cpp | 326 ------------------ .../AutoStory/Pokemon_CheckpointId_Tests.h | 23 -- SerialPrograms/cmake/SourceFiles.cmake | 4 - 6 files changed, 496 deletions(-) delete mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp delete mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.h delete mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp delete mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.h diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 6cc20db2fc..71060f8579 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -18,7 +18,6 @@ #include "Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h" #include "Pokemon/AutoStory/Pokemon_AutoStory_Tests.h" #include "Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.h" -#include "Pokemon/AutoStory/Pokemon_CheckpointId_Tests.h" #include "CommonFramework/AudioPipeline/AudioInfo_Tests.h" #include "CommonFramework/AudioPipeline/Tools/ChannelMixer.h" #include "CommonFramework/AudioPipeline/SinkPipeline_Tests.h" @@ -82,7 +81,6 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Kernels::add_tests(ret); Pokemon::add_tests_AutoStorySelect(ret); Pokemon::add_tests_AutoStoryStats(ret); - Pokemon::add_tests_CheckpointId(ret); Pokemon::add_tests_AutoStory(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp deleted file mode 100644 index 432f32333c..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/* AutoStory Checkpoint Id - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Pokemon_CheckpointId.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - -namespace{ - -// The value of two decimal digits, or nullopt if either is not a digit. -std::optional parse_two_digits(std::string_view text){ - if (text.size() != 2){ - return std::nullopt; - } - uint8_t value = 0; - for (char c : text){ - if (c < '0' || c > '9'){ - return std::nullopt; - } - value = (uint8_t)(value * 10 + (c - '0')); - } - return value; -} - -} // namespace - - - -std::optional CheckpointId::parse(std::string_view text){ - if ((text.size() != 5 && text.size() != 6) || text[2] != '.'){ - return std::nullopt; - } - std::optional segment = parse_two_digits(text.substr(0, 2)); - std::optional checkpoint = parse_two_digits(text.substr(3, 2)); - if (!segment || !checkpoint){ - return std::nullopt; - } - std::optional suffix; - if (text.size() == 6){ - const char letter = text[5]; - if (letter < 'a' || letter > 'z'){ - return std::nullopt; - } - suffix = letter; - } - return CheckpointId{*segment, *checkpoint, suffix}; -} - -std::string CheckpointId::to_string() const{ - std::string ret = std::format("{:02}.{:02}", m_segment, m_checkpoint); - if (m_suffix){ - ret += *m_suffix; - } - return ret; -} - -std::string CheckpointId::segment_string() const{ - return std::format("{:02}", m_segment); -} - - -bool starts_segment(std::optional previous, CheckpointId next){ - return !previous || previous->segment() != next.segment(); -} - - - -} // namespace Pokemon -} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.h deleted file mode 100644 index 7e5001266e..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId.h +++ /dev/null @@ -1,67 +0,0 @@ -/* AutoStory Checkpoint Id - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_CheckpointId_H -#define PokemonAutomation_Pokemon_CheckpointId_H - -#include -#include -#include -#include -#include - -namespace PokemonAutomation{ -namespace Pokemon{ - - -// An AutoStory checkpoint, written "SS.CC" with an optional lowercase -// letter: segment 03, checkpoint 08 is "03.08". A letter splits a checkpoint -// without renumbering the ones after it, e.g. FRLG's "12.02b" for a boss -// battle cut out of 12.02. Ids order by segment, then checkpoint, then -// letter: 12.02 < 12.02b < 12.02c < 12.03. parse() is the only way to build -// one, so every id is valid. -class CheckpointId{ -public: - // Reads two digits, a dot, two digits and at most one lowercase letter. - // Anything else ("3.08", "03.08B", "03.08bc", "03.08b1", "03-08", - // "03.08.01") returns nullopt. - static std::optional parse(std::string_view text); - - // "03.08", or "03.08b" with a suffix. - std::string to_string() const; - // "03". - std::string segment_string() const; - - uint8_t segment() const{ return m_segment; } - uint8_t checkpoint() const{ return m_checkpoint; } - // 'a' to 'z'. - std::optional suffix() const{ return m_suffix; } - - auto operator<=>(const CheckpointId&) const = default; - -private: - CheckpointId(uint8_t segment, uint8_t checkpoint, std::optional suffix) - : m_segment(segment) - , m_checkpoint(checkpoint) - , m_suffix(suffix) - {} - - uint8_t m_segment = 0; - uint8_t m_checkpoint = 0; - std::optional m_suffix; -}; - - -// Whether reaching `next` starts a segment: true for the first checkpoint of -// a run (`previous` is nullopt) and when the segment differs from the last -// checkpoint's. The suffix does not matter. -bool starts_segment(std::optional previous, CheckpointId next); - - - -} // namespace Pokemon -} // namespace PokemonAutomation -#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp deleted file mode 100644 index 9a507d7234..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp +++ /dev/null @@ -1,326 +0,0 @@ -/* AutoStory Checkpoint Id Tests - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include "Pokemon_CheckpointId.h" -#include "Pokemon_CheckpointId_Tests.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - -namespace{ - - -// Parse: text in, the id printed back out (nullopt when parse rejects it). - -struct ParseInput{ - std::string text; -}; - -struct ParsedId{ - std::string id; - std::string segment; -}; - -struct ParseExpectation{ - std::optional parsed; -}; - -struct ParseScenario{ - std::string name; - ParseInput input; - ParseExpectation expectation; -}; - -class Test_CheckpointIdParse : public UnitTest{ -public: - Test_CheckpointIdParse(ParseScenario scenario) - : UnitTest(std::format("Pokemon::CheckpointId::parse - {}", scenario.name)) - , m_scenario(std::move(scenario)) - {} - - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const std::optional got = CheckpointId::parse(m_scenario.input.text); - const ParseExpectation& expected = m_scenario.expectation; - if (!expected.parsed){ - if (got){ - return std::format("Expected \"{}\" to be rejected, got {}", m_scenario.input.text, got->to_string()); - } - return true; - } - if (!got){ - return std::format("Expected \"{}\" to parse, it was rejected", m_scenario.input.text); - } - if (got->to_string() != expected.parsed->id){ - return std::format("Expected id {}, got {}", expected.parsed->id, got->to_string()); - } - if (got->segment_string() != expected.parsed->segment){ - return std::format("Expected segment {}, got {}", expected.parsed->segment, got->segment_string()); - } - return true; - } - -private: - const ParseScenario m_scenario; -}; - - -// Ordering: two ids, how the first compares to the second. - -struct OrderInput{ - std::string left; - std::string right; -}; - -struct OrderExpectation{ - std::strong_ordering order; -}; - -struct OrderScenario{ - std::string name; - OrderInput input; - OrderExpectation expectation; -}; - -std::string_view order_name(std::strong_ordering order){ - if (order < 0){ - return "less"; - } - if (order > 0){ - return "greater"; - } - return "equal"; -} - -class Test_CheckpointIdOrder : public UnitTest{ -public: - Test_CheckpointIdOrder(OrderScenario scenario) - : UnitTest(std::format("Pokemon::CheckpointId order - {}", scenario.name)) - , m_scenario(std::move(scenario)) - {} - - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const std::optional left = CheckpointId::parse(m_scenario.input.left); - const std::optional right = CheckpointId::parse(m_scenario.input.right); - if (!left || !right){ - return std::format( - "Bad checkpoint id \"{}\" or \"{}\" in the test input", - m_scenario.input.left, m_scenario.input.right - ); - } - const std::strong_ordering got = *left <=> *right; - if (got != m_scenario.expectation.order){ - return std::format( - "Expected {} to be {} than {}, got {}", - m_scenario.input.left, - order_name(m_scenario.expectation.order), - m_scenario.input.right, - order_name(got) - ); - } - return true; - } - -private: - const OrderScenario m_scenario; -}; - - -// Segment starts: the checkpoints a run passes, in order, and the ones that -// start a segment. - -struct SegmentStartInput{ - std::vector passed; -}; - -struct SegmentStartExpectation{ - std::vector starts; -}; - -struct SegmentStartScenario{ - std::string name; - SegmentStartInput input; - SegmentStartExpectation expectation; -}; - -std::string join(const std::vector& ids){ - std::string ret; - for (const std::string& id : ids){ - if (!ret.empty()){ - ret += ", "; - } - ret += id; - } - return ret; -} - -class Test_CheckpointIdSegmentStart : public UnitTest{ -public: - Test_CheckpointIdSegmentStart(SegmentStartScenario scenario) - : UnitTest(std::format("Pokemon::CheckpointId starts_segment - {}", scenario.name)) - , m_scenario(std::move(scenario)) - {} - - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - std::vector got; - std::optional previous; - for (const std::string& text : m_scenario.input.passed){ - const std::optional next = CheckpointId::parse(text); - if (!next){ - return std::format("Bad checkpoint id \"{}\" in the test input", text); - } - if (starts_segment(previous, *next)){ - got.emplace_back(next->to_string()); - } - previous = next; - } - if (got != m_scenario.expectation.starts){ - return std::format( - "Expected segment starts [{}], got [{}]", - join(m_scenario.expectation.starts), join(got) - ); - } - return true; - } - -private: - const SegmentStartScenario m_scenario; -}; - - -void add_parse_tests(UnitTestDatabase& database){ - const std::vector parse_cases{ - {.name = "segment and checkpoint", .input = {.text = "03.08"}, .expectation = {.parsed = ParsedId{.id = "03.08", .segment = "03"}}}, - {.name = "first checkpoint", .input = {.text = "00.00"}, .expectation = {.parsed = ParsedId{.id = "00.00", .segment = "00"}}}, - {.name = "largest id", .input = {.text = "99.99"}, .expectation = {.parsed = ParsedId{.id = "99.99", .segment = "99"}}}, - {.name = "letter suffix", .input = {.text = "12.02b"}, .expectation = {.parsed = ParsedId{.id = "12.02b", .segment = "12"}}}, - {.name = "first letter", .input = {.text = "00.12a"}, .expectation = {.parsed = ParsedId{.id = "00.12a", .segment = "00"}}}, - {.name = "last letter", .input = {.text = "03.08z"}, .expectation = {.parsed = ParsedId{.id = "03.08z", .segment = "03"}}}, - {.name = "uppercase letter", .input = {.text = "03.08B"}, .expectation = {}}, - {.name = "two letters", .input = {.text = "03.08bc"}, .expectation = {}}, - {.name = "digit after the letter", .input = {.text = "03.08b1"}, .expectation = {}}, - {.name = "third checkpoint digit", .input = {.text = "03.081"}, .expectation = {}}, - {.name = "punctuation suffix", .input = {.text = "03.08!"}, .expectation = {}}, - {.name = "letter in the segment", .input = {.text = "0b.08"}, .expectation = {}}, - {.name = "one-digit segment", .input = {.text = "3.08"}, .expectation = {}}, - {.name = "one-digit checkpoint", .input = {.text = "03.8"}, .expectation = {}}, - {.name = "three-digit segment", .input = {.text = "100.08"}, .expectation = {}}, - {.name = "three-digit checkpoint", .input = {.text = "03.100"}, .expectation = {}}, - {.name = "no dot", .input = {.text = "0308"}, .expectation = {}}, - {.name = "other separator", .input = {.text = "03-08"}, .expectation = {}}, - {.name = "extra part", .input = {.text = "03.08.01"}, .expectation = {}}, - {.name = "segment only", .input = {.text = "03"}, .expectation = {}}, - {.name = "sign", .input = {.text = "+3.08"}, .expectation = {}}, - {.name = "spaces", .input = {.text = " 3.08"}, .expectation = {}}, - {.name = "empty", .input = {.text = ""}, .expectation = {}}, - }; - for (const ParseScenario& scenario : parse_cases){ - database.add(scenario); - } -} - -void add_order_tests(UnitTestDatabase& database){ - const std::vector order_cases{ - { - .name = "same id", - .input = {.left = "03.08", .right = "03.08"}, - .expectation = {.order = std::strong_ordering::equal}, - }, - { - .name = "later checkpoint in the same segment", - .input = {.left = "03.09", .right = "03.08"}, - .expectation = {.order = std::strong_ordering::greater}, - }, - { - .name = "segment wins over checkpoint", - .input = {.left = "02.99", .right = "03.00"}, - .expectation = {.order = std::strong_ordering::less}, - }, - { - .name = "no suffix before a suffix", - .input = {.left = "12.02", .right = "12.02b"}, - .expectation = {.order = std::strong_ordering::less}, - }, - { - .name = "suffixes in letter order", - .input = {.left = "12.02b", .right = "12.02c"}, - .expectation = {.order = std::strong_ordering::less}, - }, - { - .name = "suffix before the next checkpoint", - .input = {.left = "12.02c", .right = "12.03"}, - .expectation = {.order = std::strong_ordering::less}, - }, - { - .name = "same suffix", - .input = {.left = "12.02b", .right = "12.02b"}, - .expectation = {.order = std::strong_ordering::equal}, - }, - }; - for (const OrderScenario& scenario : order_cases){ - database.add(scenario); - } -} - -void add_segment_start_tests(UnitTestDatabase& database){ - const std::vector segment_cases{ - { - .name = "first checkpoint of a run starts its segment", - .input = {.passed = {"03.08"}}, - .expectation = {.starts = {"03.08"}}, - }, - { - .name = "checkpoints in one segment start it once", - .input = {.passed = {"03.08", "03.09", "03.10"}}, - .expectation = {.starts = {"03.08"}}, - }, - { - .name = "each new segment starts once", - .input = {.passed = {"02.04", "02.05", "03.00", "03.01", "04.00"}}, - .expectation = {.starts = {"02.04", "03.00", "04.00"}}, - }, - { - .name = "suffix does not start a segment", - .input = {.passed = {"12.01", "12.02", "12.02b", "12.03"}}, - .expectation = {.starts = {"12.01"}}, - }, - { - .name = "suffixed checkpoint can start a segment", - .input = {.passed = {"00.12", "00.12b", "01.00"}}, - .expectation = {.starts = {"00.12", "01.00"}}, - }, - { - .name = "empty run starts nothing", - .input = {.passed = {}}, - .expectation = {.starts = {}}, - }, - }; - for (const SegmentStartScenario& scenario : segment_cases){ - database.add(scenario); - } -} - - -} // namespace - - - -void add_tests_CheckpointId(UnitTestDatabase& database){ - add_parse_tests(database); - add_order_tests(database); - add_segment_start_tests(database); -} - - - -} // namespace Pokemon -} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.h deleted file mode 100644 index 37212aa763..0000000000 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.h +++ /dev/null @@ -1,23 +0,0 @@ -/* AutoStory Checkpoint Id Tests - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_CheckpointId_Tests_H -#define PokemonAutomation_Pokemon_CheckpointId_Tests_H - -#include "Common/Cpp/TestRunners/UnitTestDatabase.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -// Registers the tests for parsing, printing and ordering checkpoint ids. -void add_tests_CheckpointId(UnitTestDatabase& database); - - - -} // namespace Pokemon -} // namespace PokemonAutomation -#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 91981fb7db..ca732bbd69 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1556,10 +1556,6 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.h - Source/Pokemon/AutoStory/Pokemon_CheckpointId.cpp - Source/Pokemon/AutoStory/Pokemon_CheckpointId.h - Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.cpp - Source/Pokemon/AutoStory/Pokemon_CheckpointId_Tests.h Source/Pokemon/Pokemon_AdvRng.cpp Source/Pokemon/Pokemon_AdvRng.h Source/Pokemon/Pokemon_BdspRng.cpp