From f0e468b79b4d5b806119c06b2d6d4ef18644ce53 Mon Sep 17 00:00:00 2001 From: Dalton-V Date: Fri, 6 Nov 2026 23:45:48 -0600 Subject: [PATCH] Support custom dex template from RotomLabs --- .../PokemonHome/PokemonHome_Tests.cpp | 2 + .../PokemonHome_BoxSorterLivingDex.cpp | 101 +++++++++- .../Programs/PokemonHome_BoxSorterLivingDex.h | 6 + .../PokemonHome_BoxSorterLivingDex_Tests.cpp | 178 ++++++++++++++++++ .../PokemonHome_BoxSorterLivingDex_Tests.h | 22 +++ SerialPrograms/cmake/SourceFiles.cmake | 2 + 6 files changed, 308 insertions(+), 3 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex_Tests.h diff --git a/SerialPrograms/Source/VideoGames/PokemonHome/PokemonHome_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonHome/PokemonHome_Tests.cpp index 0ac5e1bd97..aadbdbed4b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonHome/PokemonHome_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonHome/PokemonHome_Tests.cpp @@ -17,6 +17,7 @@ #include "Inference/PokemonHome_SummaryReader.h" #include "Inference/PokemonHome_SummaryScreenDetector.h" #include "Inference/PokemonHome_TeraTypeReader.h" +#include "Programs/PokemonHome_BoxSorterLivingDex_Tests.h" #include "PokemonHome_Tests.h" namespace PokemonAutomation{ @@ -31,6 +32,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_BoxViewDetector(database); add_tests_ButtonDetector(database); add_tests_GigantamaxDetector(database); + add_tests_LivingDexTemplate(database); add_tests_OriginMarkReader(database); add_tests_SelectionArrowDetector(database); add_tests_ShinyDetector(database); diff --git a/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex.cpp b/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex.cpp index 8db9e688dc..aba02733f8 100644 --- a/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -71,6 +72,7 @@ std::unique_ptr BoxSorterLivingDex_Descriptor::make_stats() const{ } BoxSorterLivingDex::~BoxSorterLivingDex(){ + LIVING_DEX_STYLE.remove_listener(*this); OT_NAME_LANGUAGE.remove_listener(*this); }; @@ -107,10 +109,18 @@ BoxSorterLivingDex::BoxSorterLivingDex() {LivingDexStyle::POKEPC_SORTED_SPECIES, "pokepc_sorted_species", "PokePC Sorted by Species"}, {LivingDexStyle::POKEPC_SORTED_SPECIES_MINIMAL, "pokepc_sorted_species_minimal", "PokePC Sorted by Species (Minimal)"}, {LivingDexStyle::POKEPC_SPECIES_FIRST, "pokepc_species_first", "PokePC Species First"}, + {LivingDexStyle::CUSTOM, "custom", "Custom"}, }, LockMode::LOCK_WHILE_RUNNING, LivingDexStyle::SORTED_BY_FORMS ) + , CUSTOM_DEX_FILE( + "Custom Living Dex File:
Select a JSON template in the same format as the files in Resources/PokemonHome/DexTemplates.", + LockMode::LOCK_WHILE_RUNNING, + "", + "JSON Files (*.json)", + "Select a living dex JSON file..." + ) , SHINY_DEX( "Shiny Dex:
Enable or disable shiny dex mode.", LockMode::LOCK_WHILE_RUNNING, @@ -171,6 +181,7 @@ BoxSorterLivingDex::BoxSorterLivingDex() PA_ADD_OPTION(REJECT_BOX_START); PA_ADD_OPTION(REJECT_BOX_END); PA_ADD_OPTION(LIVING_DEX_STYLE); + PA_ADD_OPTION(CUSTOM_DEX_FILE); PA_ADD_OPTION(SHINY_DEX); PA_ADD_OPTION(OT_NAME_LANGUAGE); PA_ADD_OPTION(OT_NAME); @@ -182,10 +193,14 @@ BoxSorterLivingDex::BoxSorterLivingDex() BoxSorterLivingDex::on_config_value_changed(this); + LIVING_DEX_STYLE.add_listener(*this); OT_NAME_LANGUAGE.add_listener(*this); } void BoxSorterLivingDex::on_config_value_changed(void* object){ + CUSTOM_DEX_FILE.set_visibility( + LIVING_DEX_STYLE == LivingDexStyle::CUSTOM ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN + ); if (OT_NAME_LANGUAGE == Language::None){ OT_NAME.set_visibility(ConfigOptionState::HIDDEN); }else{ @@ -193,6 +208,72 @@ void BoxSorterLivingDex::on_config_value_changed(void* object){ } } +void validate_living_dex_template(const JsonValue& json, const std::string& path){ + const JsonArray* entries = json.to_array(); + if (entries == nullptr){ + throw ParseException(path + ": Expected a JSON array of living dex entries. Check the JSON syntax and outer square brackets."); + } + if (entries->empty()){ + throw ParseException(path + ": The living dex template must contain at least one entry."); + } + if (entries->size() > MAX_HOME_BOXES * 30){ + throw ParseException(path + ": The living dex template exceeds HOME's capacity of " + std::to_string(MAX_HOME_BOXES * 30) + " slots."); + } + + for (size_t i = 0; i < entries->size(); i++){ + const std::string location = path + " (entry " + std::to_string(i + 1) + ")"; + const JsonObject& obj = (*entries)[i].to_object_throw(location); + auto field = [&](const char* key, JsonType expected_type) -> const JsonValue&{ + const JsonValue& value = obj.get_value_throw(key, location); + if (value.type() != expected_type){ + throw JsonParseException(location, key, expected_type, value.type()); + } + return value; + }; + const std::string& species = field("species_slug", JsonType::STRING).to_string_throw(); + const std::string& form = field("form_slug", JsonType::STRING).to_string_throw(); + const std::string& slug = field("slug", JsonType::STRING).to_string_throw(); + const int64_t nat_id = field("natID", JsonType::INTEGER).to_integer_throw(); + const std::string& primary = field("primaryType", JsonType::STRING).to_string_throw(); + const bool gender_difference = field("has_gender_difference", JsonType::BOOLEAN).to_boolean_throw(); + if (nat_id < 0 || nat_id > std::numeric_limits::max()){ + throw ParseException(location + ": 'natID' must be an integer from 1 to 65535, or 0 for an empty slot."); + } + + PokemonType secondary_type = PokemonType::NONE; + const JsonValue* secondary = obj.get_value("secondaryType"); + if (secondary != nullptr && !secondary->is_null()){ + const std::string& type = field("secondaryType", JsonType::STRING).to_string_throw(); + secondary_type = POKEMON_TYPE_SLUGS().get_enum(type, PokemonType::NONE); + if (secondary_type == PokemonType::NONE && type != "none"){ + throw ParseException(location + ": Unknown 'secondaryType': '" + type + "'. Use a lowercase Pokemon type, or null/\"none\" for no secondary type."); + } + } + + // Bundled templates reserve empty slots with this placeholder entry. + if (nat_id == 0){ + if (species != "empty" || !form.empty() || !slug.empty() || !primary.empty() + || secondary_type != PokemonType::NONE || gender_difference + ){ + throw ParseException(location + ": An empty slot (natID 0) requires species_slug \"empty\", empty form_slug/slug/primaryType, no secondary type, and has_gender_difference false."); + } + continue; + } + + for (const char* key : {"species_slug", "form_slug", "slug"}){ + if (obj.get_string_throw(key, location).find_first_not_of(" \t\r\n") == std::string::npos){ + throw ParseException(location + ": '" + key + "' must not be blank. Use \"none\" for a Pokemon with no special form."); + } + } + if (POKEMON_TYPE_SLUGS().get_enum(primary, PokemonType::NONE) == PokemonType::NONE){ + throw ParseException(location + ": Unknown 'primaryType': '" + primary + "'. Use a lowercase Pokemon type such as \"normal\" or \"grass\"."); + } + if (gender_difference && !slug.ends_with("-male") && !slug.ends_with("-female")){ + throw ParseException(location + ": When 'has_gender_difference' is true, 'slug' must end with \"-male\" or \"-female\"."); + } + } +} + bool BoxSorterLivingDex::is_viable_for_dex( const LivingDexEntry& entry, const CollectedPokemonInfo& pokemonInfo, @@ -388,13 +469,27 @@ void BoxSorterLivingDex::program(SingleSwitchProgramEnvironment& env, ProControl case LivingDexStyle::POKEPC_SPECIES_FIRST: path = RESOURCE_PATH() + "PokemonHome/DexTemplates/pokepc_species_first.json"; break; + case LivingDexStyle::CUSTOM: + path = CUSTOM_DEX_FILE; + if (path.find_first_not_of(" \t\r\n") == std::string::npos){ + throw UserSetupError(env.logger(), "Select a Custom Living Dex File before starting the program."); + } + break; default: throw InternalProgramError( &env.logger(), PA_CURRENT_FUNCTION, "Invalid living dex style" ); } - JsonValue json = load_json_file(path); + JsonValue json; + try{ + json = load_json_file(path); + validate_living_dex_template(json, path); + }catch (const FileException& e){ + throw UserSetupError(env.logger(), "Unable to read the living dex template. Check that the selected file exists and is readable.\n" + e.message()); + }catch (const ParseException& e){ + throw UserSetupError(env.logger(), "Invalid living dex template:\n" + e.message()); + } const JsonArray& slugs = json.to_array_throw(path); std::vector living_dex_order; @@ -430,8 +525,6 @@ void BoxSorterLivingDex::program(SingleSwitchProgramEnvironment& env, ProControl // vector that will store data for each slot std::vector> living_dex_boxes_data; - exit_menus(env, context, VIDEO_DELAY.get()); - BoxCursor dest_cursor; BoxCursor nav_cursor((LIVING_DEX_START_BOX - 1), 0, 0); @@ -459,6 +552,8 @@ void BoxSorterLivingDex::program(SingleSwitchProgramEnvironment& env, ProControl ); } + exit_menus(env, context, VIDEO_DELAY.get()); + nav_cursor = populate_box_data(env, context, sort_preferences, living_dex_boxes_data, living_dex_box_count, nav_cursor, OT_NAME_LANGUAGE); dest_cursor = BoxCursor((REJECT_BOX_START - 1), 0, 0); diff --git a/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex.h b/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex.h index 82cfa6cda2..24602db6cd 100644 --- a/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex.h +++ b/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex.h @@ -8,6 +8,7 @@ #define PokemonAutomation_PokemonHome_BoxSorterLivingDex_H #include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/PathOption.h" #include "Common/Cpp/Options/SimpleIntegerOption.h" #include "Common/Cpp/Options/StringOption.h" #include "Common/Cpp/Options/TimeDurationOption.h" @@ -23,6 +24,9 @@ namespace NintendoSwitch{ namespace PokemonHome{ using namespace Pokemon; +// Throws ParseException with the file and entry location if the template is invalid. +void validate_living_dex_template(const JsonValue& json, const std::string& path); + class BoxSorterLivingDex_Descriptor : public SingleSwitchProgramDescriptor{ public: BoxSorterLivingDex_Descriptor(); @@ -66,6 +70,7 @@ class BoxSorterLivingDex : public SingleSwitchProgramInstance, public ConfigOpti POKEPC_SORTED_SPECIES, POKEPC_SORTED_SPECIES_MINIMAL, POKEPC_SPECIES_FIRST, + CUSTOM, }; // Checks if the given pokemon is viable for the living dex entry. @@ -95,6 +100,7 @@ class BoxSorterLivingDex : public SingleSwitchProgramInstance, public ConfigOpti // Living dex style. EnumDropdownOption LIVING_DEX_STYLE; + PathOption CUSTOM_DEX_FILE; // Dex filters BooleanCheckBoxOption SHINY_DEX; diff --git a/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex_Tests.cpp new file mode 100644 index 0000000000..eab45f0ef2 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex_Tests.cpp @@ -0,0 +1,178 @@ +/* Home Box Sorter Living Dex Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/GlobalAutoPaths.h" +#include "PokemonHome_BoxNavigation.h" +#include "PokemonHome_BoxSorterLivingDex.h" +#include "PokemonHome_BoxSorterLivingDex_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ + + +class Test_LivingDexTemplate : public UnitTest{ +public: + Test_LivingDexTemplate(std::string name, std::string input, std::string error = "", bool resource = false) + : UnitTest("PokemonHome::LivingDexTemplate - " + name) + , m_input(std::move(input)) + , m_error(std::move(error)) + , m_resource(resource) + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + const std::string path = m_resource ? RESOURCE_PATH() + "PokemonHome/DexTemplates/" + m_input : "custom-dex.json"; + try{ + JsonValue json = m_resource ? load_json_file(path) : parse_json(m_input); + validate_living_dex_template(json, path); + }catch (const ParseException& e){ + if (m_error.empty()){ + return UnitTestResult("Unexpected validation error: " + e.message()); + } + if (e.message().find(m_error) == std::string::npos || e.message().find(path) == std::string::npos){ + return UnitTestResult("Validation error lacks expected context '" + m_error + "': " + e.message()); + } + return true; + } + return m_error.empty() ? UnitTestResult(true) : UnitTestResult("Expected validation to fail: " + m_error); + } + +private: + std::string m_input; + std::string m_error; + bool m_resource; +}; + +class Test_LivingDexCustomOption : public UnitTest{ +public: + Test_LivingDexCustomOption() + : UnitTest("PokemonHome::LivingDexTemplate - Custom file visibility and settings") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + BoxSorterLivingDex sorter; + PathOption* file = nullptr; + for (ConfigOption* option : dynamic_cast(sorter.options()).options()){ + if (auto* path = dynamic_cast(option)){ + file = path; + } + } + if (file == nullptr || file->visibility() != ConfigOptionState::HIDDEN){ + return UnitTestResult("Custom file selector must be hidden for the default style."); + } + JsonObject settings; + settings["LIVING_DEX_STYLE"] = "custom"; + settings["CUSTOM_DEX_FILE"] = "custom-dex.json"; + sorter.load_json(settings.clone()); + if (file->visibility() != ConfigOptionState::ENABLED || std::string(*file) != "custom-dex.json"){ + return UnitTestResult("Selecting Custom must show and load the file selector."); + } + JsonValue saved = sorter.to_json(); + sorter.restore_defaults(); + if (file->visibility() != ConfigOptionState::HIDDEN){ + return UnitTestResult("Restoring the default style must hide the file selector."); + } + sorter.load_json(saved); + if (file->visibility() != ConfigOptionState::ENABLED || std::string(*file) != "custom-dex.json"){ + return UnitTestResult("Custom style and file must survive a settings round trip."); + } + settings["LIVING_DEX_STYLE"] = "sorted_by_forms"; + sorter.load_json(settings.clone()); + return file->visibility() == ConfigOptionState::HIDDEN; + } +}; + +void add_tests_LivingDexTemplate(UnitTestDatabase& database){ + for (const char* filename : { + "living_dex_by_forms.json", "living_dex_by_species.json", + "ajp_final_form.json", "ajp_final_form_form.json", "ajp_living.json", + "ajp_living_form.json", "ajp_living_form_lite.json", + "pokepc_fully_sorted.json", "pokepc_fully_sorted_minimal.json", + "pokepc_grouped_balanced.json", "pokepc_grouped_region.json", + "pokepc_sorted_species.json", "pokepc_sorted_species_minimal.json", "pokepc_species_first.json" + }){ + database.add(filename, filename, "", true); + } + + const JsonValue valid = parse_json(R"([{ + "species_slug":"bulbasaur", "form_slug":"none", "natID":1, + "primaryType":"grass", "secondaryType":"poison", "slug":"bulbasaur", + "has_gender_difference":false + }])"); + database.add("Valid Pokemon", valid.dump()); + database.add("Malformed JSON", "[{", "JSON array"); + database.add("Wrong root", "{}", "JSON array"); + database.add("Null root", "null", "JSON array"); + database.add("Empty template", "[]", "at least one entry"); + database.add("Non-object entry", "[7]", "entry 1"); + + // Missing and incorrectly typed required fields must identify the field. + const JsonObject& original = valid.to_array_throw()[0].to_object_throw(); + for (const char* field : {"species_slug", "form_slug", "natID", "primaryType", "slug", "has_gender_difference"}){ + JsonObject missing; + for (const auto& item : original){ + if (item.first != field){ + missing[item.first] = item.second.clone(); + } + } + JsonArray entries; + entries.push_back(std::move(missing)); + database.add("Missing " + std::string(field), entries.dump(), field); + JsonValue wrong_type = valid.clone(); + wrong_type.to_array_throw()[0].to_object_throw()[field] = JsonValue(); + database.add("Wrong type " + std::string(field), wrong_type.dump(), field); + } + + auto changed = [&](const std::string& name, const char* field, JsonValue value, const std::string& error){ + JsonValue json = valid.clone(); + json.to_array_throw()[0].to_object_throw()[field] = std::move(value); + database.add(name, json.dump(), error); + }; + changed("Negative dex number", "natID", -1, "natID"); + changed("Overflowing dex number", "natID", 65536, "natID"); + changed("Fractional dex number", "natID", 1.5, "natID"); + changed("Invalid empty slot", "natID", 0, "empty slot"); + changed("Blank species", "species_slug", "", "species_slug"); + changed("Blank form", "form_slug", " ", "form_slug"); + changed("Blank slug", "slug", "", "slug"); + changed("Unknown primary type", "primaryType", "Grass", "primaryType"); + changed("Missing primary type", "primaryType", "none", "primaryType"); + changed("Unknown secondary type", "secondaryType", "stellar", "secondaryType"); + changed("Wrong secondary type", "secondaryType", false, "secondaryType"); + changed("Null secondary type", "secondaryType", JsonValue(), ""); + changed("None secondary type", "secondaryType", "none", ""); + changed("Missing gender suffix", "has_gender_difference", true, "slug"); + + database.add("Optional secondary type", R"([{ + "species_slug":"charmander", "form_slug":"none", "natID":4, + "primaryType":"fire", "slug":"charmander", "has_gender_difference":false + }])"); + database.add("Empty slot", R"([{ + "species_slug":"empty", "form_slug":"", "natID":0, + "primaryType":"", "secondaryType":null, "slug":"", "has_gender_difference":false + }])"); + JsonValue gender = valid.clone(); + gender.to_array_throw()[0].to_object_throw()["has_gender_difference"] = true; + gender.to_array_throw()[0].to_object_throw()["slug"] = "bulbasaur-female"; + database.add("Gender suffix", gender.dump()); + + JsonValue second_entry = valid.clone(); + second_entry.to_array_throw().push_back(JsonObject()); + database.add("Error entry index", second_entry.dump(), "entry 2"); + JsonArray oversized; + for (size_t i = 0; i <= MAX_HOME_BOXES * 30; i++){ + oversized.push_back(JsonValue()); + } + database.add("Too many slots", oversized.dump(), "capacity"); + database.add(); +} + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex_Tests.h b/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex_Tests.h new file mode 100644 index 0000000000..08b3acb79a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex_Tests.h @@ -0,0 +1,22 @@ +/* Home Box Sorter Living Dex Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonHome_BoxSorterLivingDex_Tests_H +#define PokemonAutomation_PokemonHome_BoxSorterLivingDex_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ + + +void add_tests_LivingDexTemplate(UnitTestDatabase& database); + +} +} +} +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 5d130faff9..2e7f46d70f 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1885,6 +1885,8 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorter.h Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex.cpp Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex.h + Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex_Tests.cpp + Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex_Tests.h Source/VideoGames/PokemonHome/Programs/PokemonHome_GenerateNameOCR.cpp Source/VideoGames/PokemonHome/Programs/PokemonHome_GenerateNameOCR.h Source/VideoGames/PokemonHome/Programs/PokemonHome_PageSwap.cpp