diff --git a/.github/workflows/cpp-ci-serial-programs-base.yml b/.github/workflows/cpp-ci-serial-programs-base.yml index ecf6f2045f..e1ce8a64ca 100644 --- a/.github/workflows/cpp-ci-serial-programs-base.yml +++ b/.github/workflows/cpp-ci-serial-programs-base.yml @@ -223,12 +223,32 @@ jobs: cd Arduino-Source/SerialPrograms mkdir bin cd bin - cmake .. -DQT_MAJOR:STRING=6 -DPA_SDL=ON ${{env.CMAKE_ADDITIONAL_FLAGS}} + cmake .. -DQT_MAJOR:STRING=6 -DPA_SDL=ON -DPA_FRLG_STORY_EXPORT=ON ${{env.CMAKE_ADDITIONAL_FLAGS}} # By default Ninja reads each compile's .d dependency file into its own database, then deletes it. # To keep them for the downstream clang-query cache (see .github/scripts/clang-query-cached.py), add # -d keepdepfile cmake --build . --config RelWithDebInfo --parallel ${{env.BUILD_PARALLEL}} -- -d keepdepfile + - name: Export evaluated FRLG Parcel checkpoint (Ubuntu) + if: startsWith(inputs.os, 'ubuntu') && inputs.run-tests + run: | + cd Arduino-Source/SerialPrograms/bin + ./StoryCheckpointExport 00.05 > frlg-parcel.native.json + python3 - <<'PYTHON' + import json + from pathlib import Path + data = json.loads(Path('frlg-parcel.native.json').read_text()) + assert data['game'] == 'frlg' and data['checkpoint']['id'] == '00.05' + assert len(data['checkpoint']['events']) == 3 + PYTHON + + - name: Upload evaluated FRLG checkpoint + if: startsWith(inputs.os, 'ubuntu') && inputs.run-tests + uses: actions/upload-artifact@v7 + with: + name: frlg-checkpoint-${{inputs.os}}-${{inputs.compiler}} + path: Arduino-Source/SerialPrograms/bin/frlg-parcel.native.json + - name: Prepare upload build if: inputs.upload-build shell: bash diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index 566e410bc8..d80945e376 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -236,6 +236,8 @@ pa_embed_text_files(SerialProgramsLib "${FRLG_MAP_RESOURCES}" VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h PokemonAutomation::NintendoSwitch::PokemonFRLG overworld_map_json) pa_embed_text_files(SerialProgramsLib Source/VideoGames/PokemonFRLG/Programs/AutoStory/BattleData VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleData.h PokemonAutomation::NintendoSwitch::PokemonFRLG autostory_battle_json) +pa_embed_text_files(SerialProgramsLib Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData + VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h PokemonAutomation::NintendoSwitch::PokemonFRLG autostory_checkpoint_json) # Create binary target @@ -955,6 +957,7 @@ if(COMMAND_LINE_EXE) include(Source/CommandLine/CommandLineExecutable.cmake) endif() +include(../devtools/story-export/FRLG.cmake) if(PA_PYTHON_BINDINGS) # Python bindings (GUI-free) from subdirectory include(Source/PythonBindings/PythonBindings.cmake) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Panels.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Panels.cpp index 535e83b659..e9c2107a85 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Panels.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Panels.cpp @@ -18,6 +18,9 @@ #include "Programs/Farming/PokemonFRLG_NuggetBridgeFarmer.h" #include "Programs/Farming/PokemonFRLG_PickupFarmer.h" #include "Programs/Farming/PokemonFRLG_EvTrainer.h" + +#include "Programs/AutoStory/PokemonFRLG_AutoStory.h" + #include "Programs/ShinyHunting/PokemonFRLG_GiftReset.h" #include "Programs/ShinyHunting/PokemonFRLG_LegendaryReset.h" #include "Programs/ShinyHunting/PokemonFRLG_LegendaryRunAway.h" @@ -58,7 +61,6 @@ PanelListFactory::PanelListFactory() std::vector PanelListFactory::make_panels() const{ std::vector ret; - ret.emplace_back("---- Settings ----"); ret.emplace_back(make_OptionsPanel()); @@ -70,7 +72,8 @@ std::vector PanelListFactory::make_panels() const{ ret.emplace_back(make_SingleSwitchProgram()); ret.emplace_back(make_SingleSwitchProgram()); - //ret.emplace_back("---- General ----"); + ret.emplace_back("---- General ----"); + ret.emplace_back(make_SingleSwitchProgram()); ret.emplace_back("---- Shiny Hunting ----"); ret.emplace_back(make_SingleSwitchProgram()); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index bd5cd7499d..1cbb9d1c8c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -45,6 +45,8 @@ #include "Overworld/PokemonFRLG_OverworldWalk.h" #include "Overworld/PokemonFRLG_PlayerFacingReader.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryTable.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryExport_Tests.h" #include "Tests/TestUtils.h" #include "PokemonFRLG_Tests.h" @@ -102,6 +104,9 @@ void add_tests(UnitTestDatabase& database){ add_tests_OverworldReanchor(database); add_tests_OverworldRecovery(database); add_tests_PlayerFacingReader(database); + add_tests_AutoStory(database); + add_tests_AutoStoryExport(database); + add_tests_AutoStorySimulation(database); add_tests_AutoStoryItems(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp new file mode 100644 index 0000000000..65d0de1d1a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -0,0 +1,261 @@ +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "Pokemon/AutoStory/Pokemon_AutoStorySelect.h" +#include "Pokemon/AutoStory/Pokemon_AutoStoryStats.h" +#include "Pokemon/AutoStory/Pokemon_StoryLog.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "Pokemon/Options/Pokemon_GameLanguages.h" +#include "Pokemon/Pokemon_Strings.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" +#include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryTable.h" +#include "PokemonFRLG_AutoStory.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +AutoStory_Descriptor::AutoStory_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonFRLG:AutoStory", + Pokemon::STRING_POKEMON + " FRLG", "AutoStory", + "", + "Play FireRed (English) from a new game to the Boulder Badge.", + PanelQualityStanding::OFFICIAL_BETA, + ProgramControllerClass::StandardController_NoRestrictions, + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS + ) +{} + +std::unique_ptr AutoStory_Descriptor::make_stats() const{ + return std::make_unique(); +} + + +namespace{ + +// The start and end dropdowns' entries: the table's checkpoints, 00.01 to +// 00.10. The options hold a reference to it. +const StringSelectDatabase& checkpoint_database(){ + static const std::vector labels = []{ + std::vector result; + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + result.push_back(Pokemon::story_checkpoint_label(checkpoint)); + } + return result; + }(); + static const StringSelectDatabase database = Pokemon::story_checkpoint_database(labels); + return database; +} + +const std::string KEEP_START_FRAME_TEXT = + "Keep the start frame:
Off by default. The save loaded was made by hand where the start checkpoint " + "begins: keep the screen after loading it as that checkpoint's start frame, which later runs compare their " + "save with. The program keeps one by itself at each save it makes."; + +} // namespace + +AutoStory::AutoStory() + : RUN(checkpoint_database(), Pokemon::FireRedLeafGreenLanguages_Database()) + , NEW_GAME_FROM_TITLE( + "New game from the title screen:
The game is on its title screen with no save data. " + "Needed to start at 00.01. Otherwise the program loads the save, which must be the one the start checkpoint begins from.", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , KEEP_START_FRAME(KEEP_START_FRAME_TEXT, LockMode::LOCK_WHILE_RUNNING, false) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(RUN); + PA_ADD_OPTION(NEW_GAME_FROM_TITLE); + PA_ADD_OPTION(KEEP_START_FRAME); + PA_ADD_OPTION(NOTIFICATIONS); +} + + +// The save loaded must be the one checkpoint `first` starts from: one left +// by an earlier checkpoint (a run that failed before saving) would start +// it in the wrong place (console B, 2026-11-01: 00.09 on the forest's +// save). Checked on the SAVE card; a card that can't be read is let pass. +static void check_start_save( + SingleSwitchProgramEnvironment& env, StoryEnv& story, const StoryCheckpoint& checkpoint +){ + if (!checkpoint.start){ + return; + } + const std::string error = check_save_place(story, Pokemon::grid_pose_of(*checkpoint.start).map); + if (!error.empty()){ + throw UserSetupError(env.console, error + " Start at the checkpoint " + checkpoint.id + " the save is for."); + } +} + +namespace{ + +// The story's state for a run from `checkpoint`: its supplies, the checks +// level, and the program's start frames, the first start check keeping +// the screen as its frame if `keep_start_frame` (a save made by hand). +StoryEnv story_env( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StoryCheckpoint& checkpoint, Pokemon::StoryCheckLevel checks, bool keep_start_frame +){ + StoryEnv story{env.console, context, checkpoint.supplies, checkpoint.supplies, false, checks}; + story.start_frames = program_start_frames(); + story.keep_start_frame = keep_start_frame; + return story; +} + +// A failed attempt reloads the last save, with the supplies it had, read +// from its bag again; the engine's lines go to the console's log. +Pokemon::SegmentHooks story_hooks(SingleSwitchProgramEnvironment& env, StoryEnv& story){ + Pokemon::SegmentHooks hooks; + hooks.reload = [&story](Pokemon::RunState&){ + if (!story.has_save){ + return Pokemon::outcome_failed("no_save", "nothing saved yet"); + } + // The save reloaded must be where the checkpoint starts: a save + // that didn't happen leaves an older one (console B, 2026-11-02: + // 00.02 walked the bedroom's route in Pewter City). + try{ + soft_reset(story.console, story.context); + const std::string error = check_save_place(story, story.start_map); + if (!error.empty()){ + return Pokemon::outcome_failed("wrong_save", error); + } + story.supplies = story.saved_supplies; + // Every reload, so each verify run starts from the bag as the + // save holds it, not from a count once read wrong or not at + // all (console B, 2026-11-03: 0 Potions in all 3 runs). + read_bag_supplies(story, story.start_menu); + }catch (OperationFailedException& e){ + return Pokemon::outcome_failed("reload_failed", e.message()); + } + return Pokemon::outcome_ok(); + }; + hooks.log = [&env](const std::string& line){ + env.console.log(line); + }; + // The checkpoint and the step under way, for whoever watches the stream. + hooks.status = [&env](const std::string& line){ + env.console.overlay().add_log(line); + }; + return hooks; +} + +// The game on the save checkpoint `checkpoint` starts from, with the +// supplies and moves read from it. +void load_verify_save( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, StoryEnv& story, const StoryCheckpoint& checkpoint +){ + if (!checkpoint.start){ + throw UserSetupError(env.console, + "Verify mode reloads the checkpoint's save between runs: " + checkpoint.id + " starts a new game and has none." + ); + } + env.console.log("Verify mode: loading the save for " + checkpoint.id + "."); + soft_reset(env.console, context); + story.has_save = true; + check_start_save(env, story, checkpoint); + read_lead_moves(story, checkpoint.menu); + read_bag_supplies(story, checkpoint.menu); +} + +// Verify mode: the start checkpoint run from its save as `policy` says, +// never saving at its end, so every run starts from the same save. +// Throws unless enough runs pass. +void verify_story_checkpoint( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const Pokemon::StoryRunOptions& run, const Pokemon::VerifyPolicy& policy, EventNotificationOption& finished +){ + const std::vector& checkpoints = story_checkpoints(); + const StoryCheckpoint& checkpoint = checkpoints[run.start_index()]; + StoryEnv story = story_env(env, context, checkpoint, run.check_level(), false); + load_verify_save(env, context, story, checkpoint); + story.language = run.language(); + StoryExecutor executor(story); + Pokemon::Segment segment = make_story_segment(checkpoints, executor); + Pokemon::SegmentHooks hooks = story_hooks(env, story); + + Pokemon::RunState state; + const Pokemon::VerifyReport report = Pokemon::verify_checkpoint(checkpoint.id, policy, segment, hooks, state); + const std::string summary = std::format( + "AutoStory verify: {} {}/{} passed, {} needed.", checkpoint.id, report.passes, policy.runs, policy.passes_needed + ); + if (!report.verified){ + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, summary); + } + env.console.log(summary); + send_program_finished_notification(env, finished, summary); +} + + +} // namespace + +void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (const std::optional verify = RUN.VERIFY.policy()){ + verify_story_checkpoint(env, context, RUN, *verify, NOTIFICATION_PROGRAM_FINISH); + return; + } + const std::vector& checkpoints = story_checkpoints(); + const size_t first = RUN.start_index(); + const size_t last = RUN.end_index(); + if (first > last || last >= checkpoints.size()){ + throw UserSetupError(env.console, "The start checkpoint must not come after the end checkpoint."); + } + if (first == 0 && !NEW_GAME_FROM_TITLE){ + throw UserSetupError(env.console, "Checkpoint 00.01 starts a new game: start on the title screen with no save."); + } + + StoryEnv story = story_env(env, context, checkpoints[first], RUN.check_level(), KEEP_START_FRAME); + if (!(first == 0 && NEW_GAME_FROM_TITLE)){ + env.console.log("Loading the save for " + checkpoints[first].id + "."); + soft_reset(env.console, context); + story.has_save = true; + check_start_save(env, story, checkpoints[first]); + read_lead_moves(story, checkpoints[first].menu); + read_bag_supplies(story, checkpoints[first].menu); + } + + story.language = RUN.language(); + StoryExecutor executor(story); + Pokemon::Segment segment = make_story_segment(checkpoints, executor); + Pokemon::SegmentHooks hooks = story_hooks(env, story); + + Pokemon::RunState state; + const Pokemon::SegmentReport report = run_segment( + Pokemon::SegmentRange{checkpoints[first].id, checkpoints[last].id}, RUN.policy(), segment, hooks, state + ); + Pokemon::record_story_counts(report.story_counts(), env.current_stats()); + env.update_stats(); + if (!report.completed){ + throw OperationFailedException( + ErrorReportMode::NO_ERROR_REPORT, + std::format( + "AutoStory stopped at {} {}: {}", + report.failed_checkpoint, report.failed_event, Pokemon::to_string(report.failure) + ) + ); + } + env.console.log("AutoStory: done through " + checkpoints[last].id + "."); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h new file mode 100644 index 0000000000..285a2c16b8 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h @@ -0,0 +1,60 @@ +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + * Plays FireRed from a new game to the Boulder Badge, as the story + * checkpoints of PokemonFRLG_AutoStoryTable.h run by the shared story + * engine. Each checkpoint saves at its end; one that fails is retried from + * that save, as the shared retry options say. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStory_H +#define PokemonAutomation_PokemonFRLG_AutoStory_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Options/Pokemon_StoryRunOptions.h" +#include "PokemonFRLG_AutoStoryActions.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Program descriptor for FRLG AutoStory. +class AutoStory_Descriptor : public SingleSwitchProgramDescriptor{ +public: + AutoStory_Descriptor(); + virtual std::unique_ptr make_stats() const override; +}; + +// Program instance executing FRLG AutoStory. +class AutoStory : public SingleSwitchProgramInstance{ +public: + using Descriptor = AutoStory_Descriptor; + AutoStory(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + virtual void start_program_border_check( + VideoStream& stream, + FeedbackType feedback_type + ) override{} + +private: + // The start and end checkpoints, attempts, checks and language, as in + // every game's AutoStory. + Pokemon::StoryRunOptions RUN; + BooleanCheckBoxOption NEW_GAME_FROM_TITLE; + // The save loaded was made by hand: keep the screen as its start frame. + BooleanCheckBoxOption KEEP_START_FRAME; + EventNotificationsOption NOTIFICATIONS; +}; + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCheckpoints.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCheckpoints.h new file mode 100644 index 0000000000..f7e1c14774 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCheckpoints.h @@ -0,0 +1,67 @@ +/* AutoStory Checkpoints + * + * From: https://github.com/PokemonAutomation/ + * + * FRLG's story checkpoint, and the fixed routes, wall turns and mart + * orders its rows are built from. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryCheckpoints_H +#define PokemonAutomation_PokemonFRLG_AutoStoryCheckpoints_H + +#include +#include +#include +#include +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" +#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryBattle.h" +#include "PokemonFRLG_AutoStoryStartFrames.h" +#include "PokemonFRLG_AutoStoryStepInterrupts.h" +#include "PokemonFRLG_AutoStoryStepTable.h" +#include "PokemonFRLG_AutoStorySaveChecks.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// A shared checkpoint with what FRLG adds to it. +struct StoryCheckpoint : public Pokemon::StoryCheckpoint{ + // The healing items at its start, for a run that loads its save. + Supplies supplies; + // The START menu at its end, when it saves. + StartMenu menu = StartMenu::FULL; +}; +// `legs` from `start` as route steps for the walker, each checked against +// the map: nothing if a step is blocked or leaves the map. A leg ends "to +// wall" if the next step its way is blocked. +std::optional> fixed_route( + const std::vector& maps, const MapPosition& start, const std::vector& legs +); + +// A way the player at `tile` can turn to without stepping: a wall there, +// with no one standing in it. West and east first: walking north or south +// into a sign would read it. +std::optional wall_beside(const MapData& map, const TilePos& tile); + +// `items` as orders at the Viridian Mart before the Boulder Badge: the +// rows of POKE BALL, POTION, ANTIDOTE, PARLYZ HEAL. Nothing if it does +// not sell one of them. +std::optional> viridian_mart_orders(const std::vector& items); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp new file mode 100644 index 0000000000..29c518b22f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -0,0 +1,599 @@ +/* AutoStory Events + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Pokemon/Navigation/Pokemon_RouteLog.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h" +#include "PokemonFRLG_AutoStoryBattleData.h" +#include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStorySummary.h" +#include "PokemonFRLG_AutoStoryTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace std::chrono_literals; +using Pokemon::facing_of; +using Pokemon::Outcome; +using Pokemon::RunState; + + +namespace{ + +// The longest scenes: the old man's tutorial (about 60 lines and his +// catching demo), the lab's Pokedex scene (about 75 lines). +constexpr Milliseconds SCENE_TIMEOUT = 300000ms; +constexpr Milliseconds YES_NO_TIMEOUT = 60000ms; +constexpr Milliseconds BATTLE_TEXT_TIMEOUT = 90000ms; + +// The engine knows nothing of consoles: a failed console step is a failed +// Outcome, which the segment answers by reloading the save. +template +Outcome guarded(Body&& body){ + try{ + return body(); + }catch (OperationFailedException& e){ + return Pokemon::outcome_failed("operation_failed", e.message()); + } +} + +// The step's arg `key`, which its action declares. +template +const Type& arg(const StoryStep& step, std::string_view key){ + return Pokemon::story_arg(step.args, key); +} + +// A checkpoint's start as the engine's Pose: nothing for a new game. +std::optional start_pose(const StoryCheckpoint& checkpoint){ + if (!checkpoint.start){ + return std::nullopt; + } + return Pokemon::pose_of(*checkpoint.start); +} + +const MapData* find_story_map(const std::string& name){ + for (const MapData& map : story_maps()){ + if (map.name == name){ + return ↦ + } + } + return nullptr; +} + +// Turns the player to a wall next to `position`, which turns without a +// step whichever way the player faced. Nothing if no wall is next to it. +std::optional face_a_wall(StoryEnv& env, const MapPosition& position){ + const MapData* map = find_story_map(position.map); + if (map == nullptr){ + return std::nullopt; + } + const std::optional wall = wall_beside(*map, position.point); + if (wall){ + env.console.log(std::string("Story: facing unknown, turning to the wall ") + direction_name(*wall) + "."); + face_wall(env.context, *wall); + } + return wall; +} + +// The shared route log's arrival line (Pokemon_RouteLog.h), as BDSP's walker +// writes it: where the route was walked to. +void log_arrival(StoryEnv& env, const std::string& label, const std::string& map, const TilePos& tile){ + env.console.log(std::string(Pokemon::ROUTE_LOG_TAG) + Pokemon::route_arrived_line(label, {{map, tile}})); +} + +Outcome walk_route(StoryEnv& env, RunState& state, const StoryStep& step){ + const std::vector tiles = Pokemon::tiles_of(state.pose); + if (tiles.size() != 1 || state.pose.certainty != Pokemon::PoseCertainty::TILE){ + return Pokemon::outcome_failed("no_pose", Pokemon::to_string(state.pose)); + } + const MapPosition start{state.pose.map, tiles[0]}; + std::optional facing = facing_of(state.pose); + if (!facing){ + facing = face_a_wall(env, start); + } + if (!facing){ + return Pokemon::outcome_failed("unknown_facing", to_string(start)); + } + const Pokemon::Pose target_pose = Pokemon::pose_of(arg(step, "target")); + const std::optional target = story_pose(target_pose); + if (!target){ + return Pokemon::outcome_failed("bad_target", Pokemon::to_string(target_pose)); + } + const RouteGoal goal{{target->map, target->tile}, target->facing}; + const std::optional> route = plan_overworld_route( + story_maps(), start, goal, default_route_costs(), facing + ); + if (!route){ + return Pokemon::outcome_failed("no_route", to_string(start) + " to " + to_string(goal.position)); + } + const OverworldInterruptSet interrupts = story_interrupts(env.supplies, arg(step, "fight_wild"), env.checks, env.language); + walk_overworld_route(env.console, env.context, *route, facing, interrupts, move_speed(step)); + log_arrival(env, step.name, target->map, target->tile); + const std::optional end_facing = route->empty() ? facing : std::optional(route->back().facing_after); + return Pokemon::outcome_ok(to_pose(StoryPose{target->map, target->tile, end_facing})); +} + +Outcome walk_legs(StoryEnv& env, RunState& state, const StoryStep& step){ + const std::vector tiles = Pokemon::tiles_of(state.pose); + if (tiles.size() != 1 || state.pose.certainty != Pokemon::PoseCertainty::TILE){ + return Pokemon::outcome_failed("no_pose", Pokemon::to_string(state.pose)); + } + const MapPosition start{state.pose.map, tiles[0]}; + std::optional facing = facing_of(state.pose); + if (!facing){ + facing = face_a_wall(env, start); + } + const std::optional> route = fixed_route(story_maps(), start, arg>(step, "legs")); + if (!facing || !route || route->empty()){ + return Pokemon::outcome_failed("bad_legs", to_string(start)); + } + const OverworldInterruptSet interrupts = story_interrupts(env.supplies, arg(step, "fight_wild"), env.checks, env.language); + walk_overworld_route(env.console, env.context, *route, facing, interrupts, move_speed(step)); + log_arrival(env, step.name, route->back().end.map, route->back().end.point); + return Pokemon::outcome_ok(to_pose(StoryPose{route->back().end.map, route->back().end.point, route->back().facing_after})); +} + +Outcome take_step(StoryEnv& env, RunState& state, const StoryStep& step){ + const Direction direction = arg(step, "direction"); + step_once(env.context, direction, facing_of(state.pose)); + const std::vector tiles = Pokemon::tiles_of(state.pose); + if (tiles.size() != 1){ + return Pokemon::outcome_ok(); + } + return Pokemon::outcome_ok(to_pose(StoryPose{state.pose.map, tiles[0].next(direction), direction})); +} + +Outcome battle(StoryEnv& env, const StoryStep& step){ + env.supplies.trainer = arg(step, "trainer"); + env.supplies.risk = default_battle_risk(env.supplies.trainer); + env.supplies.foe_out.clear(); + if (advance_text(env.console, env.context, BATTLE_TEXT_TIMEOUT, true) != TextEnd::BATTLE){ + return Pokemon::outcome_failed("no_battle"); + } + env.supplies.foes = arg>(step, "foes"); + if (!env.supplies.foes.empty()){ + env.console.log(std::format( + "Story: {} is {}, risk {}; attacks are chosen against the foe out.", + step.name, env.supplies.trainer, battle_risk_name(env.supplies.risk) + )); + } + const BattleEnd end = fight_battle(env.console, env.context, env.supplies, BattleKind::TRAINER, env.checks, env.language); + env.supplies.foes.clear(); + env.supplies.trainer.clear(); + env.supplies.foe_out.clear(); + if (end == BattleEnd::LOST && !arg(step, "may_lose")){ + return Pokemon::outcome_failed("blackout"); + } + mash_until_overworld(env.console, env.context, SCENE_TIMEOUT); + return Pokemon::outcome_ok(); +} + +// HP and status are the battle loop's last reading. Items first (an +// Antidote, a Parlyz Heal, a Potion); then the nurse as +// nurse_before_battle() says. +Outcome get_ready(StoryEnv& env, RunState& state, const StoryStep& step){ + Supplies& supplies = env.supplies; + env.console.log(std::format( + "Story: before the battle, HP {}, {}, {} Potions.", + supplies.hp_red ? "red" : supplies.hurt ? "yellow" : "green", status_name(supplies.status), supplies.potions + )); + recover_after_battle(env.console, env.context, supplies, env.checks, env.language); + if (!nurse_before_battle(supplies)){ + return Pokemon::outcome_ok(); + } + Outcome walked = walk_route(env, state, step); + if (!walked.succeeded()){ + return walked; + } + heal_at_center(env.console, env.context); + healed_by_nurse(supplies); + return walked; +} + +// Viridian Mart before the Boulder Badge (pokefirered ViridianCity_Mart_Items): +// POKE BALL, POTION (300), ANTIDOTE (100), PARLYZ HEAL (200). Each item +// the story buys: its row, and where the bag's count is kept. +struct MartItem{ + std::string_view item; + int row; + int Supplies::* count; + // The name the item list reader reads (read_item_list_name()). + std::string_view slug; +}; +constexpr MartItem VIRIDIAN_MART_ITEMS[] = { + {.item = "potion", .row = 1, .count = &Supplies::potions, .slug = "potion"}, + {.item = "antidote", .row = 2, .count = &Supplies::antidotes, .slug = "antidote"}, + {.item = "parlyz_heal", .row = 3, .count = &Supplies::parlyz_heals, .slug = "parlyz-heal"}, +}; + +const MartItem* viridian_mart_item(const std::string& name){ + for (const MartItem& item : VIRIDIAN_MART_ITEMS){ + if (name == item.item){ + return &item; + } + } + return nullptr; +} + +Outcome shop(StoryEnv& env, const StoryStep& step){ + const std::optional> orders = viridian_mart_orders(arg>(step, "items")); + if (!orders){ + return Pokemon::outcome_failed("unknown_item", step.name); + } + // 2000 of the 3000 a new game starts with, plus the rival's prize. + buy_items(env.console, env.context, *orders, env.checks, env.language); + for (const Pokemon::StoryItem& item : arg>(step, "items")){ + env.supplies.*viridian_mart_item(item.item)->count += (int)item.quantity; + } + if (!checks_screen(env.checks)){ + return Pokemon::outcome_ok(); + } + // The counts from the bag, not from the orders: a wrong row once bought + // Parlyz Heals for Antidotes unnoticed (console B, 2026-11-01). + const std::vector rows = read_items_pocket(env.console, env.context, env.language); + if (rows.empty()){ + env.console.log("Story: couldn't read the Items pocket; keeping the counts ordered.", COLOR_ORANGE); + return Pokemon::outcome_ok(); + } + for (const std::string& item : set_from_bag(env.supplies, rows)){ + env.console.log(std::format( + "Story: couldn't read how many {} the bag holds; counting {}.", + item, item_count(env.supplies, item) + ), COLOR_ORANGE); + } + return Pokemon::outcome_ok(); +} + +} // namespace + + +std::optional> viridian_mart_orders(const std::vector& items){ + std::vector orders; + for (const Pokemon::StoryItem& wanted : items){ + const MartItem* found = viridian_mart_item(wanted.item); + if (found == nullptr){ + return std::nullopt; + } + orders.push_back(MartOrder{found->row, (int)wanted.quantity, found->slug}); + } + return orders; +} + +const std::vector& story_maps(){ + static const std::vector maps = overworld_maps(map_flag_set(overworld_maps(), "after_hall_of_fame")); + return maps; +} + +MoveSpeed move_speed(const StoryStep& step){ + return step.action == RUN_VARIANT ? MoveSpeed::RUN : MoveSpeed::WALK; +} + +Pokemon::Pose to_pose(const StoryPose& pose){ + return Pokemon::tile_pose(pose.map, {pose.tile}, pose.facing); +} + +std::optional story_pose(const Pokemon::Pose& pose){ + const std::vector tiles = Pokemon::tiles_of(pose); + if (tiles.size() != 1){ + return std::nullopt; + } + return StoryPose{pose.map, tiles[0], facing_of(pose)}; +} + +std::string save_card_place(const std::string& map){ + // The longer names first: "ViridianForest" before "ViridianCity". + static const std::pair PLACES[] = { + {"PalletTown", "pallet-town"}, + {"ViridianForest", "viridian-forest"}, + {"ViridianCity", "viridian-city"}, + {"PewterCity", "pewter-city"}, + }; + for (const auto& [prefix, place] : PLACES){ + if (map.rfind(prefix, 0) == 0){ + return std::string(place); + } + } + return ""; +} + +std::string save_place_error(const std::string& start_map, const std::string& place){ + const std::string expected = save_card_place(start_map); + if (expected.empty() || place.empty() || place == expected){ + return ""; + } + return "The save is in " + place + ", but the checkpoint starts in " + expected + " (" + start_map + ")."; +} + +std::string start_pose_mismatch(const Pokemon::Pose& start, const StoryPose& stands){ + const std::optional at = story_pose(start); + if (at && at->map == stands.map && at->tile == stands.tile + && (!at->facing || !stands.facing || at->facing == stands.facing) + ){ + return ""; + } + return "The save stands at " + Pokemon::to_string(to_pose(stands)) + + ", but the checkpoint starts at " + Pokemon::to_string(start) + "."; +} + +void add_start_pose_check( + Pokemon::Checkpoint& checkpoint, const std::optional& start, SavePoseReader read, StoryLog log +){ + if (!start){ + return; + } + StartReader reader = [start = *start, read = std::move(read)]() -> StartRead{ + const std::optional stands = read(); + if (!stands){ + return {}; + } + const std::string mismatch = start_pose_mismatch(start, *stands); + return mismatch.empty() ? StartRead{StartFound::AT_START} : StartRead{StartFound::ELSEWHERE, mismatch}; + }; + add_start_check(checkpoint, start, std::move(reader), std::move(log)); +} + +std::optional> fixed_route( + const std::vector& maps, const MapPosition& start, const std::vector& legs +){ + const MapData* map = nullptr; + for (const MapData& candidate : maps){ + if (candidate.name == start.map){ + map = &candidate; + } + } + if (map == nullptr || !in_bounds(*map, start.point)){ + return std::nullopt; + } + std::vector route; + PlayerState player{start.point, elevation_at(*map, start.point), false}; + for (const StoryLeg& leg : legs){ + RouteStep step; + step.direction = leg.direction; + step.tiles = leg.tiles; + step.facing_after = leg.direction; + for (int c = 0; c < leg.tiles; c++){ + const StepKind kind = classify_step(*map, player, leg.direction); + const TilePos next = player.position.next(leg.direction); + if (kind != StepKind::WALK || !in_bounds(*map, next) || warps_on_step(*map, next)){ + return std::nullopt; + } + step.wild |= is_tall_grass(*map, next); + player = after_step(*map, player, leg.direction, kind); + } + step.to_wall = classify_step(*map, player, leg.direction) == StepKind::BLOCKED; + step.end = MapPosition{map->name, player.position}; + route.push_back(step); + } + return route; +} + +std::optional wall_beside(const MapData& map, const TilePos& tile){ + for (Direction direction : {Direction::WEST, Direction::EAST, Direction::NORTH, Direction::SOUTH}){ + const TilePos next = tile.next(direction); + if (in_bounds(map, next) && tile_at(map, next) == TileKind::WALL && object_at(map, next) == nullptr){ + return direction; + } + } + return std::nullopt; +} + +namespace{ + +// How the console does an action that needs only the env. +using ConsoleAction = Outcome (*)(StoryEnv& env, RunState& state, const StoryStep& step); + +ConsoleAction console_action_of(StoryActionId id){ + switch (id){ + case StoryActionId::NEW_GAME: + return [](StoryEnv& env, RunState&, const StoryStep&){ + play_new_game_intro(env.console, env.context); + return Pokemon::outcome_ok(); + }; + case StoryActionId::ROUTE: + return [](StoryEnv& env, RunState& state, const StoryStep& step){ return walk_route(env, state, step); }; + case StoryActionId::LEGS: + return walk_legs; + case StoryActionId::STEP: + return take_step; + case StoryActionId::TALK: + return [](StoryEnv& env, RunState&, const StoryStep&){ + pbf_press_button(env.context, BUTTON_A, 160ms, 800ms); + return Pokemon::outcome_ok(); + }; + case StoryActionId::ANSWER: + return [](StoryEnv& env, RunState&, const StoryStep& step){ + answer_yes_no(env.console, env.context, arg(step, "yes"), BUTTON_B, YES_NO_TIMEOUT); + return Pokemon::outcome_ok(); + }; + case StoryActionId::MASH: + return [](StoryEnv& env, RunState&, const StoryStep&){ + mash_until_overworld(env.console, env.context, SCENE_TIMEOUT); + return Pokemon::outcome_ok(); + }; + case StoryActionId::BATTLE: + return [](StoryEnv& env, RunState&, const StoryStep& step){ return battle(env, step); }; + case StoryActionId::HEAL: + return [](StoryEnv& env, RunState&, const StoryStep&){ + heal_at_center(env.console, env.context); + healed_by_nurse(env.supplies); + return Pokemon::outcome_ok(); + }; + case StoryActionId::SHOP: + return [](StoryEnv& env, RunState&, const StoryStep& step){ return shop(env, step); }; + case StoryActionId::READY: + return get_ready; + case StoryActionId::OPTIONS: + case StoryActionId::GAME: + break; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("No console action for {}", story_action_name(id))); +} + +} // namespace + + +StoryExecutor::StoryExecutor(StoryEnv& env) + : m_env(env) + , m_guard(env.console.logger()) + , m_table(make_story_action_table([this](StoryActionId id){ return console_action(id); })) + , m_executor(m_table, m_guard) + , m_look(env.console, env.context) + , m_interrupts(step_interrupts( + [this](bool fresh){ return m_look.look(fresh); }, + console_interrupt_actions(env.console, env.context, [&env]{ + return story_interrupts(env.supplies, false, env.checks, env.language); + }) + )) +{ + m_executor.set_interrupts(&m_interrupts); +} + +Outcome StoryExecutor::run(const StoryStep& step, RunState& state){ + return m_executor.run(step, state); +} + +Pokemon::StoryAction StoryExecutor::console_action(StoryActionId id){ + if (id == StoryActionId::OPTIONS){ + return {.act = [this](const StoryStep&, RunState&){ + set_options(m_env.console, m_env.context, m_menu, m_env.language); + return Pokemon::outcome_ok(); + }, .needs_console = true}; + } + if (id == StoryActionId::GAME){ + return {.act = [](const StoryStep& step, RunState&){ return Pokemon::unsupported_step(step); }, .needs_console = true}; + } + const ConsoleAction action = console_action_of(id); + return {.act = [this, action](const StoryStep& step, RunState& state){ return action(m_env, state, step); }, .needs_console = true}; +} + + +std::string check_save_place(StoryEnv& env, const std::string& start_map){ + if (save_card_place(start_map).empty()){ + return ""; + } + const std::string place = read_save_place(env.console, env.context, env.language); + if (place.empty()){ + env.console.log("Couldn't read the save card's place; going on.", COLOR_ORANGE); + return ""; + } + const std::string error = save_place_error(start_map, place); + if (error.empty()){ + env.console.log("The save is in " + place + ", where the checkpoint starts."); + } + return error; +} + +void read_lead_moves(StoryEnv& env, StartMenu menu){ + const std::optional read = read_party_summary(env.console, env.context, menu, env.language, 0); + if (!read || read->moves.empty()){ + env.console.log("Couldn't read the lead's moves; going on with the checkpoint's.", COLOR_ORANGE); + return; + } + const PartyMember& before = env.supplies.lead; + const std::string species = read->species.empty() ? before.species : read->species; + const uint8_t level = read->level && *read->level <= 100 ? static_cast(*read->level) : before.moves_through_level; + // The stats belong to the species and level read. + const bool stats_fit = species == read->species && read->level.has_value(); + env.supplies.lead = member_from_summary(species, level, read->moves, stats_fit ? read->stats : std::nullopt); + env.saved_supplies.lead = env.supplies.lead; +} + +void read_bag_supplies(StoryEnv& env, StartMenu menu){ + if (menu != StartMenu::FULL){ + return; + } + const std::vector rows = read_items_pocket(env.console, env.context, env.language); + if (rows.empty()){ + env.console.log("Couldn't read the Items pocket; going on with the checkpoint's items.", COLOR_ORANGE); + return; + } + for (const std::string& item : set_from_loaded_bag(env.supplies, env.saved_supplies, rows)){ + env.console.log(std::format( + "Story: couldn't read how many {} the bag holds; counting {}.", item, item_count(env.supplies, item) + ), COLOR_ORANGE); + } +} + +namespace{ + +// The console's start check for `checkpoint`; with keep_start_frame (a +// save made by hand), the screen is kept as its frame instead. +StartRead read_console_start(StoryEnv& env, const std::string& checkpoint){ + if (env.keep_start_frame){ + env.keep_start_frame = false; + return keep_console_start(env.console, env.context, env.start_frames, checkpoint); + } + return check_console_start(env.console, env.context, env.start_frames, checkpoint); +} + +// After the save at the end of `ended`: the screen, kept as the start +// frame of the table's next checkpoint, which starts there. +void keep_next_start_frame(StoryEnv& env, const std::string& ended){ + const std::vector& table = story_checkpoints(); + for (size_t c = 0; c + 1 < table.size(); c++){ + if (table[c].id == ended && table[c + 1].start){ + keep_console_frame(env.console, env.context, env.start_frames, table[c + 1].id, "saved at the end of " + ended); + return; + } + } +} + +} // namespace + +Pokemon::Checkpoint build_checkpoint(const StoryCheckpoint& data, StoryExecutor& executor){ + executor.set_menu(data.menu); + StoryEnv& env = executor.env(); + // The console has no reader for the tile the save stands on: the save + // card's place is checked when the save is loaded (check_save_place()), + // and the start check compares the screen with the frame kept when the + // program last saved there. With none kept, it passes. + Pokemon::Checkpoint checkpoint = Pokemon::build_story_checkpoint(data, executor); + add_start_check( + checkpoint, start_pose(data), + [&env, id = data.id]{ return read_console_start(env, id); }, + [&env](const std::string& line){ env.console.log(line, COLOR_ORANGE); } + ); + env.start_map = data.start ? Pokemon::grid_pose_of(*data.start).map : ""; + env.start_menu = data.menu; + const StartMenu menu = data.menu; + checkpoint.save = [&env, menu, id = data.id](RunState&){ + return guarded([&]{ + save_game(env.console, env.context, menu); + keep_next_start_frame(env, id); + env.has_save = true; + env.saved_supplies = env.supplies; + return Pokemon::outcome_ok(); + }); + }; + return checkpoint; +} + +Pokemon::Segment make_story_segment(const std::vector& checkpoints, StoryExecutor& executor){ + Pokemon::Segment segment; + segment.id = "00"; + for (const StoryCheckpoint& data : checkpoints){ + segment.checkpoints.push_back(Pokemon::CheckpointSpec{ + data.id, data.title, false, + [&data, &executor]{ return build_checkpoint(data, executor); } + }); + } + return segment; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h new file mode 100644 index 0000000000..418c6f2c31 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h @@ -0,0 +1,142 @@ +/* AutoStory Events + * + * From: https://github.com/PokemonAutomation/ + * + * The FRLG story as data for the shared story engine + * (Pokemon/AutoStory/Pokemon_StoryEvents.h, Pokemon_StorySegments.h). + * A checkpoint is a list of the shared StorySteps + * (Pokemon/AutoStory/Pokemon_StoryStepExecutor.h), each one kind of event (a + * route, a talk, text read to its end, a YES/NO, a battle, the nurse, the + * Mart); StoryExecutor does each kind on the console, and + * make_story_segment() turns the table into engine checkpoints. Routes + * plan from the pose the run carries and return where they leave the + * player; scenes that move the player say where in the table. + * + * The table itself is in PokemonFRLG_AutoStoryTable.h; it is plain data, + * so its routes are planned in unit tests without a console. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryEvents_H +#define PokemonAutomation_PokemonFRLG_AutoStoryEvents_H + +#include +#include +#include +#include +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" +#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryBattle.h" +#include "PokemonFRLG_AutoStoryStartFrames.h" +#include "PokemonFRLG_AutoStoryStepInterrupts.h" +#include "PokemonFRLG_AutoStoryStepTable.h" +#include "PokemonFRLG_AutoStoryCheckpoints.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + + +// What the story's events act on. `supplies` are what the bag holds now, +// `saved_supplies` what the last save holds. +struct StoryEnv{ + ConsoleHandle& console; + ProControllerContext& context; + Supplies supplies; + Supplies saved_supplies; + // Whether the game has a save to reload. + bool has_save = false; + Pokemon::StoryCheckLevel checks = Pokemon::StoryCheckLevel::DEFAULT; + // The game's language, for reading item names. In one the readers have + // no names for, the checks fall back to positions and counts. + Language language = Language::English; + // The map the checkpoint under way starts on, where its save is: a + // reload checks the save card against it. + std::string start_map = {}; + // That checkpoint's START menu: a reload reads the bag again with it. + StartMenu start_menu = StartMenu::BEFORE_POKEMON; + // The frames of where each checkpoint starts, for the start check: a + // save at a checkpoint's end keeps one for the next checkpoint. + StartFrameStore start_frames = {}; + // The next start check keeps the screen as its checkpoint's start + // frame and passes: the user saved there by hand. + bool keep_start_frame = false; +}; + +// After a save is loaded for a checkpoint that starts on `start_map`: the +// save card's place, read from the START menu, against it, at every checks +// level. Empty if the save is there (or the card can't be read), else why +// not. +std::string check_save_place(StoryEnv& env, const std::string& start_map); + +// After a save is loaded, with START's menu `menu`: the lead's moves as its +// summary shows them, which the battles then start from in place of the +// row's (in env's supplies and the ones a reload restores). The row's are +// kept if no move can be read. +void read_lead_moves(StoryEnv& env, StartMenu menu); + +// After a save is loaded, with START's menu `menu`: the Items pocket's +// counts as read (set_from_loaded_bag()), in place of the row's, which +// are kept if nothing can be read. Only with the full menu: the rows +// before it carry the items they have. +void read_bag_supplies(StoryEnv& env, StartMenu menu); + +// Does FRLG's kinds of story step on the console, each with its row of +// story_action_rows() (PokemonFRLG_AutoStoryStepTable.h). A console step +// that fails is a failed Outcome, which the segment answers by reloading. +// Before each step it clears what came up since the step before +// (step_interrupts(), PokemonFRLG_AutoStoryStepInterrupts.h). +class StoryExecutor : public Pokemon::StoryStepExecutor{ +public: + explicit StoryExecutor(StoryEnv& env); + // Its table's actions point at it. + StoryExecutor(const StoryExecutor&) = delete; + StoryExecutor& operator=(const StoryExecutor&) = delete; + + StoryEnv& env(){ + return m_env; + } + // The START menu SET_OPTIONS leaves: the checkpoint's being built. + void set_menu(StartMenu menu){ + m_menu = menu; + } + + // The step's action from the table. + virtual Pokemon::Outcome run(const StoryStep& step, Pokemon::RunState& state) override; + +private: + // How the console does `id`. + Pokemon::StoryAction console_action(StoryActionId id); + + StoryEnv& m_env; + StartMenu m_menu = StartMenu::FULL; + // A failed step fails the step; an interrupt between steps is logged. + InterruptLogGuard m_guard; + Pokemon::StoryActionTable m_table; + Pokemon::TableExecutor m_executor; + // What is cleared between steps, looked for on the screen. + ConsoleScreenLook m_look; + Pokemon::StoryInterrupts m_interrupts; +}; + +// The checkpoint `data` as events, saving at its end. +Pokemon::Checkpoint build_checkpoint(const StoryCheckpoint& data, StoryExecutor& executor); + +// `checkpoints` (kept alive by the caller) as a segment for run_segment(). +Pokemon::Segment make_story_segment(const std::vector& checkpoints, StoryExecutor& executor); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport.cpp new file mode 100644 index 0000000000..35619d684c --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport.cpp @@ -0,0 +1,102 @@ +/* FRLG Authored Checkpoint Export + * From: https://github.com/PokemonAutomation/ + */ +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h" +#include "PokemonFRLG_AutoStoryExport.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ +namespace{ +std::string_view menu_name(StartMenu menu){ + switch (menu){ + case StartMenu::BEFORE_POKEMON: return "before_pokemon"; + case StartMenu::BEFORE_POKEDEX: return "before_pokedex"; + case StartMenu::FULL: return "full"; + } + throw ParseException("Unsupported FRLG START menu."); +} +JsonArray strings(const std::vector& values){ + JsonArray result; + for (const std::string& value : values){ + result.push_back(value); + } + return result; +} +int64_t count(size_t value){ + if (value > (size_t)std::numeric_limits::max()){ + throw ParseException("FRLG checkpoint count exceeds JSON integer range."); + } + return (int64_t)value; +} +JsonObject stats_json(const Stats& stats){ + JsonObject result; + result["hp"] = stats.hp; + result["attack"] = stats.attack; + result["defense"] = stats.defense; + result["sp_attack"] = stats.sp_attack; + result["sp_defense"] = stats.sp_defense; + result["speed"] = stats.speed; + return result; +} +JsonObject member_json(const PartyMember& member){ + JsonObject result; + result["species"] = member.species; + JsonArray moves; + for (const KnownMove& move : member.moves){ + JsonObject entry; + entry["move"] = move.move; + entry["pp"] = move.pp; + moves.push_back(std::move(entry)); + } + result["moves"] = std::move(moves); + result["moves_through_level"] = member.moves_through_level; + result["moves_read"] = member.moves_read; + result["level"] = member.level; + result["stats"] = member.stats ? JsonValue(stats_json(*member.stats)) : JsonValue(); + return result; +} +JsonObject supplies_json(const Supplies& supplies){ + JsonObject result; + result["potions"] = supplies.potions; + result["antidotes"] = supplies.antidotes; + result["parlyz_heals"] = supplies.parlyz_heals; + result["pocket"] = strings(supplies.pocket); + result["status"] = std::string(status_name(supplies.status)); + result["hurt"] = supplies.hurt; + result["hp_red"] = supplies.hp_red; + result["hp_fill"] = supplies.hp_fill; + result["lead"] = member_json(supplies.lead); + JsonArray protected_slots; + for (size_t slot : supplies.protected_slots){ + protected_slots.push_back(count(slot)); + } + result["protected_slots"] = std::move(protected_slots); + result["foes"] = strings(supplies.foes); + result["trainer"] = supplies.trainer; + result["risk"] = std::string(battle_risk_name(supplies.risk)); + result["foe_out"] = supplies.foe_out.empty() ? JsonValue() : JsonValue(supplies.foe_out); + result["wild_foes"] = strings(supplies.wild_foes); + return result; +} +} // namespace +JsonValue story_checkpoint_export(const StoryCheckpoint& checkpoint){ + JsonObject result; + result["format"] = "pokesim-native-checkpoint-export/1"; + result["game"] = "frlg"; + result["status"] = "native-table-export"; + JsonObject native; + native["menu"] = std::string(menu_name(checkpoint.menu)); + native["supplies"] = supplies_json(checkpoint.supplies); + result["native_fields"] = std::move(native); + result["state_basis"] = "native-table-bookkeeping"; + result["unbound"] = strings({"runtime_configuration", "map_pins", "executor_bindings", "entry_evidence", "effective_save_retry_policy"}); + return result; +} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport.h new file mode 100644 index 0000000000..f2cc73c6b2 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport.h @@ -0,0 +1,18 @@ +/* FRLG Authored Checkpoint Export + * From: https://github.com/PokemonAutomation/ + */ +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryExport_H +#define PokemonAutomation_PokemonFRLG_AutoStoryExport_H +#include "Common/Cpp/Json/JsonValue.h" +#include "PokemonFRLG_AutoStoryEvents.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ +// Capture evaluated shared fields and every FRLG checkpoint extension. +// Native supplies are bookkeeping, not observed state or entry requirements. +// Runtime options, map pins, effective policies and execution remain unbound. +JsonValue story_checkpoint_export(const StoryCheckpoint& checkpoint); +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport_Tests.cpp new file mode 100644 index 0000000000..41113be2bf --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport_Tests.cpp @@ -0,0 +1,92 @@ +/* FRLG Checkpoint Export Tests + * From: https://github.com/PokemonAutomation/ + */ +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "PokemonFRLG_AutoStoryExport.h" +#include "PokemonFRLG_AutoStoryTable.h" +#include "PokemonFRLG_AutoStoryExport_Tests.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ +namespace{ +struct ExportInput{ + std::string_view id; + bool custom = false; +}; +struct ExportExpectation{ + std::string_view menu; + std::string_view native_json = {}; +}; +struct ExportCase{ + ExportInput input; + ExportExpectation expectation; +}; +const ExportCase CASES[] = { + {.input = {.id = "00.05"}, .expectation = {.menu = "before_pokedex"}}, + {.input = {.id = "00.05", .custom = true}, .expectation = { + .menu = "full", + .native_json = R"({"menu":"full","supplies":{"potions":2,"antidotes":3,"parlyz_heals":4,"pocket":["antidote",""],"status":"PSN","hurt":true,"hp_red":true,"hp_fill":0.25,"lead":{"species":"wartortle","moves":[{"move":"bite","pp":0}],"moves_through_level":18,"moves_read":true,"level":19,"stats":{"hp":50,"attack":20,"defense":30,"sp_attack":40,"sp_defense":35,"speed":25}},"protected_slots":[0,2],"foes":["staryu"],"trainer":"misty","risk":"high","foe_out":"staryu","wild_foes":["pidgey"]}})" + }}, +}; +void customize(StoryCheckpoint& row){ + row.menu = StartMenu::FULL; + Supplies& state = row.supplies; + state.potions = 2; + state.antidotes = 3; + state.parlyz_heals = 4; + state.pocket = {"antidote", ""}; + state.status = StatusCondition::POISON; + state.hurt = true; + state.hp_red = true; + state.hp_fill = 0.25; + state.lead = PartyMember{.species = "wartortle", .moves = {{"bite", 0}}, + .moves_through_level = 18, .moves_read = true, .level = 19, + .stats = Stats{.hp = 50, .attack = 20, .defense = 30, .sp_attack = 40, .sp_defense = 35, .speed = 25}}; + state.protected_slots = {0, 2}; + state.foes = {"staryu"}; + state.trainer = "misty"; + state.risk = BattleRisk::HIGH; + state.foe_out = "staryu"; + state.wild_foes = {"pidgey"}; +} +std::string check_export(StoryCheckpoint row, const ExportCase& test){ + if (test.input.custom){ + customize(row); + } + const JsonValue encoded = story_checkpoint_export(row); + const JsonObject& root = encoded.to_object_throw(); + const JsonObject& native = root.get_object_throw("native_fields"); + if (native.get_string_throw("menu") != test.expectation.menu){ + return "Expected menu " + std::string(test.expectation.menu) + ", read " + native.get_string_throw("menu"); + } + if (!test.expectation.native_json.empty() && !(JsonValue(native.clone()) == parse_json(std::string(test.expectation.native_json)))){ + return "Expected native fields " + std::string(test.expectation.native_json) + ", read " + native.dump(); + } + return ""; +} +class ExportTest : public UnitTest{ +public: + explicit ExportTest(ExportCase test) + : UnitTest("PokemonFRLG::CheckpointExport - " + std::string(test.input.id) + (test.input.custom ? " custom" : " authored")), m_test(test){} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + for (const auto& row : story_checkpoints()){ + if (row.id == m_test.input.id){ + const std::string error = check_export(row, m_test); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } + } + return UnitTestResult("Expected checkpoint " + std::string(m_test.input.id) + ", read no matching row."); + } +private: + ExportCase m_test; +}; +} // namespace +void add_tests_AutoStoryExport(UnitTestDatabase& database){ + for (const ExportCase& test : CASES){ + database.add(test); + } +} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport_Tests.h new file mode 100644 index 0000000000..90eabc74a9 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport_Tests.h @@ -0,0 +1,15 @@ +/* FRLG Checkpoint Export Tests + * From: https://github.com/PokemonAutomation/ + */ +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryExport_Tests_H +#define PokemonAutomation_PokemonFRLG_AutoStoryExport_Tests_H +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ +// Register evaluated-table and non-default native-extension preservation tests. +void add_tests_AutoStoryExport(UnitTestDatabase& database); +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPoses.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPoses.h new file mode 100644 index 0000000000..553ac917bc --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPoses.h @@ -0,0 +1,73 @@ +/* AutoStory Poses + * + * From: https://github.com/PokemonAutomation/ + * + * Where the story stands and how fast it moves: its poses, the maps it + * plans on, and the run variant. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryPoses_H +#define PokemonAutomation_PokemonFRLG_AutoStoryPoses_H + +#include +#include +#include +#include +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" +#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryBattle.h" +#include "PokemonFRLG_AutoStoryStartFrames.h" +#include "PokemonFRLG_AutoStoryStepInterrupts.h" +#include "PokemonFRLG_AutoStoryStepTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Story leg definition imported from Pokemon AutoStory. +using Pokemon::StoryLeg; +// Story step definition imported from Pokemon AutoStory. +using Pokemon::StoryStep; +// Story step kind classification imported from Pokemon AutoStory. +using Pokemon::StoryStepKind; + +// Where the player stands and faces: the one-tile poses of FRLG's table +// and routes. An unknown facing (after a scene that turns the player) is +// set before the next route by turning to a wall. +struct StoryPose{ + std::string map; + TilePos tile; + std::optional facing; +}; + +// The variant of a ROUTE or LEGS step that runs, with B held: the player +// has the Running Shoes (00.10 on). +inline const std::string RUN_VARIANT = "run"; + +// How `step`, a ROUTE or LEGS, moves the player: RUN_VARIANT runs. +MoveSpeed move_speed(const StoryStep& step); +// The maps the story plans on: every map to Brock, with the objects the +// game hides after the Hall of Fame removed, as the lab's frlg_route does. +const std::vector& story_maps(); + +// Converts a StoryPose to a general navigation Pose. +Pokemon::Pose to_pose(const StoryPose& pose); +// `pose` as a StoryPose: nothing unless it is on one tile. +std::optional story_pose(const Pokemon::Pose& pose); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySaveChecks.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySaveChecks.h new file mode 100644 index 0000000000..218cebb6c5 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySaveChecks.h @@ -0,0 +1,73 @@ +/* AutoStory Save Checks + * + * From: https://github.com/PokemonAutomation/ + * + * Whether a loaded save starts a checkpoint: the save card's place and the + * pose the save stands at. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStorySaveChecks_H +#define PokemonAutomation_PokemonFRLG_AutoStorySaveChecks_H + +#include +#include +#include +#include +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" +#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryBattle.h" +#include "PokemonFRLG_AutoStoryStartFrames.h" +#include "PokemonFRLG_AutoStoryStepInterrupts.h" +#include "PokemonFRLG_AutoStoryStepTable.h" +#include "PokemonFRLG_AutoStoryPoses.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The place the save card names for a save on `map` (see +// read_save_card_location()), or empty for a map whose place isn't known. +std::string save_card_place(const std::string& map); + +// Why a save whose card names `place` can't start a checkpoint that starts +// on `start_map`, or empty if it can: the places match, the card couldn't +// be read (empty `place`), or the map has no known place. +std::string save_place_error(const std::string& start_map, const std::string& place); + +// Why a save standing at `stands` can't start a checkpoint that starts at +// `start`, or empty if it can: the same map and tile, and the same facing +// when both are known. +std::string start_pose_mismatch(const Pokemon::Pose& start, const StoryPose& stands); + +// Where the save just loaded stands, as the game reads it: nothing when it +// can't be read. +using SavePoseReader = std::function()>; +// Where the start check says what it found. +using StoryLog = std::function; + +// Adds to `checkpoint`, built from a row that starts at `start`, the start +// check: the save it starts from, as `read` reads it, must stand there +// (start_pose_mismatch()), or the checkpoint stops before its first event, +// "start_failed". A save that can't be read passes. `log` gets a +// mismatch, or that nothing was read. A row with no start (a new game) +// gets none. (add_start_check() with a reader of the tile.) +void add_start_pose_check( + Pokemon::Checkpoint& checkpoint, const std::optional& start, SavePoseReader read, StoryLog log +); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp new file mode 100644 index 0000000000..20cbaf91ce --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp @@ -0,0 +1,477 @@ +/* AutoStory Simulation Tests + * + * From: https://github.com/PokemonAutomation/ + * + * A run of the whole story table, new game to the Boulder Badge, without + * the console: story_checkpoints() built into engine checkpoints by the + * shared builder, saving at each end as the program does, run by the + * shared runner with the program's retry policy, against a fake game. + * The fake plans each ROUTE on the story maps from where the run's pose + * says we stand (turning to a wall when the facing is unknown, as the + * program does), walks each LEGS on them, steps onto triggers, and passes + * every other step unless told to fail it. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" +#include "PokemonFRLG_AutoStoryStepTable.h" +#include "PokemonFRLG_AutoStoryTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +using Pokemon::Outcome; +using Pokemon::RunState; + +std::string joined(const std::vector& lines){ + std::string text; + for (const std::string& line : lines){ + text += "\n " + line; + } + return text; +} + +// A checkpoint's start as the engine's Pose: nothing for a new game. +std::optional start_pose(const StoryCheckpoint& checkpoint){ + if (!checkpoint.start){ + return std::nullopt; + } + return Pokemon::pose_of(*checkpoint.start); +} + +const MapData* map_named(const std::string& name){ + for (const MapData& map : story_maps()){ + if (map.name == name){ + return ↦ + } + } + return nullptr; +} + +// Whether the player, at the end of a WALK `step`, stops there holding on: +// the map's edge, a wall, or water to Surf onto, but no warp of any kind, +// even one to a map that isn't loaded. +bool stops_past_end(const RouteStep& step){ + const MapData& map = *map_named(step.end.map); + const TilePos here = step.end.point; + const TilePos ahead = here.next(step.direction); + if (!in_bounds(map, ahead)){ + return true; + } + if (warps_on_step(map, ahead) || exit_mat(map, here) == step.direction + || (step.direction == Direction::NORTH && is_door(map, ahead)) + ){ + return false; + } + const StepKind kind = classify_step(map, PlayerState{here, elevation_at(map, here), step.surfing}, step.direction); + return kind == StepKind::BLOCKED || kind == StepKind::START_SURF; +} + +// The first leg of `route` to a wall that holding on would carry past its +// end, or nothing (console B, 2026-11-02: one rode Route 4's Pokemon +// Center escalator). +std::optional overrun_wall_leg(const std::vector& route){ + for (const RouteStep& step : route){ + if (step.to_wall && !stops_past_end(step)){ + return to_string(step); + } + } + return std::nullopt; +} + +// Where the run stands, with a facing: a wall beside it when unknown. +struct Standing{ + MapPosition position; + Direction facing = Direction::NORTH; + std::string error; +}; +Standing standing(const Pokemon::Pose& pose){ + const std::optional at = story_pose(pose); + if (!at){ + return {{}, Direction::NORTH, "no one-tile pose: " + Pokemon::to_string(pose)}; + } + std::optional facing = at->facing; + if (!facing){ + const MapData* map = map_named(at->map); + facing = map ? wall_beside(*map, at->tile) : std::nullopt; + } + if (!facing){ + return {{}, Direction::NORTH, "facing unknown and no wall beside " + to_string(MapPosition{at->map, at->tile})}; + } + return {{at->map, at->tile}, *facing, ""}; +} + +class FakeGame : public Pokemon::StoryStepExecutor{ +public: + struct Failure{ + std::string failure; + size_t times = 0; + }; + + std::vector trace; + std::map failures; + // Where the save loaded stands, when not at its checkpoint's start. + std::optional save_stands; + // What the Mart sold, by its list's names. + std::map bag; + + virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ + m_row = data.id; + trace.push_back("begin " + data.id); + } + virtual Outcome run(const StoryStep& step, RunState& state) override{ + const std::string key = m_row + "/" + step.name; + trace.push_back(key); + auto failure = failures.find(key); + if (failure != failures.end() && failure->second.times > 0){ + failure->second.times--; + return Pokemon::outcome_failed(failure->second.failure, key); + } + return act(state, step); + } +private: + // The step by its kind, as the console does it (StoryExecutor), with + // nothing done on a screen. + Outcome act(RunState& state, const StoryStep& step){ + switch (step.kind){ + case StoryStepKind::ROUTE: + return walk_to(state.pose, step); + case StoryStepKind::LEGS: + return legs(state, step); + case StoryStepKind::STEP: + return take_step(state, step); + case StoryStepKind::READY: + return ready(state, step); + case StoryStepKind::SHOP: + return shop(step); + case StoryStepKind::NEW_GAME: + case StoryStepKind::OPTIONS: + case StoryStepKind::TALK: + case StoryStepKind::ANSWER: + case StoryStepKind::MASH: + case StoryStepKind::BATTLE: + case StoryStepKind::HEAL: + return Pokemon::outcome_ok(); + default: + return Pokemon::unsupported_step(step); + } + } + Outcome legs(RunState& state, const StoryStep& step){ + const Standing at = standing(state.pose); + if (!at.error.empty()){ + return Pokemon::outcome_failed("no_pose", at.error); + } + const std::optional> route = fixed_route(story_maps(), at.position, Pokemon::story_arg>(step.args, "legs")); + if (!route || route->empty()){ + return Pokemon::outcome_failed("bad_legs", to_string(at.position)); + } + return Pokemon::outcome_ok(to_pose(StoryPose{route->back().end.map, route->back().end.point, route->back().facing_after})); + } + Outcome take_step(RunState& state, const StoryStep& step){ + const std::optional at = story_pose(state.pose); + if (!at){ + return Pokemon::outcome_failed("no_pose", Pokemon::to_string(state.pose)); + } + const Direction direction = Pokemon::story_arg(step.args, "direction"); + return Pokemon::outcome_ok(to_pose(StoryPose{at->map, at->tile.next(direction), direction})); + } + // The nurse's way must plan too, but the run goes on from where it stands. + Outcome ready(RunState& state, const StoryStep& step){ + const Outcome to_nurse = walk_to(state.pose, step); + return to_nurse.succeeded() ? Pokemon::outcome_ok() : to_nurse; + } + // The Viridian Mart's list as the game shows it. After a purchase the + // cursor stays on the row bought (console B, 2026-11-01), so each + // order moves it from there, as buy_items() does since ad5d40885. + Outcome shop(const StoryStep& step){ + const std::vector& items = Pokemon::story_arg>(step.args, "items"); + static const std::vector LIST{"poke_ball", "potion", "antidote", "parlyz_heal", "cancel"}; + const std::optional> orders = viridian_mart_orders(items); + if (!orders){ + return Pokemon::outcome_failed("unknown_item", step.name); + } + int cursor = 0; + for (size_t c = 0; c < orders->size(); c++){ + const MartOrder& order = (*orders)[c]; + // The presses: down or up from where the cursor is. + cursor += order.row - cursor; + if (cursor < 0 || cursor >= (int)LIST.size() || LIST[cursor] == "cancel"){ + return Pokemon::outcome_failed("mart_cancel", std::format("order {} ends on row {}", c + 1, cursor + 1)); + } + if (LIST[cursor] != items[c].item){ + return Pokemon::outcome_failed("wrong_item", std::format("{} instead of {}", LIST[cursor], items[c].item)); + } + bag[LIST[cursor]] += order.quantity; + } + return Pokemon::outcome_ok(); + } + + Outcome walk_to(const Pokemon::Pose& pose, const StoryStep& step){ + const Standing at = standing(pose); + if (!at.error.empty()){ + return Pokemon::outcome_failed("no_pose", at.error); + } + const std::optional target = story_pose(Pokemon::pose_of(Pokemon::story_arg(step.args, "target"))); + const RouteGoal goal{{target->map, target->tile}, target->facing}; + const std::optional> route = plan_overworld_route( + story_maps(), at.position, goal, default_route_costs(), at.facing + ); + if (!route){ + return Pokemon::outcome_failed("no_route", to_string(at.position) + " to " + to_string(goal.position)); + } + const MapPosition end = follow_overworld_route(story_maps(), at.position, *route); + if (!(end == goal.position)){ + return Pokemon::outcome_failed("wrong_end", to_string(end)); + } + if (const std::optional leg = overrun_wall_leg(*route)){ + return Pokemon::outcome_failed("wall_overrun", *leg); + } + const Direction facing = route->empty() ? at.facing : route->back().facing_after; + return Pokemon::outcome_ok(to_pose(StoryPose{target->map, target->tile, facing})); + } + + std::string m_row; +}; + + +// One simulated run, segment built as the program builds it: each +// checkpoint saves at its end (hooks.save stands for save_game()). +struct Simulation{ + FakeGame game; + std::vector lines; + // Where each save stood: the end of its checkpoint. + std::vector> saves; + Pokemon::SegmentPolicy policy; + + Pokemon::SegmentReport run(const Pokemon::SegmentRange& range){ + Pokemon::Segment segment; + segment.id = "00"; + for (const StoryCheckpoint& data : story_checkpoints()){ + segment.checkpoints.push_back(Pokemon::CheckpointSpec{ + .id = data.id, .title = data.title, .saves = true, + .build = [this, &data]{ + Pokemon::Checkpoint checkpoint = Pokemon::build_story_checkpoint(data, game); + add_start_pose_check(checkpoint, start_pose(data), [this]{ return game.save_stands; }, [this](const std::string& line){ lines.push_back(line); }); + return checkpoint; + }, + }); + } + Pokemon::SegmentHooks hooks; + hooks.save = [this](RunState& state){ + game.trace.push_back("save"); + saves.emplace_back(last_begun(), state.pose); + return Pokemon::outcome_ok(); + }; + hooks.reload = [this](RunState&){ + game.trace.push_back("reload"); + return Pokemon::outcome_ok(); + }; + hooks.log = [this](const std::string& line){ lines.push_back(line); }; + RunState state; + return Pokemon::run_segment(range, policy, segment, hooks, state); + } + std::string last_begun() const{ + for (auto it = game.trace.rbegin(); it != game.trace.rend(); ++it){ + if (it->starts_with("begin ")){ + return it->substr(6); + } + } + return ""; + } + std::vector begun() const{ + std::vector ids; + for (const std::string& item : game.trace){ + if (item.starts_with("begin ")){ + ids.push_back(item.substr(6)); + } + } + return ids; + } + size_t count(const std::string& item) const{ + return (size_t)std::count(game.trace.begin(), game.trace.end(), item); + } +}; + + +struct AutoStorySimulationInput{ + std::string name; + UnitTestResult (*body)(); +}; + +struct AutoStorySimulationExpectation{ + std::string_view description; +}; + +struct AutoStorySimulationTestCase{ + AutoStorySimulationInput input; + AutoStorySimulationExpectation expectation; +}; + +class Test_AutoStorySimulation : public UnitTest{ +public: + explicit Test_AutoStorySimulation(AutoStorySimulationTestCase scenario) + : UnitTest("PokemonFRLG::AutoStory - Simulation: " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_scenario.input.body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + AutoStorySimulationTestCase m_scenario; +}; + + +UnitTestResult test_whole_story(){ + Simulation sim; + const Pokemon::SegmentReport report = sim.run({}); + if (!report.completed){ + return "Expected the whole story through:" + joined(sim.lines); + } + std::vector ids; + for (const StoryCheckpoint& data : story_checkpoints()){ + ids.push_back(data.id); + } + if (sim.begun() != ids || sim.saves.size() != ids.size()){ + return "Expected each checkpoint once, in order, each saving at its end:" + joined(sim.game.trace); + } + // Each checkpoint starts where the save before it stands. + for (size_t c = 1; c < story_checkpoints().size(); c++){ + const StoryCheckpoint& data = story_checkpoints()[c]; + const std::optional start = story_pose(*start_pose(data)); + const std::optional saved = story_pose(sim.saves[c - 1].second); + const bool same = start && saved && start->map == saved->map && start->tile == saved->tile + && (!start->facing || start->facing == saved->facing); + if (!same){ + return std::format("{} starts at {}, but {} saved at {}.", data.id, + Pokemon::to_string(*start_pose(data)), sim.saves[c - 1].first, Pokemon::to_string(sim.saves[c - 1].second)); + } + } + if (report.one_shot_passes() != report.checkpoints_run){ + return "Expected every checkpoint one-shot:" + joined(sim.lines); + } + // 00.07's shopping, with the cursor staying on each row bought. + const std::map bought{{"potion", 5}, {"antidote", 3}, {"parlyz_heal", 1}}; + if (sim.game.bag != bought){ + std::string text; + for (const auto& item : sim.game.bag){ + text += std::format(" {} {}", item.second, item.first); + } + return "Expected 5 Potions, 3 Antidotes and 1 Parlyz Heal; bought" + text + "."; + } + return true; +} + +UnitTestResult test_start_and_end(){ + Simulation sim; + const Pokemon::SegmentReport report = sim.run({.from = "00.05", .to = "00.07"}); + if (!report.completed || sim.begun() != std::vector{"00.05", "00.06", "00.07"}){ + return "Expected 00.05 to 00.07 only:" + joined(sim.begun()); + } + return true; +} + +// A walk that fails once (a trainer the walker could not recover from): +// the checkpoint reloads its last save and runs again from its start. +UnitTestResult test_retry_from_save(){ + Simulation sim; + sim.game.failures["00.08/forest_north"] = {.failure = "operation_failed", .times = 1}; + const Pokemon::SegmentReport report = sim.run({.from = "00.08", .to = "00.09"}); + if (!report.completed || report.reloads != 1 || sim.begun() != std::vector{"00.08", "00.08", "00.09"} + || sim.count("00.08/forest_east") != 2 + ){ + return "Expected 00.08 reloaded once and run again from its start:" + joined(sim.game.trace); + } + if (std::find(sim.lines.begin(), sim.lines.end(), "[Checkpoint] 00.08: passed on attempt 2 (1 reset)") == sim.lines.end()){ + return "Expected the retried pass logged:" + joined(sim.lines); + } + return true; +} + +// console B, FRLG 00.27, 2026-11-09: the save stood below Cerulean Center's +// door, and the run walked as if from the counter where 00.27 starts. 00.09 +// from below Pewter Center's door (17, 25) stops before any step or save. +UnitTestResult test_save_off_start_pose(){ + Simulation sim; + sim.game.save_stands = StoryPose{"PewterCity", TilePos{17, 26}, Direction::SOUTH}; + const Pokemon::SegmentReport report = sim.run({.from = "00.09", .to = "00.09"}); + const auto stepped = [](const std::string& item){ return item.starts_with("00.09/"); }; + const auto told = [](const std::string& line){ return line.starts_with("start pose mismatch: "); }; + if (report.completed || report.failure.failure != "start_failed" || !sim.saves.empty() + || std::ranges::any_of(sim.game.trace, stepped) || std::ranges::none_of(sim.lines, told) + ){ + return "Expected 00.09 stopped at its start check, the mismatch logged:" + joined(sim.game.trace) + joined(sim.lines); + } + return true; +} + +// Brock's battle lost every time: three attempts, then the stop. +UnitTestResult test_gives_up_after_attempts(){ + Simulation sim; + sim.game.failures["00.09/brock"] = {.failure = "blackout", .times = 10}; + const Pokemon::SegmentReport report = sim.run({.from = "00.09", .to = std::nullopt}); + if (report.completed || report.reloads != 2 || report.failed_checkpoint != "00.09" || report.failed_event != "brock" + || report.failure.failure != "blackout" || sim.count("00.09/brock") != 3 || !sim.saves.empty() + ){ + return "Expected 00.09 tried 3 times, then a stop on Brock:" + joined(sim.game.trace) + joined(sim.lines); + } + return true; +} + +const AutoStorySimulationTestCase AUTO_STORY_SIMULATION_CASES[] = { + { + .input = {.name = "new game to Brock, in order, each start where the last save stood", .body = test_whole_story}, + .expectation = {.description = "runs full story progression from new game through Brock gym"}, + }, + { + .input = {.name = "start and end checkpoints", .body = test_start_and_end}, + .expectation = {.description = "executes segment bounded by start and end checkpoints"}, + }, + { + .input = {.name = "a failed walk reloads its checkpoint's save", .body = test_retry_from_save}, + .expectation = {.description = "reloads checkpoint save state on simulated movement failure"}, + }, + { + .input = {.name = "a battle lost every time stops after 3 attempts", .body = test_gives_up_after_attempts}, + .expectation = {.description = "aborts after three consecutive battle blackouts"}, + }, + { + .input = {.name = "a save off the start pose stops before any step", .body = test_save_off_start_pose}, + .expectation = {.description = "fails the start check without walking or saving"}, + }, +}; + +} // namespace + + +void add_tests_AutoStorySimulation(UnitTestDatabase& database){ + add_tests_AutoStoryStepTable(database); + add_tests_AutoStoryStartFrames(database); + for (const auto& scenario : AUTO_STORY_SIMULATION_CASES){ + database.add(scenario); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrameCompare.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrameCompare.h new file mode 100644 index 0000000000..0755595658 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrameCompare.h @@ -0,0 +1,56 @@ +/* AutoStory Start Frame Compare + * + * From: https://github.com/PokemonAutomation/ + * + * A checkpoint start's frame as the start check keeps it, and how another + * frame differs from it. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryStartFrameCompare_H +#define PokemonAutomation_PokemonFRLG_AutoStoryStartFrameCompare_H + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The game screen as the start check keeps and compares it: the GBA's own +// 240x160 pixels, 15x10 tiles of 16. `game_screen` is the game's part of +// the frame (GameSettings' GAME_BOX). +ImageRGB32 start_frame(const ImageViewRGB32& game_screen); + +// How a frame differs from a checkpoint start's frame, tile by tile. +struct StartFrameDifference{ + size_t tiles = 0; + // The tiles whose pixels differ by more than an animated tile's do. + size_t changed = 0; +}; + +// The two frames, each scaled as start_frame() does, tile by tile. +StartFrameDifference compare_start_frames(const ImageViewRGB32& reference, const ImageViewRGB32& frame); + +// Whether the difference leaves the same place: few enough tiles changed +// for people who moved, too many for another place (see the .cpp). +bool same_start_place(const StartFrameDifference& difference); + +// "12 of 150 tiles changed". +std::string to_string(const StartFrameDifference& difference); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrameStore.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrameStore.h new file mode 100644 index 0000000000..c20800708b --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrameStore.h @@ -0,0 +1,82 @@ +/* AutoStory Start Frame Store + * + * From: https://github.com/PokemonAutomation/ + * + * The start check on frames, and where the start frames are kept. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryStartFrameStore_H +#define PokemonAutomation_PokemonFRLG_AutoStoryStartFrameStore_H + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" +#include "PokemonFRLG_AutoStoryStartFrameCompare.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// What a start reader found about the save just loaded. +enum class StartFound{ + // It can't tell: the check passes. + NOT_READ, + AT_START, + ELSEWHERE, +}; +// A start reader's answer, with the line the start check logs for it. +struct StartRead{ + StartFound found = StartFound::NOT_READ; + // For the log: why nothing was read, or what was seen. + std::string detail = {}; +}; + +// The game screen now, as start_frame() makes it; an empty image when +// there is no video. Called again for each frame tried. +using StartFrameSource = std::function; + +// The start check on frames: up to `tries` frames from `next_frame` +// against `reference`, the first one that shows the same place +// (same_start_place()) passing, so a fade or a passer-by in front of the +// camera on one frame doesn't fail the check. No reference, or no video, +// is NOT_READ. +StartRead read_start_frames(const std::optional& reference, const StartFrameSource& next_frame, size_t tries); + + +// Where the start frames are kept: for each checkpoint, .png, the +// frame, and .json, the checkpoint, when it was kept and why. +class StartFrameStore{ +public: + // Keeps nothing and finds nothing (the simulation). + StartFrameStore() = default; + // `folder` ends with "/". + explicit StartFrameStore(std::string folder); + + // Replaces the frame kept for `checkpoint`; `source` says why it is kept. + // Returns false if it couldn't be written. + bool save(const std::string& checkpoint, const ImageViewRGB32& frame, const std::string& source) const; + // The frame kept for `checkpoint`, if any. + std::optional load(const std::string& checkpoint) const; + +private: + std::string m_folder; +}; + +// The program's store: USER_FILE_PATH()/PokemonFRLG/AutoStoryStartFrames/. +StartFrameStore program_start_frames(); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrames.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrames.cpp new file mode 100644 index 0000000000..22658b98fb --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrames.cpp @@ -0,0 +1,247 @@ +/* AutoStory Start Frames + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Filesystem/Filesystem.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "CommonFramework/GlobalAutoPaths.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" +#include "PokemonFRLG_AutoStoryStartFrames.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +constexpr size_t FRAME_WIDTH = 240; +constexpr size_t FRAME_HEIGHT = 160; +constexpr size_t TILE = 16; +// A tile is compared as its four 8x8 quarters' average colours, so an +// animated tile, whose pattern shifts a few pixels, keeps its averages. +constexpr size_t BLOCK = 8; + +// The thresholds, from console B's captures (Route 10 outside the +// Center and on its grass, S.S. Anne's 1F corridor) and edits of them, +// with 8x8 quarters and 24 below: +// - the same frame with the player's 16x32 sprite copied onto one or two +// other tiles, as a person who walked there: 1 to 4 tiles changed of +// 150; the river's pattern shifted 2 or 4 pixels, as its animation +// does: 0 to 10; +// - another place on the same route, or Route 10 against the S.S. Anne: +// 131 and 148; +// - the view one step off: 20 to 78, depending on how plain the floor is; +// six steps along the S.S. Anne's plain corridor: 36. +// A quarter of the tiles (37) leaves room for a river and 6 people who +// moved (at most 4 tiles each: where they stood and stand), and catches +// another place and 5 of the 6 single steps off; a step along a plain +// corridor can pass. + +// A tile has changed when its quarters differ by more than this, on +// average per colour channel (0 to 255). +constexpr unsigned TILE_CHANGE = 24; +// The same place when at most a quarter of the tiles changed. +constexpr size_t MOST_CHANGED_PERCENT = 25; + +// Frames the console's start check tries, a second apart: a fade or a +// passer-by in front of the camera on one frame doesn't fail it. +constexpr size_t START_FRAME_TRIES = 3; +constexpr Milliseconds START_FRAME_WAIT = std::chrono::milliseconds(1000); + +// The block at (`bx`, `by`): its channels' totals in `a` less those in +// `b`, summed as absolute values. +uint64_t block_difference(const ImageViewRGB32& a, const ImageViewRGB32& b, size_t bx, size_t by){ + int64_t sums[3] = {0, 0, 0}; + for (size_t y = by; y < by + BLOCK; y++){ + for (size_t x = bx; x < bx + BLOCK; x++){ + const uint32_t p = a.pixel(x, y); + const uint32_t q = b.pixel(x, y); + for (int c = 0; c < 3; c++){ + sums[c] += (int64_t)((p >> (8 * c)) & 0xff) - (int64_t)((q >> (8 * c)) & 0xff); + } + } + } + return (uint64_t)(std::llabs(sums[0]) + std::llabs(sums[1]) + std::llabs(sums[2])); +} + +// The tile at (`tx`, `ty`)'s quarters' average difference per channel. +unsigned tile_difference(const ImageViewRGB32& a, const ImageViewRGB32& b, size_t tx, size_t ty){ + uint64_t total = 0; + for (size_t by = ty * TILE; by < (ty + 1) * TILE; by += BLOCK){ + for (size_t bx = tx * TILE; bx < (tx + 1) * TILE; bx += BLOCK){ + total += block_difference(a, b, bx, by); + } + } + return (unsigned)(total / (TILE * TILE * 3)); +} + +} // namespace + + +ImageRGB32 start_frame(const ImageViewRGB32& game_screen){ + return game_screen.scale_to(FRAME_WIDTH, FRAME_HEIGHT); +} + +StartFrameDifference compare_start_frames(const ImageViewRGB32& reference, const ImageViewRGB32& frame){ + const ImageRGB32 a = start_frame(reference); + const ImageRGB32 b = start_frame(frame); + StartFrameDifference difference; + for (size_t ty = 0; ty < FRAME_HEIGHT / TILE; ty++){ + for (size_t tx = 0; tx < FRAME_WIDTH / TILE; tx++){ + difference.tiles++; + if (tile_difference(a, b, tx, ty) > TILE_CHANGE){ + difference.changed++; + } + } + } + return difference; +} + +bool same_start_place(const StartFrameDifference& difference){ + return difference.tiles > 0 && difference.changed * 100 <= difference.tiles * MOST_CHANGED_PERCENT; +} + +std::string to_string(const StartFrameDifference& difference){ + return std::format("{} of {} tiles changed", difference.changed, difference.tiles); +} + + +StartRead read_start_frames(const std::optional& reference, const StartFrameSource& next_frame, size_t tries){ + if (!reference){ + return {StartFound::NOT_READ, "no start frame kept for this checkpoint"}; + } + std::string seen; + for (size_t attempt = 0; attempt < tries; attempt++){ + const ImageRGB32 frame = next_frame(); + if (!frame){ + return {StartFound::NOT_READ, "no video"}; + } + const StartFrameDifference difference = compare_start_frames(*reference, frame); + if (same_start_place(difference)){ + return {StartFound::AT_START, "the start frame matches: " + to_string(difference)}; + } + seen += (seen.empty() ? "" : ", ") + to_string(difference); + } + return {StartFound::ELSEWHERE, "the screen isn't the checkpoint's start frame: " + seen}; +} + + +StartFrameStore::StartFrameStore(std::string folder) + : m_folder(std::move(folder)) +{} + +bool StartFrameStore::save(const std::string& checkpoint, const ImageViewRGB32& frame, const std::string& source) const{ + if (m_folder.empty()){ + return false; + } + Filesystem::create_directories(m_folder); + if (!frame.save(m_folder + checkpoint + ".png")){ + return false; + } + JsonObject json; + json["checkpoint"] = checkpoint; + json["kept"] = now_to_filestring(); + json["source"] = source; + JsonValue(std::move(json)).dump(m_folder + checkpoint + ".json"); + return true; +} + +std::optional StartFrameStore::load(const std::string& checkpoint) const{ + const std::string path = m_folder + checkpoint + ".png"; + if (m_folder.empty() || !Filesystem::exists(path)){ + return std::nullopt; + } + ImageRGB32 frame(path); + if (!frame){ + return std::nullopt; + } + return frame; +} + +StartFrameStore program_start_frames(){ + return StartFrameStore(USER_FILE_PATH() + "PokemonFRLG/AutoStoryStartFrames/"); +} + + +ImageRGB32 console_start_frame(ConsoleHandle& console, ProControllerContext& context){ + context.wait_for_all_requests(); + const VideoSnapshot snapshot = console.video().snapshot(); + if (!snapshot){ + return ImageRGB32(); + } + return start_frame(extract_box_reference(snapshot, GameSettings::instance().GAME_BOX)); +} + +StartRead check_console_start( + ConsoleHandle& console, ProControllerContext& context, const StartFrameStore& store, const std::string& checkpoint +){ + size_t frames = 0; + return read_start_frames(store.load(checkpoint), [&]{ + if (frames++ > 0){ + context.wait_for(START_FRAME_WAIT); + } + return console_start_frame(console, context); + }, START_FRAME_TRIES); +} + +bool keep_console_frame( + ConsoleHandle& console, ProControllerContext& context, const StartFrameStore& store, + const std::string& checkpoint, const std::string& source +){ + const ImageRGB32 frame = console_start_frame(console, context); + return frame && store.save(checkpoint, frame, source); +} + +StartRead keep_console_start( + ConsoleHandle& console, ProControllerContext& context, const StartFrameStore& store, const std::string& checkpoint +){ + if (!keep_console_frame(console, context, store, checkpoint, "kept by the program's option from the save loaded")){ + return {StartFound::NOT_READ, "couldn't keep the screen as " + checkpoint + "'s start frame"}; + } + return {StartFound::AT_START, "kept the screen as " + checkpoint + "'s start frame"}; +} + + +void add_start_check( + Pokemon::Checkpoint& checkpoint, const std::optional& start, StartReader read, + std::function log +){ + if (!start){ + return; + } + checkpoint.start.push_back(Pokemon::condition("save_at_start_pose", + [read = std::move(read), log = std::move(log)](Pokemon::RunState&){ + const StartRead found = read(); + switch (found.found){ + case StartFound::NOT_READ: + log("start pose not read: " + (found.detail.empty() ? "" : found.detail + "; ") + + "going on from the save as the checkpoint's start."); + return true; + case StartFound::AT_START: + if (!found.detail.empty()){ + log("start pose matches: " + found.detail); + } + return true; + case StartFound::ELSEWHERE: + log("start pose mismatch: " + found.detail); + return false; + } + return false; + } + )); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrames.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrames.h new file mode 100644 index 0000000000..479a2beee6 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrames.h @@ -0,0 +1,87 @@ +/* AutoStory Start Frames + * + * From: https://github.com/PokemonAutomation/ + * + * The console's start check, with no reader for the map or the tile: a + * frame of the game where each checkpoint starts, kept when the program + * saves there, and the frame after that save is loaded compared with it. + * FRLG's camera follows the player on whole tiles, so the same pose shows + * the same tiles, up to people walking about and animated tiles (water, + * flowers); another place, even a step away, shows other tiles. + * + * Also the start check itself (add_start_check()), which takes its + * reader: frames on the console, the save's pose in the simulation. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryStartFrames_H +#define PokemonAutomation_PokemonFRLG_AutoStoryStartFrames_H + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" +#include "PokemonFRLG_AutoStoryStartFrameStore.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + + +// The game screen on the console now, as start_frame() makes it; empty +// with no video. +ImageRGB32 console_start_frame(ConsoleHandle& console, ProControllerContext& context); + +// The console's start check for `checkpoint`: the screen against the +// frame `store` keeps for it, up to 3 frames a second apart +// (read_start_frames()). +StartRead check_console_start( + ConsoleHandle& console, ProControllerContext& context, const StartFrameStore& store, const std::string& checkpoint +); + +// The screen kept as `checkpoint`'s start frame, `source` saying why. +// Returns false if there was no video or it couldn't be written. +bool keep_console_frame( + ConsoleHandle& console, ProControllerContext& context, const StartFrameStore& store, + const std::string& checkpoint, const std::string& source +); + +// The start check for a save made by hand: the screen is kept as +// `checkpoint`'s start frame, and the save is taken to be there. +StartRead keep_console_start( + ConsoleHandle& console, ProControllerContext& context, const StartFrameStore& store, const std::string& checkpoint +); + + +// Where the save just loaded is, against the start of the checkpoint it +// starts. +using StartReader = std::function; + +// Adds to `checkpoint`, built from a row that starts at `start`, the start +// check: the save it starts from, as `read` finds it, must be there, or +// the checkpoint stops before its first event, "start_failed". A save +// `read` can't tell about passes. `log` gets a mismatch ("start pose +// mismatch: "), that nothing was read ("start pose not read: "), or what +// a match saw. A row with no start (a new game) gets none. +void add_start_check( + Pokemon::Checkpoint& checkpoint, const std::optional& start, StartReader read, + std::function log +); + + +// Registers the comparison's and the store's unit tests (synthetic frames). +void add_tests_AutoStoryStartFrames(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrames_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrames_Tests.cpp new file mode 100644 index 0000000000..f6a9cfb692 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrames_Tests.cpp @@ -0,0 +1,480 @@ +/* AutoStory Start Frames Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The start frame comparison on synthetic screens: a map of textured + * 16x16 tiles seen through the GBA's 15x10-tile camera, with people drawn + * on it, scaled up to the size the game takes in a 1080p capture and + * given a capture's noise. The thresholds were chosen on console B's + * captures (see PokemonFRLG_AutoStoryStartFrames.cpp); game captures + * aren't kept in the repo. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Filesystem/Filesystem.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/GlobalAutoPaths.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" +#include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryStartFrames.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +constexpr size_t TILE = 16; +constexpr size_t VIEW_TILES_X = 15; +constexpr size_t VIEW_TILES_Y = 10; +// GAME_BOX in a 1920x1080 capture. +constexpr size_t CAPTURE_WIDTH = 1560; +constexpr size_t CAPTURE_HEIGHT = 1040; + +uint32_t next_random(uint32_t& state){ + state = state * 1664525u + 1013904223u; + return state >> 8; +} + +uint32_t rgb(uint32_t r, uint32_t g, uint32_t b){ + return 0xff000000 | (std::min(r, 255) << 16) | (std::min(g, 255) << 8) | std::min(b, 255); +} + +// A map's tiles: indoor floors and walls, or grass, paths and trees. +struct Tileset{ + std::vector colors; +}; +const Tileset INDOOR{{rgb(200, 184, 152), rgb(176, 160, 128), rgb(232, 224, 208), rgb(120, 112, 104), rgb(208, 96, 72), rgb(88, 136, 200)}}; +const Tileset OUTDOOR{{rgb(96, 192, 120), rgb(72, 160, 96), rgb(216, 200, 144), rgb(48, 112, 64), rgb(120, 168, 232), rgb(152, 136, 120)}}; + +// The tile `kind` of `tileset`: its colour, shaded in a pattern of its own. +uint32_t tile_pixel(const Tileset& tileset, size_t kind, size_t x, size_t y){ + const uint32_t base = tileset.colors[kind % tileset.colors.size()]; + const int shade = (int)((x * (3 + kind) + y * (5 + 2 * kind)) % 7) * 10 - 30; + const auto channel = [&](int shift){ + return (uint32_t)std::clamp((int)((base >> shift) & 0xff) + shade, 0, 255); + }; + return rgb(channel(16), channel(8), channel(0)); +} + +// A map of 40x30 tiles, the same for the same seed. +struct Map{ + const Tileset* tileset; + std::vector tiles; +}; +constexpr size_t MAP_WIDTH = 40; +constexpr size_t MAP_HEIGHT = 30; +Map make_map(const Tileset& tileset, uint32_t seed){ + Map map{&tileset, {}}; + for (size_t c = 0; c < MAP_WIDTH * MAP_HEIGHT; c++){ + map.tiles.push_back(next_random(seed) % tileset.colors.size()); + } + return map; +} + +// A person standing on view tile (`tx`, `ty`): 16x32, their head on the +// tile above. +struct Person{ + size_t tx; + size_t ty; +}; + +// What the camera at map tile (`cx`, `cy`) shows, with `people` on it, as +// the capture shows the game: scaled up, with noise. +ImageRGB32 screen(const Map& map, size_t cx, size_t cy, const std::vector& people, uint32_t noise_seed){ + ImageRGB32 view(VIEW_TILES_X * TILE, VIEW_TILES_Y * TILE); + for (size_t y = 0; y < view.height(); y++){ + for (size_t x = 0; x < view.width(); x++){ + const size_t kind = map.tiles[(cy + y / TILE) * MAP_WIDTH + cx + x / TILE]; + view.pixel(x, y) = tile_pixel(*map.tileset, kind, x % TILE, y % TILE); + } + } + for (const Person& person : people){ + for (size_t y = person.ty * TILE - TILE; y < person.ty * TILE + TILE; y++){ + for (size_t x = person.tx * TILE; x < person.tx * TILE + TILE; x++){ + const size_t row = y - (person.ty * TILE - TILE); + view.pixel(x, y) = row < 10 ? rgb(232, 64, 48) : row < 20 ? rgb(248, 208, 168) : rgb(48, 80, 176); + } + } + } + ImageRGB32 capture = view.scale_to(CAPTURE_WIDTH, CAPTURE_HEIGHT); + for (size_t y = 0; y < capture.height(); y++){ + for (size_t x = 0; x < capture.width(); x++){ + const uint32_t pixel = capture.pixel(x, y); + const int jitter = (int)(next_random(noise_seed) % 9) - 4; + const auto channel = [&](int shift){ + return (uint32_t)std::clamp((int)((pixel >> shift) & 0xff) + jitter, 0, 255); + }; + capture.pixel(x, y) = rgb(channel(16), channel(8), channel(0)); + } + } + return capture; +} + +const Map CENTER = make_map(INDOOR, 27); +const Map CITY = make_map(OUTDOOR, 10); +const Map ROUTE = make_map(OUTDOOR, 4); +// The player, in the middle of the view. +const Person PLAYER{7, 5}; + + +struct CompareInput{ + std::string name; + ImageRGB32 (*frame)(); +}; +struct CompareExpectation{ + bool same_place; +}; +struct CompareCase{ + CompareInput input; + CompareExpectation expectation; +}; + +// The reference: Cerulean Center's counter, the nurse behind it, a +// visitor by the door. +ImageRGB32 counter_reference(){ + return screen(CENTER, 10, 8, {PLAYER, {7, 3}, {11, 8}}, 1); +} + +class Test_StartFrameCompare : public UnitTest{ +public: + explicit Test_StartFrameCompare(CompareCase test_case) + : UnitTest("PokemonFRLG::AutoStoryStartFrames - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const StartFrameDifference difference = compare_start_frames(counter_reference(), m_case.input.frame()); + if (same_start_place(difference) != m_case.expectation.same_place){ + return std::format( + "expected {}, got {}", + m_case.expectation.same_place ? "the same place" : "another place", to_string(difference) + ); + } + return true; + } + +private: + CompareCase m_case; +}; + +const CompareCase COMPARE_CASES[] = { + { + .input = {"the same screen, another capture", []{ return screen(CENTER, 10, 8, {PLAYER, {7, 3}, {11, 8}}, 2); }}, + .expectation = {true}, + }, + { + .input = {"the visitor walked off", []{ return screen(CENTER, 10, 8, {PLAYER, {7, 3}}, 3); }}, + .expectation = {true}, + }, + { + .input = {"three people moved", []{ return screen(CENTER, 10, 8, {PLAYER, {8, 3}, {2, 7}, {12, 2}, {4, 8}}, 4); }}, + .expectation = {true}, + }, + { + .input = {"one step off the counter", []{ return screen(CENTER, 10, 9, {PLAYER, {7, 2}, {11, 7}}, 5); }}, + .expectation = {false}, + }, + { + .input = {"outside the Center's door", []{ return screen(CITY, 12, 6, {PLAYER}, 6); }}, + .expectation = {false}, + }, + { + .input = {"another map", []{ return screen(ROUTE, 3, 14, {PLAYER, {3, 6}}, 7); }}, + .expectation = {false}, + }, + { + .input = {"a black fade", []{ + ImageRGB32 black(CAPTURE_WIDTH, CAPTURE_HEIGHT); + black.fill(0xff000000); + return black; + }}, + .expectation = {false}, + }, +}; + + +// read_start_frames() on a run of frames. +struct ReadInput{ + std::string name; + bool has_reference; + // The screens, one per frame read; an empty one is no video. + std::vector frames; +}; +struct ReadExpectation{ + StartFound found; + size_t frames_read; +}; +struct ReadCase{ + ReadInput input; + ReadExpectation expectation; +}; + +ImageRGB32 no_video(){ + return ImageRGB32(); +} +ImageRGB32 black_fade(){ + ImageRGB32 black(CAPTURE_WIDTH, CAPTURE_HEIGHT); + black.fill(0xff000000); + return black; +} +ImageRGB32 at_counter(){ + return screen(CENTER, 10, 8, {PLAYER, {7, 3}}, 8); +} +ImageRGB32 outside_door(){ + return screen(CITY, 12, 6, {PLAYER}, 9); +} + +std::string to_string(StartFound found){ + switch (found){ + case StartFound::NOT_READ: + return "NOT_READ"; + case StartFound::AT_START: + return "AT_START"; + case StartFound::ELSEWHERE: + return "ELSEWHERE"; + } + return "?"; +} + +class Test_StartFrameRead : public UnitTest{ +public: + explicit Test_StartFrameRead(ReadCase test_case) + : UnitTest("PokemonFRLG::AutoStoryStartFrames - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + std::optional reference; + if (m_case.input.has_reference){ + reference = start_frame(counter_reference()); + } + size_t read = 0; + const StartRead got = read_start_frames(reference, [&]{ + return m_case.input.frames[std::min(read++, m_case.input.frames.size() - 1)](); + }, 3); + if (got.found != m_case.expectation.found || read != m_case.expectation.frames_read){ + return std::format( + "expected {} after {} frames, got {} after {}: {}", + to_string(m_case.expectation.found), m_case.expectation.frames_read, to_string(got.found), read, got.detail + ); + } + return true; + } + +private: + ReadCase m_case; +}; + +const ReadCase READ_CASES[] = { + { + .input = {"no frame kept: not read", false, {at_counter}}, + .expectation = {StartFound::NOT_READ, 0}, + }, + { + .input = {"no video: not read", true, {no_video}}, + .expectation = {StartFound::NOT_READ, 1}, + }, + { + .input = {"the counter: at the start", true, {at_counter}}, + .expectation = {StartFound::AT_START, 1}, + }, + { + .input = {"a fade, then the counter: at the start", true, {black_fade, at_counter}}, + .expectation = {StartFound::AT_START, 2}, + }, + { + .input = {"outside the door three times: elsewhere", true, {outside_door}}, + .expectation = {StartFound::ELSEWHERE, 3}, + }, +}; + + +// console B, FRLG 00.27, 2026-11-09: the save stood outside Cerulean +// Center's door, not at the counter where 00.27 starts, and the run walked +// off. A checkpoint of one walk with the console's start check on frames +// (add_start_check(), as build_checkpoint() adds it): the walk runs only +// when the screen after the save loads shows the kept frame's place, or +// when no frame is kept. +struct StartCheckInput{ + std::string name; + bool has_reference; + ImageRGB32 (*screen)(); +}; +struct StartCheckExpectation{ + bool walked; + // The start check's log line starts with this. + std::string logged; +}; +struct StartCheckCase{ + StartCheckInput input; + StartCheckExpectation expectation; +}; + +class Test_StartFrameCheck : public UnitTest{ +public: + explicit Test_StartFrameCheck(StartCheckCase test_case) + : UnitTest("PokemonFRLG::AutoStoryStartFrames - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + size_t walks = 0; + std::vector lines; + Pokemon::Checkpoint checkpoint = one_walk(walks); + add_start_check( + checkpoint, to_pose(StoryPose{"CeruleanCity_PokemonCenter_1F", TilePos{7, 4}, Direction::NORTH}), + [this]{ return read_start_frames(reference(), m_case.input.screen, 3); }, + [&lines](const std::string& line){ lines.push_back(line); } + ); + Pokemon::RunState state; + Pokemon::EventLogger log = [](const std::string&){}; + const Pokemon::CheckpointReport report = Pokemon::run_checkpoint(state, checkpoint, log); + const bool stopped = !report.completed && report.failure.failure == "start_failed"; + const bool logged = lines.size() == 1 && lines[0].starts_with(m_case.expectation.logged); + if ((m_case.expectation.walked ? !report.completed || walks != 1 : !stopped || walks != 0) || !logged){ + return std::format( + "expected {}, \"{}\" logged; got {} walk(s), {}: {}", + m_case.expectation.walked ? "the walk" : "a stop before it", m_case.expectation.logged, + walks, Pokemon::to_string(report.failure), lines.empty() ? "nothing logged" : lines[0] + ); + } + return true; + } + +private: + static Pokemon::Checkpoint one_walk(size_t& walks){ + Pokemon::Checkpoint checkpoint; + checkpoint.id = "00.27"; + Pokemon::Event walk; + walk.name = "to_the_door"; + walk.act = [&walks](Pokemon::RunState&){ + walks++; + return Pokemon::outcome_ok(); + }; + checkpoint.events.push_back(std::move(walk)); + return checkpoint; + } + std::optional reference() const{ + if (!m_case.input.has_reference){ + return std::nullopt; + } + return start_frame(counter_reference()); + } + + StartCheckCase m_case; +}; + +const StartCheckCase START_CHECK_CASES[] = { + { + .input = {"a save outside the door stops before any step", true, outside_door}, + .expectation = {false, "start pose mismatch: "}, + }, + { + .input = {"a save at the counter walks", true, at_counter}, + .expectation = {true, "start pose matches: "}, + }, + { + .input = {"no frame kept walks, as before", false, outside_door}, + .expectation = {true, "start pose not read: no start frame kept"}, + }, +}; + + +// The store, given two frames for 00.28 (outside the door, then the +// counter): what it finds for 00.28 and 00.27. +struct StoreInput{ + std::string name; + // A folder to keep them in; none for the simulation's store. + bool has_folder; +}; +struct StoreExpectation{ + // 00.28's frame is found, and is the last one kept (the counter). + bool finds_last; +}; +struct StoreCase{ + StoreInput input; + StoreExpectation expectation; +}; + +class Test_StartFrameStore : public UnitTest{ +public: + explicit Test_StartFrameStore(StoreCase test_case) + : UnitTest("PokemonFRLG::AutoStoryStartFrames - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + if (!m_case.input.has_folder){ + return check(StartFrameStore()); + } + const std::string folder = Filesystem::unique_temp_path(USER_FILE_PATH() + "AutoStoryStartFrames").string() + "/"; + const UnitTestResult result = check(StartFrameStore(folder)); + Filesystem::remove_all(folder); + return result; + } + +private: + UnitTestResult check(const StartFrameStore& store) const{ + if (store.load("00.28")){ + return "expected no frame before one is kept"; + } + const bool kept = store.save("00.28", start_frame(outside_door()), "test") + && store.save("00.28", start_frame(at_counter()), "test"); + const std::optional found = store.load("00.28"); + const bool finds_last = kept && found && found->width() == 240 && found->height() == 160 + && same_start_place(compare_start_frames(*found, at_counter())); + if (finds_last != m_case.expectation.finds_last || store.load("00.27")){ + return std::format( + "expected 00.28's last frame {}found and none for 00.27; kept: {}, found: {}", + m_case.expectation.finds_last ? "" : "not ", kept, found.has_value() + ); + } + return true; + } + + StoreCase m_case; +}; + +const StoreCase STORE_CASES[] = { + { + .input = {"the store keeps the last frame per checkpoint", true}, + .expectation = {true}, + }, + { + .input = {"a store with no folder keeps nothing", false}, + .expectation = {false}, + }, +}; + +} // namespace + + +void add_tests_AutoStoryStartFrames(UnitTestDatabase& database){ + for (const auto& item : COMPARE_CASES){ + database.add(item); + } + for (const auto& item : READ_CASES){ + database.add(item); + } + for (const auto& item : START_CHECK_CASES){ + database.add(item); + } + for (const auto& item : STORE_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.cpp new file mode 100644 index 0000000000..dd9767b704 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.cpp @@ -0,0 +1,117 @@ +/* AutoStory Step Interrupts + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Color.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryStepInterrupts.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using Pokemon::InterruptKind; +using Pokemon::InterruptPose; +using Pokemon::StoryStepKind; +using namespace std::chrono_literals; + +// A warp's scene is a fade and the map's name: well within this. +constexpr Milliseconds WARP_SCENE_TIMEOUT = 60000ms; + + +bool presses_through_text(StoryStepKind kind){ + switch (kind){ + case StoryStepKind::MASH: + case StoryStepKind::ANSWER: + case StoryStepKind::BATTLE: + case StoryStepKind::GAME: + case StoryStepKind::NEW_GAME: + return true; + default: + return false; + } +} + +StepInterruptActions console_interrupt_actions( + ConsoleHandle& console, ProControllerContext& context, + std::function walker +){ + const auto walker_clears = [&console, &context, walker](bool wild){ + return [&console, &context, walker, wild](const Pokemon::InterruptVerdict&, Pokemon::RunState&){ + const OverworldInterruptSet set = walker(); + (wild ? set.wild : set.other).front()->clear(console, context); + return Pokemon::outcome_ok(); + }; + }; + return StepInterruptActions{ + .wild = walker_clears(true), + .trainer = walker_clears(false), + .dialog = walker_clears(false), + .warp = [&console, &context](const Pokemon::InterruptVerdict&, Pokemon::RunState&){ + mash_until_overworld(console, context, WARP_SCENE_TIMEOUT); + return Pokemon::outcome_ok(); + }, + }; +} + +Pokemon::StoryInterrupts step_interrupts(Pokemon::ScreenLookFunction look, const StepInterruptActions& actions){ + Pokemon::StoryInterrupts out; + out.look = std::move(look); + out.handlers.add(InterruptKind::WILD_ENCOUNTER, {.handle = actions.wild, .pose = InterruptPose::UNCHANGED}); + out.handlers.add(InterruptKind::TRAINER_SIGHT, {.handle = actions.trainer, .pose = InterruptPose::UNCHANGED}); + out.handlers.add(InterruptKind::DIALOG, {.handle = actions.dialog, .pose = InterruptPose::UNCHANGED}); + out.handlers.add(InterruptKind::WARP, {.handle = actions.warp, .pose = InterruptPose::LOST}); + for (StoryStepKind step : {StoryStepKind::MASH, StoryStepKind::ANSWER, StoryStepKind::BATTLE, StoryStepKind::GAME, StoryStepKind::NEW_GAME}){ + out.handlers.starts_on(step, InterruptKind::DIALOG); + } + out.handlers.starts_on(StoryStepKind::BATTLE, InterruptKind::TRAINER_SIGHT); + out.handlers.starts_on(StoryStepKind::BATTLE, InterruptKind::WILD_ENCOUNTER); + for (StoryStepKind step : {StoryStepKind::GAME, StoryStepKind::NEW_GAME}){ + for (InterruptKind kind : {InterruptKind::WILD_ENCOUNTER, InterruptKind::TRAINER_SIGHT, InterruptKind::WARP}){ + out.handlers.starts_on(step, kind); + } + } + return out; +} + + +ConsoleScreenLook::ConsoleScreenLook(ConsoleHandle& console, ProControllerContext& context) + : m_stream(console) + , m_context(context) + , m_eyes(console, m_observer) + , m_watcher(m_eyes) + , m_start(current_time()) +{} + +Pokemon::ScreenLook ConsoleScreenLook::look(bool fresh){ + if (fresh){ + m_watcher.reset(); + m_start = current_time(); + } + wait_until(m_stream, m_context, BETWEEN_STEPS_LOOK, {m_watcher}); + return {.log = m_watcher.log(), .window = {.start = m_start, .end = current_time()}}; +} + + +void InterruptLogGuard::on_interrupt(const Pokemon::StoryStep& step, const Pokemon::InterruptCheck& check){ + const bool cleared = check.outcome.succeeded(); + m_logger.log(std::format( + "Story: {}: before it, {}: {}", step.name, + Pokemon::interrupt_kind_name(check.verdict.kind), cleared ? "cleared" : Pokemon::to_string(check.outcome) + ), cleared ? COLOR_ORANGE : COLOR_RED); +} + +void InterruptLogGuard::on_screen(const Pokemon::StoryStep& step, const Pokemon::ScreenSettle& screen){ + m_logger.log(std::format("[Screen] before {}: {}", step.name, Pokemon::describe(screen))); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.h new file mode 100644 index 0000000000..e9a57f129c --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.h @@ -0,0 +1,123 @@ +/* AutoStory Step Interrupts + * + * From: https://github.com/PokemonAutomation/ + * + * FRLG's interrupts between story steps (Pokemon_StoryInterrupts.h): a + * wild battle is run from, a trainer who saw the player is fought, a + * message is read to its end (and a trainer's battle after it fought), + * and a warp's fade is pressed through, the pose then lost. The console + * (ConsoleScreenLook and console_interrupt_actions()), the simulation + * and the replay bind the same table. + * + * The steps that press through text (MASH, ANSWER, BATTLE, GAME, + * NEW_GAME) start on a message: one showing before them is theirs. A + * BATTLE starts on its trainer's lines, and on its battle already + * showing, which reads as a wild one when the lines were missed. A GAME + * step (a measured script: a capture, the PC, a gift's summary) and + * NEW_GAME (the title screen) start on anything. FRLG's story has no + * TRAIN steps. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryStepInterrupts_H +#define PokemonAutomation_PokemonFRLG_AutoStoryStepInterrupts_H + +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/Time.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "CommonTools/ScreenEvents/ScreenEvents.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeScreenObserver.h" +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" +#include "Pokemon/AutoStory/Pokemon_StoryInterrupts.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h" +#include "PokemonFRLG_AutoStoryScreenEvents.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// What clears each kind of interrupt, as a binding does it. +struct StepInterruptActions{ + Pokemon::InterruptAction wild = {}; + Pokemon::InterruptAction trainer = {}; + Pokemon::InterruptAction dialog = {}; + Pokemon::InterruptAction warp = {}; +}; + +// FRLG's interrupts between steps: `look` judged with the shared knobs, +// `actions` for each kind, and the steps that start on one. The knobs +// are the shared defaults, BDSP's timings: FRLG's flash-to-battle and +// lines-to-battle times are not measured on the console yet. +Pokemon::StoryInterrupts step_interrupts(Pokemon::ScreenLookFunction look, const StepInterruptActions& actions); + +// The console's actions, as the walker clears what stops a leg +// part-way (`walker()`'s interrupts, story_interrupts() in +// PokemonFRLG_AutoStoryBattle.h, built when one is cleared): a wild +// battle is run from, a message read to its end and a trainer's battle +// after it fought. A warp's scene is pressed through. +StepInterruptActions console_interrupt_actions( + ConsoleHandle& console, ProControllerContext& context, + std::function walker +); + +// Whether a step of `kind` presses through any text showing when it +// starts; a step of another kind is stopped by it (a walk, a talk). +bool presses_through_text(Pokemon::StoryStepKind kind); + + +// How long the console looks at the screen before a step: the walker's +// wait for a message box (its StoryMessage interrupt's detection delay). +// Not measured as a look between steps yet. +constexpr Milliseconds BETWEEN_STEPS_LOOK = Milliseconds(400); + +// The console's look between steps: FrlgScreenObserver's events for +// BETWEEN_STEPS_LOOK, everything showing in it judged. +// The Switch's HOME menu comes first (SwitchHomeObserver), so a +// step that starts on it fails instead of pressing buttons on HOME. +class ConsoleScreenLook{ +public: + ConsoleScreenLook(ConsoleHandle& console, ProControllerContext& context); + + Pokemon::ScreenLook look(bool fresh); + +private: + VideoStream& m_stream; + ProControllerContext& m_context; + FrlgScreenObserver m_observer; + SwitchHomeObserver m_eyes; + ScreenEventWatcher m_watcher; + WallClock m_start; +}; + +// The console's guard: a failed step fails it, as before; each interrupt +// found between steps is logged, cleared or not, and how the screen looked +// before every step. +class InterruptLogGuard : public Pokemon::StepGuard{ +public: + explicit InterruptLogGuard(Logger& logger) + : m_logger(logger) + {} + + virtual void on_interrupt(const Pokemon::StoryStep& step, const Pokemon::InterruptCheck& check) override; + virtual void on_screen(const Pokemon::StoryStep& step, const Pokemon::ScreenSettle& screen) override; + +private: + Logger& m_logger; +}; + + +// The binding's table against a scripted screen. +void add_tests_AutoStoryStepInterrupts(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts_Tests.cpp new file mode 100644 index 0000000000..81c8105402 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts_Tests.cpp @@ -0,0 +1,232 @@ +/* AutoStory Step Interrupts Tests + * + * From: https://github.com/PokemonAutomation/ + * + * FRLG's table of interrupts between steps (step_interrupts()) on the + * shared executor, against a scripted screen: what each kind of step is + * stopped by and what it starts on. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonTools/ScreenEvents/ScreenEvents.h" +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" +#include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryStepTable.h" +#include "PokemonFRLG_AutoStoryStepInterrupts.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +using Pokemon::StoryStepKind; + +const WallClock T0 = WallClock() + std::chrono::hours(1); + +// What FrlgScreenObserver reports of each screen (no PLAYER_CAN_MOVE). +const ScreenEvents OVERWORLD{}; +const ScreenEvents BOX{ScreenEvent::DIALOG_BOX}; +const ScreenEvents WHITE{ScreenEvent::FADE_WHITE}; +const ScreenEvents BLACK{ScreenEvent::FADE_BLACK}; +const ScreenEvents BATTLE{ScreenEvent::BATTLE_STARTED}; + +// One frame of the scripted screen: its events, `ms` after T0. +struct Frame{ + int ms; + ScreenEvents events; +}; + +// FRLG's rows bound to a recorder, and its interrupts to a scripted look +// and handlers that note what they cleared, all in `trace`. +class FakeGame{ +public: + explicit FakeGame(std::vector screen) + : m_screen(std::move(screen)) + , m_table(make_story_action_table([this](StoryActionId id){ return recorder(id); })) + , m_executor(m_table, m_guard) + , m_interrupts(step_interrupts([this](bool){ return look(); }, noting())) + { + m_executor.set_interrupts(&m_interrupts); + } + + // `kind`'s step through the table, from a known pose: its outcome. + Pokemon::Outcome run(StoryStepKind kind){ + Pokemon::StoryStep step; + step.kind = kind; + step.name = "synthetic"; + return m_executor.run(step, state); + } + + Pokemon::RunState state{.pose = to_pose(StoryPose{"Route1", TilePos{1, 2}, std::nullopt})}; + std::vector trace; + +private: + // The screen until its last frame, then quiet: a cleared interrupt is + // gone at the next look. + Pokemon::ScreenLook look(){ + Pokemon::ScreenLook out; + int until = 300; + for (const Frame& frame : std::exchange(m_screen, {})){ + out.log.record(frame.events, T0 + Milliseconds(frame.ms)); + until = std::max(until, frame.ms + 300); + } + out.window = {T0, T0 + Milliseconds(until)}; + return out; + } + StepInterruptActions noting(){ + const auto note = [this](std::string_view kind){ + return [this, kind](const Pokemon::InterruptVerdict&, Pokemon::RunState&){ + trace.push_back(std::format("clear {}", kind)); + return Pokemon::outcome_ok(); + }; + }; + return {.wild = note("wild"), .trainer = note("trainer"), .dialog = note("dialog"), .warp = note("warp")}; + } + Pokemon::StoryAction recorder(StoryActionId id){ + return {.act = [this, id](const Pokemon::StoryStep&, Pokemon::RunState&){ + trace.emplace_back(story_action_name(id)); + return Pokemon::outcome_ok(); + }}; + } + + std::vector m_screen; + Pokemon::StepGuard m_guard; + Pokemon::StoryActionTable m_table; + Pokemon::TableExecutor m_executor; + Pokemon::StoryInterrupts m_interrupts; +}; + +// Runs a `kind` step after `screen`; empty if what ran was `expected`. +std::string ran(std::vector screen, StoryStepKind kind, const std::vector& expected){ + FakeGame game(std::move(screen)); + const Pokemon::Outcome outcome = game.run(kind); + if (outcome.succeeded() && game.trace == expected){ + return ""; + } + std::string got = Pokemon::to_string(outcome) + ":"; + for (const std::string& item : game.trace){ + got += " " + item; + } + return std::string(Pokemon::story_step_kind_name(kind)) + ": got " + got; +} + +UnitTestResult test_message(){ + const std::vector message{{0, OVERWORLD}, {100, BOX}}; + for (const std::string& error : { + ran(message, StoryStepKind::ROUTE, {"clear dialog", "route"}), + ran(message, StoryStepKind::TALK, {"clear dialog", "talk"}), + ran(message, StoryStepKind::MASH, {"mash"}), + ran(message, StoryStepKind::ANSWER, {"answer"}), + ran(message, StoryStepKind::BATTLE, {"battle"}), + }){ + if (!error.empty()){ + return error; + } + } + return true; +} + +UnitTestResult test_battle(){ + const std::vector wild{{0, OVERWORLD}, {100, WHITE}, {400, OVERWORLD}, {1500, BATTLE}}; + const std::vector trainer{{0, OVERWORLD}, {100, BOX}, {2000, BLACK}, {2500, BATTLE}}; + for (const std::string& error : { + ran(wild, StoryStepKind::ROUTE, {"clear wild", "route"}), + ran(wild, StoryStepKind::BATTLE, {"battle"}), + ran(trainer, StoryStepKind::LEGS, {"clear trainer", "legs"}), + ran(trainer, StoryStepKind::BATTLE, {"battle"}), + ran(trainer, StoryStepKind::GAME, {"game"}), + }){ + if (!error.empty()){ + return error; + } + } + return true; +} + +UnitTestResult test_warp(){ + const std::vector warp{{0, OVERWORLD}, {100, BLACK}, {600, OVERWORLD}, {9000, OVERWORLD}}; + FakeGame game(warp); + const Pokemon::Outcome outcome = game.run(StoryStepKind::STEP); + if (!outcome.succeeded() || game.trace != std::vector{"clear warp", "step"}){ + return "Expected the warp cleared before the step, got " + Pokemon::to_string(outcome); + } + if (game.state.pose.where != nullptr){ + return "Expected the pose lost after a warp, got " + Pokemon::to_string(game.state.pose); + } + const std::string error = ran(warp, StoryStepKind::GAME, {"game"}); + if (!error.empty()){ + return error; + } + return true; +} + + +struct StepInterruptsInput{ + std::string name; + UnitTestResult (*body)(); +}; +struct StepInterruptsExpectation{ + std::string_view description; +}; +struct StepInterruptsTestCase{ + StepInterruptsInput input; + StepInterruptsExpectation expectation; +}; + +class Test_StepInterrupts : public UnitTest{ +public: + explicit Test_StepInterrupts(StepInterruptsTestCase scenario) + : UnitTest("PokemonFRLG::AutoStoryStepInterrupts - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_scenario.input.body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + StepInterruptsTestCase m_scenario; +}; + +const StepInterruptsTestCase STEP_INTERRUPTS_CASES[] = { + { + .input = {.name = "a message before a step", .body = test_message}, + .expectation = {.description = "read before a walk or a talk; the step's own before one that presses through text"}, + }, + { + .input = {.name = "a battle before a step", .body = test_battle}, + .expectation = {.description = "run from or fought before a walk; a BATTLE's own, its lines missed or not"}, + }, + { + .input = {.name = "a warp before a step", .body = test_warp}, + .expectation = {.description = "pressed through and the pose lost; a GAME's own"}, + }, +}; + +} // namespace + + +void add_tests_AutoStoryStepInterrupts(UnitTestDatabase& database){ + for (const auto& scenario : STEP_INTERRUPTS_CASES){ + database.add(scenario); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp new file mode 100644 index 0000000000..b628fbcb5b --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp @@ -0,0 +1,99 @@ +/* AutoStory Step Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "PokemonFRLG_AutoStoryStepTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using Pokemon::StoryStepKind; + + +std::string_view story_action_name(StoryActionId id){ + switch (id){ + case StoryActionId::NEW_GAME: return "new_game"; + case StoryActionId::OPTIONS: return "options"; + case StoryActionId::ROUTE: return "route"; + case StoryActionId::LEGS: return "legs"; + case StoryActionId::STEP: return "step"; + case StoryActionId::TALK: return "talk"; + case StoryActionId::ANSWER: return "answer"; + case StoryActionId::MASH: return "mash"; + case StoryActionId::BATTLE: return "battle"; + case StoryActionId::HEAL: return "heal"; + case StoryActionId::SHOP: return "shop"; + case StoryActionId::READY: return "ready"; + case StoryActionId::GAME: return "game"; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown story action."); +} + +const std::vector& story_action_rows(){ + static const std::vector ROWS{ + {StoryStepKind::NEW_GAME, "", StoryActionId::NEW_GAME}, + {StoryStepKind::OPTIONS, "", StoryActionId::OPTIONS}, + {StoryStepKind::ROUTE, "", StoryActionId::ROUTE}, + {StoryStepKind::LEGS, "", StoryActionId::LEGS}, + {StoryStepKind::STEP, "", StoryActionId::STEP}, + {StoryStepKind::TALK, "", StoryActionId::TALK}, + {StoryStepKind::ANSWER, "", StoryActionId::ANSWER}, + {StoryStepKind::MASH, "", StoryActionId::MASH}, + {StoryStepKind::BATTLE, "", StoryActionId::BATTLE}, + {StoryStepKind::HEAL, "", StoryActionId::HEAL}, + {StoryStepKind::SHOP, "", StoryActionId::SHOP}, + {StoryStepKind::READY, "", StoryActionId::READY}, + {StoryStepKind::GAME, "", StoryActionId::GAME}, + }; + return ROWS; +} + +std::span story_action_specs(){ + static const std::vector SPECS = []{ + const std::span builtin = Pokemon::builtin_story_actions(); + std::vector specs(builtin.begin(), builtin.end()); + // A trainer battle's plan names the trainer and its party. + for (Pokemon::StoryActionSpec& spec : specs){ + if (spec.kind != StoryStepKind::BATTLE){ + continue; + } + spec.args.push_back(Pokemon::StoryArgSpec{ + .key = "trainer", .type = Pokemon::StoryArgType::WORD, .required = false, .fallback = std::string(), + .why = "pret's constant for the trainer (\"TRAINER_LEADER_BROCK\"); sets the battle's risk", + }); + spec.args.push_back(Pokemon::StoryArgSpec{ + .key = "foes", .type = Pokemon::StoryArgType::WORDS, .required = false, .fallback = std::vector(), + .why = "the trainer's party in order; attacks are chosen against the one out", + }); + } + for (StoryStepKind kind : {StoryStepKind::ROUTE, StoryStepKind::LEGS}){ + Pokemon::StoryActionSpec run = *Pokemon::find_story_action(builtin, kind, ""); + run.name = "run"; + specs.push_back(std::move(run)); + } + return specs; + }(); + return SPECS; +} + +Pokemon::StoryActionTable make_story_action_table(const StoryActionBinding& bind){ + Pokemon::StoryActionTable table; + for (const StoryActionRow& row : story_action_rows()){ + Pokemon::StoryAction action = bind(row.id); + if (const Pokemon::StoryActionSpec* spec = Pokemon::find_story_action(story_action_specs(), row.kind, row.variant)){ + action.args = spec->args; + } + table.add(row.kind, row.variant, std::move(action)); + } + return table; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.h new file mode 100644 index 0000000000..2a7918060f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.h @@ -0,0 +1,82 @@ +/* AutoStory Step Table + * + * From: https://github.com/PokemonAutomation/ + * + * FRLG's story steps as rows of the shared action table + * (Pokemon/AutoStory/Pokemon_StoryActions.h): each row names what does + * a kind of step, or one variant of it. The console (StoryExecutor) binds + * each name to its console action; the tests bind them to a recorder, so + * the rows are checked without a console. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryStepTable_H +#define PokemonAutomation_PokemonFRLG_AutoStoryStepTable_H + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// What does a step: one of FRLG's story actions. +enum class StoryActionId{ + NEW_GAME, + OPTIONS, + ROUTE, + LEGS, + STEP, + TALK, + ANSWER, + MASH, + BATTLE, + HEAL, + SHOP, + READY, + // A GAME step: one only FRLG has. + GAME, +}; +// "route", "game": the action's name in logs and test traces. +std::string_view story_action_name(StoryActionId id); + +// A row of FRLG's table: the action for steps of `kind` whose variant is +// named `variant`, or for every other step of `kind` if it is empty. +struct StoryActionRow{ + Pokemon::StoryStepKind kind; + std::string variant; + StoryActionId id; +}; +// Every row. TRAIN and SAVE have none: FRLG's story doesn't use them. +const std::vector& story_action_rows(); + +// The actions FRLG's steps name, with the args each takes: the built-in +// ones (Pokemon_BuiltinStoryActions.h), then a ROUTE and a LEGS named +// "run" (RUN_VARIANT), which take the same args and run with B held. +// A story file is read against these. +std::span story_action_specs(); + +// How one binding (the console, a test) does each action. +using StoryActionBinding = std::function; +// The rows as a table, each with `bind`'s action for its id and its +// spec's args. +Pokemon::StoryActionTable make_story_action_table(const StoryActionBinding& bind); + + +// The rows against the dispatch they replaced, and every checkpoint linted +// against them. +void add_tests_AutoStoryStepTable(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable_Tests.cpp new file mode 100644 index 0000000000..fbc9596dab --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable_Tests.cpp @@ -0,0 +1,236 @@ +/* AutoStory Step Table Tests + * + * From: https://github.com/PokemonAutomation/ + * + * FRLG's rows run with a recorder for each action: every step of the + * story, and every kind with each variant the rows name, must reach the + * action the per-kind dispatch they replaced reached. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" +#include "PokemonFRLG_AutoStoryStepInterrupts.h" +#include "PokemonFRLG_AutoStoryStepTable.h" +#include "PokemonFRLG_AutoStoryTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +using Pokemon::StoryStepKind; + +const StoryStepKind ALL_KINDS[] = { + StoryStepKind::NEW_GAME, StoryStepKind::OPTIONS, StoryStepKind::ROUTE, StoryStepKind::LEGS, + StoryStepKind::STEP, StoryStepKind::TALK, StoryStepKind::ANSWER, StoryStepKind::MASH, + StoryStepKind::BATTLE, StoryStepKind::TRAIN, StoryStepKind::HEAL, StoryStepKind::SHOP, + StoryStepKind::SAVE, StoryStepKind::READY, StoryStepKind::GAME, +}; + +// The action StoryExecutor ran for `step` before the table: the shared +// per-kind dispatch (StoryStepExecutor::run()) into the kinds it +// overrode. Nothing for the kinds it left to the shared executor. +std::optional old_dispatch(const StoryStep& step){ + switch (step.kind){ + case StoryStepKind::NEW_GAME: return StoryActionId::NEW_GAME; + case StoryStepKind::OPTIONS: return StoryActionId::OPTIONS; + case StoryStepKind::ROUTE: return StoryActionId::ROUTE; + case StoryStepKind::LEGS: return StoryActionId::LEGS; + case StoryStepKind::STEP: return StoryActionId::STEP; + case StoryStepKind::TALK: return StoryActionId::TALK; + case StoryStepKind::ANSWER: return StoryActionId::ANSWER; + case StoryStepKind::MASH: return StoryActionId::MASH; + case StoryStepKind::BATTLE: return StoryActionId::BATTLE; + case StoryStepKind::HEAL: return StoryActionId::HEAL; + case StoryStepKind::SHOP: return StoryActionId::SHOP; + case StoryStepKind::READY: return StoryActionId::READY; + case StoryStepKind::GAME: return StoryActionId::GAME; + case StoryStepKind::TRAIN: + case StoryStepKind::SAVE: + return std::nullopt; + } + return std::nullopt; +} + +// FRLG's rows bound to a recorder: each action adds its name to `trace`. +class FakeGame{ +public: + FakeGame() + : m_table(make_story_action_table([this](StoryActionId id){ return recorder(id); })) + , m_executor(m_table, m_guard) + {} + + const Pokemon::StoryActionTable& table() const{ + return m_table; + } + // `step` through the table: the outcome, and the actions it ran. + Pokemon::Outcome run(const StoryStep& step, std::vector& trace){ + m_trace = &trace; + Pokemon::RunState state; + return m_executor.run(step, state); + } + +private: + Pokemon::StoryAction recorder(StoryActionId id){ + return {.act = [this, id](const StoryStep&, Pokemon::RunState&){ + m_trace->emplace_back(story_action_name(id)); + return Pokemon::outcome_ok(); + }}; + } + + std::vector* m_trace = nullptr; + Pokemon::StepGuard m_guard; + Pokemon::StoryActionTable m_table; + Pokemon::TableExecutor m_executor; +}; + +// Why `step` didn't run what old_dispatch() did, or empty. +std::string parity_error(FakeGame& game, const StoryStep& step){ + std::vector trace; + const Pokemon::Outcome outcome = game.run(step, trace); + const std::optional expected = old_dispatch(step); + const std::string label = std::format("{} '{}' ({})", Pokemon::story_step_kind_name(step.kind), step.action, step.name); + if (!expected){ + if (!trace.empty() || outcome.failure != "unsupported_step"){ + return label + ": expected unsupported, ran " + (trace.empty() ? outcome.failure : trace[0]); + } + return ""; + } + if (trace != std::vector{std::string(story_action_name(*expected))} || !outcome.succeeded()){ + return std::format("{}: expected {}, ran {} action(s){}", label, story_action_name(*expected), + trace.size(), trace.empty() ? "" : ", first " + trace[0]); + } + return ""; +} + +// Every kind, with no variant, an unknown one, and each one a row names. +std::vector every_kind_and_variant(){ + std::vector variants{"", "no_such_variant", "no_such_variant key=1"}; + for (const StoryActionRow& row : story_action_rows()){ + if (!row.variant.empty()){ + variants.push_back(row.variant); + } + } + std::vector steps; + for (StoryStepKind kind : ALL_KINDS){ + for (const std::string& variant : variants){ + StoryStep step; + step.kind = kind; + step.name = "synthetic"; + step.action = variant; + steps.push_back(std::move(step)); + } + } + return steps; +} + +UnitTestResult test_parity_every_kind(){ + FakeGame game; + for (const StoryStep& step : every_kind_and_variant()){ + const std::string error = parity_error(game, step); + if (!error.empty()){ + return error; + } + } + return true; +} + +UnitTestResult test_parity_story_steps(){ + FakeGame game; + for (const StoryCheckpoint& data : story_checkpoints()){ + for (const StoryStep& step : data.steps){ + const std::string error = parity_error(game, step); + if (!error.empty()){ + return data.id + " " + error; + } + } + } + return true; +} + +UnitTestResult test_every_step_bound(){ + FakeGame game; + std::string problems; + for (const StoryCheckpoint& data : story_checkpoints()){ + for (const std::string& problem : Pokemon::lint_story_checkpoint(data, game.table())){ + problems += "\n" + problem; + } + } + if (!problems.empty()){ + return "Expected every step to have an action:" + problems; + } + return true; +} + + +struct StepTableInput{ + std::string name; + UnitTestResult (*body)(); +}; + +struct StepTableExpectation{ + std::string_view description; +}; + +struct StepTableTestCase{ + StepTableInput input; + StepTableExpectation expectation; +}; + +class Test_StepTable : public UnitTest{ +public: + explicit Test_StepTable(StepTableTestCase scenario) + : UnitTest("PokemonFRLG::AutoStoryStepTable - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_scenario.input.body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + StepTableTestCase m_scenario; +}; + +const StepTableTestCase STEP_TABLE_CASES[] = { + { + .input = {.name = "every kind and variant runs what the per-kind dispatch ran", .body = test_parity_every_kind}, + .expectation = {.description = "table rows match the replaced dispatch for each kind and variant"}, + }, + { + .input = {.name = "every story step runs what the per-kind dispatch ran", .body = test_parity_story_steps}, + .expectation = {.description = "table rows match the replaced dispatch for each authored step"}, + }, + { + .input = {.name = "every checkpoint's steps have an action", .body = test_every_step_bound}, + .expectation = {.description = "lint_story_checkpoint finds no unbound step"}, + }, +}; + +} // namespace + + +void add_tests_AutoStoryStepTable(UnitTestDatabase& database){ + for (const auto& scenario : STEP_TABLE_CASES){ + database.add(scenario); + } + add_tests_AutoStoryStepInterrupts(database); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp new file mode 100644 index 0000000000..8c9b714717 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp @@ -0,0 +1,164 @@ +/* AutoStory Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson.h" +#include "PokemonFRLG_AutoStoryParty.h" +#include "PokemonFRLG_AutoStoryStepTable.h" +#include "PokemonFRLG_AutoStoryTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +// The wire names of the START menus. +StartMenu read_start_menu(std::string_view name, std::string_view source){ + if (name == "before_pokemon"){ + return StartMenu::BEFORE_POKEMON; + } + if (name == "before_pokedex"){ + return StartMenu::BEFORE_POKEDEX; + } + if (name == "full"){ + return StartMenu::FULL; + } + throw ParseException(std::format("{}: unknown START menu {}", source, name)); +} + +// `object`'s fields, each of which must be one of `keys`. +void only_fields(const JsonObject& object, std::initializer_list keys, std::string_view 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 execution field {}", source, key)); + } + } +} + +int read_count(const JsonObject& object, const std::string& key, std::string_view source){ + const JsonValue* value = object.get_value(key); + if (value == nullptr){ + return 0; + } + const int64_t count = value->to_integer_throw(std::string(source)); + if (count < 0 || count > 999){ + throw ParseException(std::format("{}: {} out of range", source, key)); + } + return (int)count; +} + +Supplies read_supplies(const JsonObject& execution, std::string_view source){ + Supplies supplies; + if (const JsonObject* items = execution.get_object("supplies")){ + only_fields(*items, {"potions", "antidotes", "parlyz_heals"}, source); + supplies.potions = read_count(*items, "potions", source); + supplies.antidotes = read_count(*items, "antidotes", source); + supplies.parlyz_heals = read_count(*items, "parlyz_heals", source); + } + if (const std::string* lead = execution.get_string("lead")){ + if (*lead != "after_brock"){ + throw ParseException(std::format("{}: unknown lead {}", source, *lead)); + } + supplies.lead = story_lead_after_brock(); + }else if (execution.get_value("lead") != nullptr){ + throw ParseException(std::format("{}: lead must be a string", source)); + } + return supplies; +} + +// The keys of the notes: "checkpoint" or a step's id, each a list of lines. +std::set read_note_keys(const JsonObject& execution, std::string_view source){ + std::set keys; + const JsonValue* notes = execution.get_value("notes"); + if (notes == nullptr){ + return keys; + } + for (const auto& [key, lines] : notes->to_object_throw(std::string(source))){ + for (const JsonValue& line : lines.to_array_throw(std::string(source))){ + line.to_string_throw(std::string(source)); + } + keys.insert(key); + } + return keys; +} + +// The file without its "metadata", which the shared reader doesn't take +// (yet): {"phase": testing, verification or reproduction}, how far the +// checkpoint is trusted to save (the engine's save policy reads it). +JsonValue without_metadata(const JsonValue& value, std::string_view source){ + JsonObject stripped; + for (const auto& [key, field] : value.to_object_throw(std::string(source))){ + if (key != "metadata"){ + stripped[key] = field.clone(); + continue; + } + const JsonObject& metadata = field.to_object_throw(std::string(source)); + for (const auto& [metadata_key, unused] : metadata){ + if (metadata_key != "phase"){ + throw ParseException(std::format("{}: unsupported metadata field {}", source, metadata_key)); + } + } + const std::string& phase = metadata.get_string_throw("phase", std::string(source)); + if (phase != "testing" && phase != "verification" && phase != "reproduction"){ + throw ParseException(std::format("{}: unknown phase {}", source, phase)); + } + } + return JsonValue(std::move(stripped)); +} + +} // namespace + + +StoryCheckpoint read_story_checkpoint_file(const JsonValue& value, std::string_view source){ + StoryCheckpoint checkpoint; + std::set note_keys; + const Pokemon::ExecutionReader read_execution = [&](const JsonObject& execution, std::string_view where){ + only_fields(execution, {"menu", "supplies", "lead", "notes"}, where); + checkpoint.menu = read_start_menu(execution.get_string_throw("menu", std::string(where)), where); + checkpoint.supplies = read_supplies(execution, where); + note_keys = read_note_keys(execution, where); + }; + static_cast(checkpoint) = Pokemon::read_authored_checkpoint( + without_metadata(value, source), "frlg", source, read_execution, story_action_specs() + ); + for (const std::string& key : note_keys){ + bool found = key == "checkpoint"; + for (const StoryStep& step : checkpoint.steps){ + found |= step.name == key; + } + if (!found){ + throw ParseException(std::format("{}: notes for unknown step {}", source, key)); + } + } + return checkpoint; +} + +const std::vector& story_checkpoints(){ + static const std::vector checkpoints = []{ + std::vector result; + for (const auto& [name, text] : autostory_checkpoint_json()){ + result.push_back(read_story_checkpoint_file(parse_json(text), name)); + } + return result; + }(); + return checkpoints; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h new file mode 100644 index 0000000000..62cbb37513 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h @@ -0,0 +1,69 @@ +/* AutoStory Table + * + * From: https://github.com/PokemonAutomation/ + * + * FireRed from a new game to the Boulder Badge and the Running Shoes, as + * story checkpoints 00.01 to 00.10, each saved at its end. After 00.10 + * every route and leg runs. Taken from a by-hand run on + * console B (2026-11-01) and the pokefirered map scripts. + * + * Each checkpoint is an authored JSON file in StoryData/ + * (frlg-.plan.json, format pokesim-authored-checkpoint/1): the shared + * checkpoint, its steps each an action with args, read against FRLG's + * actions (story_action_specs()), and FRLG's execution object: + * + * "menu" before_pokemon, before_pokedex or full: the START menu + * at its end (StoryCheckpoint::menu); + * "supplies" optional: {"potions", "antidotes", "parlyz_heals"} at + * its start, for a run that loads its save; + * "lead" optional: "after_brock", the starter as the story left + * it by Brock (story_lead_after_brock()); + * "notes" optional: {"checkpoint" or a step's id: [lines]}, the + * reasons behind a step that a reader of the file needs. + * The program doesn't read them. + * + * Beside "execution", "metadata": {"phase": testing, verification or + * reproduction}: how far the checkpoint is trusted. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryTable_H +#define PokemonAutomation_PokemonFRLG_AutoStoryTable_H + +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonFRLG_AutoStoryEvents.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// (name, JSON text) of each file in StoryData/, sorted by name. +// Generated at build time (SerialPrograms/cmake/EmbedTextFiles.cmake). +const std::vector>& autostory_checkpoint_json(); + +// The checkpoint of an authored FRLG file. Throws ParseException when +// the file is malformed, names an action FRLG doesn't have, gives an +// action args it doesn't take, or has notes for a step it doesn't have. +StoryCheckpoint read_story_checkpoint_file(const JsonValue& value, std::string_view source); + +// Checkpoints 00.01 to 00.10, in order: every file in StoryData/. +const std::vector& story_checkpoints(); + + +// Registers AutoStory table validation unit tests. +void add_tests_AutoStory(UnitTestDatabase& database); +// The table run end to end against a fake game (PokemonFRLG_AutoStorySimulation_Tests.cpp). +void add_tests_AutoStorySimulation(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp new file mode 100644 index 0000000000..5768edbd81 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -0,0 +1,681 @@ +/* AutoStory Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Plans every route of the story table on the map files, from where the + * table says the player stands, and checks that each checkpoint starts + * where the one before it ends. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_OptionMenuReader.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" +#include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryMoveData.h" +#include "PokemonFRLG_AutoStoryStepTable.h" +#include "PokemonFRLG_AutoStoryTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +struct AutoStoryInput{ + std::string name; + UnitTestResult (*body)(); +}; + +struct AutoStoryExpectation{ + std::string_view description; +}; + +struct AutoStoryTestCase{ + AutoStoryInput input; + AutoStoryExpectation expectation; +}; + +class Test_AutoStory : public UnitTest{ +public: + explicit Test_AutoStory(AutoStoryTestCase scenario) + : UnitTest("PokemonFRLG::AutoStory - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_scenario.input.body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + AutoStoryTestCase m_scenario; +}; + +const MapData* find_map_named(const std::string& name){ + for (const MapData& map : story_maps()){ + if (map.name == name){ + return ↦ + } + } + return nullptr; +} + +std::string describe(const std::vector& route){ + std::string text; + for (const RouteStep& step : route){ + text += "\n " + to_string(step); + } + return text; +} + +std::string describe(const StoryPose& pose){ + return to_string(MapPosition{pose.map, pose.tile}) + + (pose.facing ? std::string(" facing ") + direction_name(*pose.facing) : ""); +} + +// A table pose as a StoryPose; FRLG's table has one-tile poses only. +StoryPose one_tile(const Pokemon::GridPose& grid_pose){ + const Pokemon::Pose pose = Pokemon::pose_of(grid_pose); + const std::optional ret = story_pose(pose); + if (!ret){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Not a one-tile pose: " + Pokemon::to_string(pose)); + } + return *ret; +} + +Direction reverse(Direction direction){ + switch (direction){ + case Direction::NORTH: + return Direction::SOUTH; + case Direction::EAST: + return Direction::WEST; + case Direction::SOUTH: + return Direction::NORTH; + case Direction::WEST: + return Direction::EAST; + } + return direction; +} + +// The tiles a route's walking legs pass over on `map`. +std::vector tiles_walked_on(const std::vector& route, const std::string& map){ + std::vector tiles; + for (const RouteStep& step : route){ + if (step.action != RouteAction::WALK || step.end.map != map){ + continue; + } + TilePos tile = step.end.point; + for (int c = 0; c < step.tiles; c++){ + tiles.push_back(tile); + tile = tile.next(reverse(step.direction)); + } + } + return tiles; +} + +// Steps that must reach Viridian Forest's gate by legs the walker can hold +// again after a battle: each ends on a wall or a warp, or is one step. +bool held_legs_only(const std::string& name){ + return name == "forest_east" || name == "forest_exit" || name == "forest_gate"; +} +UnitTestResult check_held_legs(const std::string& name, const std::vector& route){ + for (const RouteStep& step : route){ + if (step.action == RouteAction::WALK && !step.to_wall && !step.warps && step.tiles != 1){ + return name + ": an open leg, " + to_string(step) + ":" + describe(route); + } + } + return true; +} + +// Walks `step`'s fixed legs from `pose` and moves `pose` to their end. +UnitTestResult check_legs(StoryPose& pose, const StoryStep& step){ + const std::optional> route = fixed_route(story_maps(), MapPosition{pose.map, pose.tile}, Pokemon::story_arg>(step.args, "legs")); + if (!route || route->empty()){ + return step.name + ": the legs can't be walked from " + describe(pose) + "."; + } + if (held_legs_only(step.name)){ + UnitTestResult result = check_held_legs(step.name, *route); + if (result.result != UnitTestResult::PASSED){ + return result; + } + } + pose = StoryPose{route->back().end.map, route->back().end.point, route->back().facing_after}; + return true; +} + +// Plans `step` from `pose` and moves `pose` to its end. +UnitTestResult check_route(StoryPose& pose, const StoryStep& step){ + const MapPosition start{pose.map, pose.tile}; + std::optional facing = pose.facing; + if (!facing){ + const MapData* map = find_map_named(pose.map); + facing = map ? wall_beside(*map, pose.tile) : std::nullopt; + if (!facing){ + return step.name + ": the facing is unknown at " + describe(pose) + " and no wall is beside it."; + } + } + const StoryPose target = one_tile(Pokemon::story_arg(step.args, "target")); + const RouteGoal goal{{target.map, target.tile}, target.facing}; + const std::optional> route = plan_overworld_route(story_maps(), start, goal, default_route_costs(), facing); + if (!route){ + return step.name + ": no route from " + to_string(start) + " to " + to_string(goal.position) + "."; + } + const MapPosition end = follow_overworld_route(story_maps(), start, *route); + if (!(end == goal.position)){ + return step.name + ": the route ends at " + to_string(end) + ":" + describe(*route); + } + if (goal.facing && !route->empty() && route->back().facing_after != *goal.facing){ + return step.name + ": the route doesn't end facing " + direction_name(*goal.facing) + ":" + describe(*route); + } + if (held_legs_only(step.name)){ + UnitTestResult result = check_held_legs(step.name, *route); + if (result.result != UnitTestResult::PASSED){ + return result; + } + } + if (step.name == "below_old_man_trigger"){ + for (const TilePos& tile : tiles_walked_on(*route, "ViridianCity")){ + if (tile == TilePos{20, 8} || tile == TilePos{22, 8}){ + return step.name + ": walks over the old man's trigger " + to_string(tile) + ":" + describe(*route); + } + } + } + pose = StoryPose{target.map, target.tile, route->empty() ? facing : route->back().facing_after}; + return true; +} + +// Follows `checkpoint` from its start; `pose` ends where it leaves the player. +UnitTestResult check_checkpoint(const StoryCheckpoint& checkpoint, StoryPose& pose){ + for (const StoryStep& step : checkpoint.steps){ + if (step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS){ + UnitTestResult result = step.kind == StoryStepKind::ROUTE ? check_route(pose, step) : check_legs(pose, step); + if (result.result != UnitTestResult::PASSED){ + return checkpoint.id + " " + result.message; + } + }else if (step.kind == StoryStepKind::READY){ + // The nurse may be needed: that way must plan too, but the pose + // goes on from where the player stands. + StoryPose nurse_pose = pose; + StoryStep to_nurse = step; + UnitTestResult result = check_route(nurse_pose, to_nurse); + if (result.result != UnitTestResult::PASSED){ + return checkpoint.id + " " + result.message; + } + }else if (step.kind == StoryStepKind::STEP){ + const Direction direction = Pokemon::story_arg(step.args, "direction"); + pose = StoryPose{pose.map, pose.tile.next(direction), direction}; + } + if (step.pose_after){ + pose = one_tile(Pokemon::grid_pose_of(*step.pose_after)); + } + } + return true; +} + +UnitTestResult test_routes_and_chain(){ + const std::vector& checkpoints = story_checkpoints(); + if (checkpoints.size() != 10 || checkpoints[0].start){ + return "Expected 10 checkpoints, the first from a new game."; + } + StoryPose pose; + for (size_t c = 0; c < checkpoints.size(); c++){ + const StoryCheckpoint& checkpoint = checkpoints[c]; + if (c > 0){ + const StoryPose start = one_tile(Pokemon::grid_pose_of(*checkpoint.start)); + const bool same_facing = !start.facing || start.facing == pose.facing; + if (start.map != pose.map || !(start.tile == pose.tile) || !same_facing){ + return checkpoint.id + " starts at " + describe(start) + ", but " + checkpoints[c - 1].id + " ends at " + describe(pose) + "."; + } + pose = start; + } + UnitTestResult result = check_checkpoint(checkpoint, pose); + if (result.result != UnitTestResult::PASSED){ + return result; + } + } + return true; +} + +struct ExpectedLeg{ + Direction direction; + int tiles; + TilePos end; +}; + +// Plans `start` to `goal` on the story maps and checks the walking legs +// on `map`, except the step that warps onto it, against `expected`. +UnitTestResult check_legs_on( + const MapPosition& start, Direction start_facing, const RouteGoal& goal, + const std::string& map, const std::vector& expected +){ + const std::optional> route = plan_overworld_route( + story_maps(), start, goal, default_route_costs(), start_facing + ); + if (!route){ + return "No route from " + to_string(start) + " to " + to_string(goal.position) + "."; + } + std::vector legs; + for (const RouteStep& step : *route){ + if (step.action == RouteAction::WALK && !step.warps && step.end.map == map){ + legs.push_back(step); + } + } + bool same = legs.size() == expected.size(); + for (size_t c = 0; same && c < legs.size(); c++){ + same = legs[c].direction == expected[c].direction && legs[c].tiles == expected[c].tiles && legs[c].end.point == expected[c].end; + } + if (!same){ + return "Unexpected legs on " + map + " from " + to_string(start) + " to " + to_string(goal.position) + ":" + describe(*route); + } + return true; +} + +// 00.09, each walk from where the one before leaves the player. +UnitTestResult test_pewter_gym_walks(){ + const MapPosition nurse{"PewterCity_PokemonCenter_1F", {7, 4}}; + // In by the door's mat (6, 14), straight up column 6 to below Liam's row. + UnitTestResult result = check_legs_on( + nurse, Direction::NORTH, RouteGoal{{"PewterCity_Gym", {6, 9}}, Direction::NORTH}, + "PewterCity_Gym", {{Direction::NORTH, 5, {6, 9}}} + ); + if (result.result != UnitTestResult::PASSED){ + return result; + } + // The step onto (6, 8), into Liam's line. + const MapData& gym = *find_map_named("PewterCity_Gym"); + if (classify_step(gym, PlayerState{{6, 9}, elevation_at(gym, {6, 9}), false}, Direction::NORTH) != StepKind::WALK){ + return "Can't step north from (6, 9) onto (6, 8)."; + } + // After Liam, on to Brock: two tiles north. + result = check_legs_on( + MapPosition{"PewterCity_Gym", {6, 8}}, Direction::NORTH, RouteGoal{{"PewterCity_Gym", {6, 6}}, Direction::NORTH}, + "PewterCity_Gym", {{Direction::NORTH, 2, {6, 6}}} + ); + if (result.result != UnitTestResult::PASSED){ + return result; + } + // The nurse's way: from her counter back in and up column 6 to Brock. + return check_legs_on( + nurse, Direction::NORTH, RouteGoal{{"PewterCity_Gym", {6, 6}}, Direction::NORTH}, + "PewterCity_Gym", {{Direction::NORTH, 8, {6, 6}}} + ); +} + +// 00.10: out of the Gym to the aide's top trigger. The route keeps off his +// three trigger tiles (46, 21..23), which would start the scene a step +// early, and the step east from its end lands on (46, 21). +UnitTestResult test_pewter_aide_walk(){ + const MapPosition gym{"PewterCity_Gym", {6, 6}}; + const MapPosition goal{"PewterCity", {45, 21}}; + const std::optional> route = plan_overworld_route( + story_maps(), gym, RouteGoal{goal, Direction::EAST}, default_route_costs(), Direction::NORTH + ); + if (!route || route->empty()){ + return "No route from " + to_string(gym) + " to " + to_string(goal) + "."; + } + MapPosition from = gym; + for (const RouteStep& step : *route){ + if (step.action != RouteAction::WALK){ + continue; + } + for (const MapPosition& tile : leg_tiles(story_maps(), from, step)){ + if (tile.map == "PewterCity" && tile.point.x == 46 && tile.point.y >= 21 && tile.point.y <= 23){ + return "The route crosses the aide's trigger " + to_string(tile) + ":" + describe(*route); + } + } + from = step.end; + } + if (route->back().end != goal){ + return "Expected the route to end at " + to_string(goal) + ", got " + to_string(route->back().end) + "."; + } + const MapData& pewter = *find_map_named("PewterCity"); + if (classify_step(pewter, PlayerState{{45, 21}, elevation_at(pewter, {45, 21}), false}, Direction::EAST) != StepKind::WALK){ + return "Can't step east from (45, 21) onto the trigger (46, 21)."; + } + return true; +} + +// Every ROUTE and LEGS after the Running Shoes (00.10) runs; none before. +UnitTestResult test_runs_after_shoes(){ + bool has_shoes = false; + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + for (const StoryStep& step : checkpoint.steps){ + if (step.kind != StoryStepKind::ROUTE && step.kind != StoryStepKind::LEGS){ + continue; + } + const MoveSpeed expected = has_shoes ? MoveSpeed::RUN : MoveSpeed::WALK; + if (move_speed(step) != expected){ + return std::format("{}/{}: expected to {}, it would {}.", checkpoint.id, step.name, move_speed_name(expected), move_speed_name(move_speed(step))); + } + } + has_shoes = has_shoes || checkpoint.id == "00.10"; + } + if (!has_shoes){ + return "No checkpoint 00.10, where the player gets the Running Shoes."; + } + return true; +} + +// Every checkpoint that starts from a save has a place the save card +// names, so a save left elsewhere is caught before it runs; and the +// places of the starts that matter differ. +UnitTestResult test_save_places(){ + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + if (checkpoint.start && save_card_place(Pokemon::grid_pose_of(*checkpoint.start).map).empty()){ + return checkpoint.id + " starts on " + Pokemon::grid_pose_of(*checkpoint.start).map + ", which has no save card place."; + } + } + if (save_card_place("ViridianForest") != "viridian-forest" || save_card_place("ViridianCity_Mart") != "viridian-city" + || save_card_place("PewterCity_PokemonCenter_1F") != "pewter-city" || save_card_place("PalletTown_ProfessorOaksLab") != "pallet-town" + ){ + return "Wrong save card places."; + } + if (!save_card_place("Route22").empty()){ + return "A place for a map the table doesn't use."; + } + return true; +} + +// A reload's save checked against the checkpoint's start: a save left in +// Pewter City (a new game whose save didn't happen) can't start 00.02 in +// the bedroom. The check takes no checks level: Fast runs it too. +UnitTestResult test_save_place_error(){ + struct Case{ + std::string start_map; + std::string place; + bool error; + }; + const Case CASES[] = { + {.start_map = "PalletTown_PlayersHouse_2F", .place = "pewter-city", .error = true}, + {.start_map = "PalletTown_PlayersHouse_2F", .place = "pallet-town", .error = false}, + // A card that can't be read is let pass. + {.start_map = "PalletTown_PlayersHouse_2F", .place = "", .error = false}, + {.start_map = "ViridianForest", .place = "viridian-city", .error = true}, + // A map with no known place isn't checked. + {.start_map = "Route22", .place = "pewter-city", .error = false}, + }; + for (const Case& c : CASES){ + const std::string error = save_place_error(c.start_map, c.place); + if (error.empty() == c.error){ + return "A save in \"" + c.place + "\" for a start on " + c.start_map + ": expected " + + (c.error ? "an error" : "no error") + ", got \"" + error + "\"."; + } + } + return true; +} + +std::string_view save_action_name(SaveAction action){ + switch (action){ + case SaveAction::WAIT: + return "WAIT"; + case SaveAction::ANSWER_YES: + return "ANSWER_YES"; + case SaveAction::NEXT_PAGE: + return "NEXT_PAGE"; + case SaveAction::CHECK_OVERWORLD: + return "CHECK_OVERWORLD"; + case SaveAction::FAIL_CANCELLED: + return "FAIL_CANCELLED"; + case SaveAction::FAIL_ERROR: + return "FAIL_ERROR"; + } + return "?"; +} + +// save_game()'s answers to the save dialogs of pokefirered's start_menu.c, +// screen by screen from the first YES/NO. +UnitTestResult test_save_dialog(){ + using S = SaveScreen; + using A = SaveAction; + struct Case{ + std::string name; + std::vector> screens; + }; + const std::vector CASES = { + { + .name = "first save", + .screens = {{S::YES_NO, A::ANSWER_YES}, {S::TEXT, A::WAIT}, {S::TEXT, A::WAIT}, {S::NOTHING, A::WAIT}, {S::NOTHING, A::CHECK_OVERWORLD}}, + }, + { + .name = "over this game's save", + .screens = {{S::YES_NO, A::ANSWER_YES}, {S::TEXT, A::WAIT}, {S::YES_NO, A::ANSWER_YES}, {S::TEXT, A::WAIT}, {S::NOTHING, A::WAIT}, {S::NOTHING, A::CHECK_OVERWORLD}}, + }, + { + // WARNING!, four pages, then the YES/NO that starts on NO. + .name = "a new game over another game's save", + .screens = { + {S::YES_NO, A::ANSWER_YES}, + {S::PAGED_TEXT, A::NEXT_PAGE}, {S::NOTHING, A::WAIT}, {S::PAGED_TEXT, A::NEXT_PAGE}, {S::PAGED_TEXT, A::NEXT_PAGE}, + {S::TEXT, A::WAIT}, {S::YES_NO, A::ANSWER_YES}, {S::TEXT, A::WAIT}, {S::NOTHING, A::WAIT}, {S::NOTHING, A::CHECK_OVERWORLD}, + }, + }, + { + .name = "cancelled: the START menu is back", + .screens = {{S::YES_NO, A::ANSWER_YES}, {S::TEXT, A::WAIT}, {S::START_MENU, A::FAIL_CANCELLED}}, + }, + { + .name = "Save error.", + .screens = {{S::YES_NO, A::ANSWER_YES}, {S::TEXT, A::WAIT}, {S::PAGED_TEXT, A::NEXT_PAGE}, {S::NOTHING, A::WAIT}, {S::NOTHING, A::FAIL_ERROR}}, + }, + }; + for (const Case& c : CASES){ + SaveDialog dialog; + for (size_t i = 0; i < c.screens.size(); i++){ + const SaveAction action = dialog.next(c.screens[i].first); + if (action != c.screens[i].second){ + return std::format("{}, screen {}: expected {}, got {}.", c.name, i + 1, save_action_name(c.screens[i].second), save_action_name(action)); + } + } + } + return true; +} + +UnitTestResult test_lint(){ + // FRLG's own action args (a battle's trainer and foes), with no console. + const Pokemon::StoryActionTable table = make_story_action_table([](StoryActionId){ + return Pokemon::StoryAction{}; + }); + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + const std::vector problems = Pokemon::lint_story_checkpoint(checkpoint, table); + if (!problems.empty()){ + return problems[0]; + } + } + return true; +} + +// Every battle step in the table names its trainer and that trainer's +// party, each species one the battle data has. +UnitTestResult test_story_trainers(){ + size_t battles = 0; + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + for (const StoryStep& step : checkpoint.steps){ + if (step.kind != StoryStepKind::BATTLE){ + continue; + } + battles++; + const std::string& trainer = Pokemon::story_arg(step.args, "trainer"); + const std::vector& foes = Pokemon::story_arg>(step.args, "foes"); + if (trainer.empty() || foes.empty()){ + return std::format("{}, {}: no trainer or no foes.", checkpoint.id, step.name); + } + for (const std::string& foe : foes){ + if (species_data(foe) == nullptr){ + return std::format("{}, {}: unknown foe {}.", checkpoint.id, step.name, foe); + } + } + } + } + if (battles == 0){ + return "Expected battle steps in the table."; + } + return true; +} + +UnitTestResult test_unique_names(){ + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + for (size_t i = 0; i < checkpoint.steps.size(); i++){ + for (size_t j = i + 1; j < checkpoint.steps.size(); j++){ + if (checkpoint.steps[i].name == checkpoint.steps[j].name){ + return checkpoint.id + " has two steps named " + checkpoint.steps[i].name + "."; + } + } + } + } + return true; +} +// The intro's names: the player's keyboard first, then the rival's list, +// where a preset is picked; a keyboard after the player's means the list +// was missed. +UnitTestResult test_intro_names(){ + struct Case{ + std::string_view what; + IntroNameScreen screen; + size_t keyboards_seen; + size_t presets_picked; + IntroNameStep expected; + }; + const std::vector cases{ + {.what = "the first keyboard", .screen = IntroNameScreen::KEYBOARD, .keyboards_seen = 0, .presets_picked = 0, .expected = IntroNameStep::PLAYER_KEYBOARD}, + {.what = "the list after the player's keyboard", .screen = IntroNameScreen::RIVAL_LIST, .keyboards_seen = 1, .presets_picked = 0, .expected = IntroNameStep::RIVAL_PRESET}, + {.what = "a list read before the player's keyboard", .screen = IntroNameScreen::RIVAL_LIST, .keyboards_seen = 0, .presets_picked = 0, .expected = IntroNameStep::NONE}, + {.what = "the second keyboard", .screen = IntroNameScreen::KEYBOARD, .keyboards_seen = 1, .presets_picked = 0, .expected = IntroNameStep::RIVAL_KEYBOARD}, + {.what = "a keyboard after a preset was picked", .screen = IntroNameScreen::KEYBOARD, .keyboards_seen = 1, .presets_picked = 1, .expected = IntroNameStep::RIVAL_KEYBOARD}, + {.what = "the list again after a NO", .screen = IntroNameScreen::RIVAL_LIST, .keyboards_seen = 1, .presets_picked = 1, .expected = IntroNameStep::RIVAL_PRESET}, + {.what = "the list after every try", .screen = IntroNameScreen::RIVAL_LIST, .keyboards_seen = 1, .presets_picked = RIVAL_PRESET_TRIES, .expected = IntroNameStep::NONE}, + {.what = "a message box", .screen = IntroNameScreen::OTHER, .keyboards_seen = 1, .presets_picked = 0, .expected = IntroNameStep::NONE}, + }; + for (const Case& c : cases){ + const IntroNameStep step = intro_name_step(c.screen, c.keyboards_seen, c.presets_picked); + if (step != c.expected){ + return std::string(c.what) + ": expected step " + std::to_string(static_cast(c.expected)) + + ", got " + std::to_string(static_cast(step)) + "."; + } + } + // A black screen is no list. + ImageRGB32 black(1920, 1080); + black.fill(0xff000000); + if (rival_name_list_cursor(black).has_value()){ + return "Read the rival's name list on a black screen."; + } + return true; +} + +// set_options()'s RIGHT presses from each value an old save can leave: +// on console B a save with FAST and SET became SLOW and SHIFT when the +// presses assumed MID and SHIFT. +UnitTestResult test_option_presses(){ + const std::vector& speed = option_menu_values(OptionMenuItem::TEXT_SPEED); + const std::vector& scene = option_menu_values(OptionMenuItem::BATTLE_SCENE); + const std::vector& style = option_menu_values(OptionMenuItem::BATTLE_STYLE); + struct Case{ + const std::vector& values; + std::string current; + std::string target; + std::optional expected; + }; + const std::vector cases{ + {.values = speed, .current = "slow", .target = "fast", .expected = 2}, + {.values = speed, .current = "mid", .target = "fast", .expected = 1}, + {.values = speed, .current = "fast", .target = "fast", .expected = 0}, + {.values = scene, .current = "on", .target = "off", .expected = 1}, + {.values = scene, .current = "off", .target = "off", .expected = 0}, + {.values = style, .current = "shift", .target = "set", .expected = 1}, + {.values = style, .current = "set", .target = "set", .expected = 0}, + // RIGHT wraps from the last value to the first. + {.values = speed, .current = "fast", .target = "slow", .expected = 1}, + // Unread, or another row's value: no guess. + {.values = speed, .current = "", .target = "fast", .expected = std::nullopt}, + {.values = style, .current = "fast", .target = "set", .expected = std::nullopt}, + {.values = scene, .current = "set", .target = "off", .expected = std::nullopt}, + }; + for (const Case& c : cases){ + const std::optional presses = option_right_presses(c.values, c.current, c.target); + if (presses != c.expected){ + auto text = [](const std::optional& n){ + return n ? std::to_string(*n) + " RIGHT" : std::string("no presses"); + }; + return "\"" + c.current + "\" to " + c.target + ": expected " + text(c.expected) + ", got " + text(presses) + "."; + } + } + return true; +} + +const AutoStoryTestCase AUTO_STORY_CASES[] = { + { + .input = {.name = "every route plans, and checkpoints chain", .body = test_routes_and_chain}, + .expectation = {.description = "verifies route planning validity across all chained checkpoints"}, + }, + { + .input = {.name = "step names are unique per checkpoint", .body = test_unique_names}, + .expectation = {.description = "ensures step identifier uniqueness within checkpoints"}, + }, + { + .input = {.name = "every save has a place on the save card", .body = test_save_places}, + .expectation = {.description = "validates save location identifiers on save card"}, + }, + { + .input = {.name = "a reload's save is checked against the start", .body = test_save_place_error}, + .expectation = {.description = "detects mismatch between checkpoint initial state and save point"}, + }, + { + .input = {.name = "save dialogs: every YES/NO is YES, a cancel fails", .body = test_save_dialog}, + .expectation = {.description = "verifies save confirmation prompt interactions"}, + }, + { + .input = {.name = "every checkpoint lints clean", .body = test_lint}, + .expectation = {.description = "validates semantic lint rules across story step sequence"}, + }, + { + .input = {.name = "every story battle's plan names a trainer and its party", .body = test_story_trainers}, + .expectation = {.description = "ensures all scripted story battles list known foes"}, + }, + { + .input = {.name = "Pewter Gym walks", .body = test_pewter_gym_walks}, + .expectation = {.description = "verifies Pewter Gym route planning and obstacle avoidance"}, + }, + { + .input = {.name = "Pewter: to the aide's trigger", .body = test_pewter_aide_walk}, + .expectation = {.description = "plans path to Running Shoes aide trigger tile"}, + }, + { + .input = {.name = "routes run after the Running Shoes", .body = test_runs_after_shoes}, + .expectation = {.description = "switches movement speed to running once shoes acquired"}, + }, + { + .input = {.name = "intro: names, the rival's from the list", .body = test_intro_names}, + .expectation = {.description = "verifies character and rival naming inputs"}, + }, + { + .input = {.name = "options: RIGHT presses from the shown value", .body = test_option_presses}, + .expectation = {.description = "calculates Dpad RIGHT inputs for setting game options"}, + }, +}; + +} // namespace + + +void add_tests_AutoStory(UnitTestDatabase& database){ + for (const auto& scenario : AUTO_STORY_CASES){ + database.add(scenario); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.01.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.01.plan.json new file mode 100644 index 0000000000..3e47c1be6b --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.01.plan.json @@ -0,0 +1,30 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "00.01", + "title": "new game to the bedroom", + "events": [ + { + "id": "intro", + "kind": "new_game", + "declared_after": {"map": "PalletTown_PlayersHouse_2F", "tiles": [[6, 6]], "facing": "north"}, + "why": "Oak's speech, BOY, default names, rival GREEN" + }, + { + "id": "options", + "kind": "options", + "why": "fast text; no switch prompt between a trainer's Pokemon" + } + ] + }, + "execution": { + "menu": "before_pokemon", + "notes": { + "intro": [ + "new_game.c: the bedroom at (6, 6), facing the TV." + ] + } + }, + "metadata": {"phase": "testing"} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.02.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.02.plan.json new file mode 100644 index 0000000000..06d522c23d --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.02.plan.json @@ -0,0 +1,23 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "00.02", + "title": "bedroom to Pallet Town", + "start": {"map": "PalletTown_PlayersHouse_2F", "tiles": [[6, 6]], "facing": "north"}, + "events": [ + { + "id": "front_door", + "kind": "route", + "args": { + "target": {"map": "PalletTown", "tiles": [[6, 8]]} + }, + "why": "down the stairs and out of the house" + } + ] + }, + "execution": { + "menu": "before_pokemon" + }, + "metadata": {"phase": "testing"} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.03.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.03.plan.json new file mode 100644 index 0000000000..0a86b054dc --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.03.plan.json @@ -0,0 +1,42 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "00.03", + "title": "Oak stops the player and walks them to the lab", + "start": {"map": "PalletTown", "tiles": [[6, 8]], "facing": "south"}, + "events": [ + { + "id": "below_oaks_trigger", + "kind": "route", + "args": { + "target": {"map": "PalletTown", "tiles": [[12, 2]], "facing": "north"} + }, + "why": "below the north exit, short of Oak's trigger at (12, 1)" + }, + { + "id": "oaks_trigger", + "kind": "step", + "args": { + "direction": "north" + }, + "why": "the trigger: \"Don't go out!\"" + }, + { + "id": "to_the_lab", + "kind": "scene", + "declared_after": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[6, 4]], "facing": "north"}, + "why": "Oak walks the player into the lab; the scene ends at the table" + } + ] + }, + "execution": { + "menu": "before_pokemon", + "notes": { + "to_the_lab": [ + "PlayerEnter walks the player up 8 tiles from the lab's door." + ] + } + }, + "metadata": {"phase": "testing"} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.04.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.04.plan.json new file mode 100644 index 0000000000..db5ea566e7 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.04.plan.json @@ -0,0 +1,79 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "00.04", + "title": "Squirtle, then the rival's battle", + "start": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[6, 4]], "facing": "north"}, + "events": [ + { + "id": "below_squirtle", + "kind": "route", + "args": { + "target": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[9, 5]], "facing": "north"} + }, + "why": "under Squirtle's ball (9, 4)" + }, + { + "id": "squirtle_ball", + "kind": "talk", + "why": "\"So, you want the WATER POKEMON SQUIRTLE?\"" + }, + { + "id": "choose_squirtle", + "kind": "answer", + "why": "take Squirtle" + }, + { + "id": "no_nickname", + "kind": "answer", + "args": { + "yes": false + }, + "why": "\"give a nickname?\" NO" + }, + { + "id": "rival_takes_bulbasaur", + "kind": "scene", + "declared_after": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[9, 5]], "facing": "north"}, + "why": "the rival picks his ball; the player still faces the table (console B, 2026-11-01)" + }, + { + "id": "above_rival_trigger", + "kind": "route", + "args": { + "target": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[7, 7]], "facing": "south"} + }, + "why": "short of the rival's trigger row 8" + }, + { + "id": "rival_trigger", + "kind": "step", + "args": { + "direction": "south" + }, + "why": "\"Wait, let's check out our POKEMON!\"" + }, + { + "id": "rival_battle", + "kind": "battle", + "args": { + "may_lose": true, + "trainer": "TRAINER_RIVAL_OAKS_LAB_BULBASAUR", + "foes": ["bulbasaur"] + }, + "declared_after": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[7, 8]], "facing": "south"}, + "why": "the tutorial battle; losing goes on too" + } + ] + }, + "execution": { + "menu": "before_pokedex", + "notes": { + "rival_battle": [ + "The rival leaves; PlayerWatchRivalExitAfterBattleRight ends facing down." + ] + } + }, + "metadata": {"phase": "testing"} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.05.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.05.plan.json new file mode 100644 index 0000000000..19e8a2e15e --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.05.plan.json @@ -0,0 +1,42 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "00.05", + "title": "Route 1 to Viridian Mart: Oak's Parcel", + "start": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[7, 8]], "facing": "south"}, + "events": [ + { + "id": "below_mart_door", + "kind": "route", + "args": { + "target": {"map": "ViridianCity", "tiles": [[36, 20]], "facing": "north"} + }, + "why": "Route 1, running from wild battles" + }, + { + "id": "mart_door", + "kind": "step", + "args": { + "direction": "north" + }, + "why": "the clerk's scene starts on entering" + }, + { + "id": "parcel_from_clerk", + "kind": "scene", + "declared_after": {"map": "ViridianCity_Mart", "tiles": [[4, 3]], "facing": "west"}, + "why": "the clerk gives OAK'S PARCEL" + } + ] + }, + "execution": { + "menu": "before_pokedex", + "notes": { + "parcel_from_clerk": [ + "ApproachCounter: up 4 from the mat, then faces the clerk." + ] + } + }, + "metadata": {"phase": "testing"} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.06.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.06.plan.json new file mode 100644 index 0000000000..f58aba06bb --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.06.plan.json @@ -0,0 +1,34 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "00.06", + "title": "Oak's Parcel to the Pokedex", + "start": {"map": "ViridianCity_Mart", "tiles": [[4, 3]], "facing": "west"}, + "events": [ + { + "id": "below_oak", + "kind": "route", + "args": { + "target": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[6, 4]], "facing": "north"} + }, + "why": "back down Route 1 to Oak" + }, + { + "id": "give_parcel", + "kind": "talk", + "why": "Oak takes the parcel" + }, + { + "id": "pokedex_scene", + "kind": "scene", + "declared_after": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[6, 4]], "facing": "south"}, + "why": "the rival comes in, Pokedexes from the desk; the player ends facing south (console B, 2026-11-01)" + } + ] + }, + "execution": { + "menu": "full" + }, + "metadata": {"phase": "testing"} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.07.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.07.plan.json new file mode 100644 index 0000000000..75e4db6a09 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.07.plan.json @@ -0,0 +1,96 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "00.07", + "title": "Viridian shopping, then into Viridian Forest", + "start": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[6, 4]], "facing": "south"}, + "events": [ + { + "id": "mart_clerk", + "kind": "route", + "args": { + "target": {"map": "ViridianCity_Mart", "tiles": [[4, 3]], "facing": "west"} + }, + "why": "Route 1 again" + }, + { + "id": "potions_and_antidotes", + "kind": "shop", + "args": { + "items": [{"item": "potion", "quantity": 5}, {"item": "antidote", "quantity": 3}, {"item": "parlyz_heal", "quantity": 1}] + }, + "why": "5 Potions, 3 Antidotes, 1 Parlyz Heal" + }, + { + "id": "viridian_nurse", + "kind": "route", + "args": { + "target": {"map": "ViridianCity_PokemonCenter_1F", "tiles": [[7, 4]], "facing": "north"} + }, + "why": "heal before the forest" + }, + { + "id": "heal_viridian", + "kind": "heal", + "why": "full HP" + }, + { + "id": "below_old_man_trigger", + "kind": "route", + "args": { + "target": {"map": "ViridianCity", "tiles": [[20, 9]], "facing": "north"} + }, + "why": "short of the tutorial trigger (20, 8)" + }, + { + "id": "old_man_trigger", + "kind": "step", + "args": { + "direction": "north" + }, + "why": "the old man's catching tutorial can't be walked around" + }, + { + "id": "old_man_tutorial", + "kind": "scene", + "declared_after": {"map": "ViridianCity", "tiles": [[20, 8]], "facing": "east"}, + "why": "about 60 lines and his demo battle; TEACHY TV" + }, + { + "id": "past_old_man", + "kind": "route", + "args": { + "target": {"map": "ViridianCity", "tiles": [[20, 5]], "facing": "north"} + }, + "why": "north along column 20, clear of the old man" + }, + { + "id": "forest_entrance", + "kind": "route", + "args": { + "target": {"map": "ViridianForest", "tiles": [[29, 62]], "facing": "north"} + }, + "why": "Route 2 and the south gate, running from wild battles" + } + ] + }, + "execution": { + "menu": "full", + "notes": { + "potions_and_antidotes": [ + "2000 of the 3000 a new game starts with, plus the rival's prize." + ], + "old_man_tutorial": [ + "TutorialTriggerLeft turns the player right, to the old man." + ], + "past_old_man": [ + "After his demo the old man stands east of the player, beside (20, 8), where the map doesn't have him: \"east 2\" from there didn't move, and the walk north ended under Route 2's ledge in column 8 (console B, 2026-11-01). Go north first." + ], + "forest_entrance": [ + "The gate's north warp lands on the forest's exit mat (29, 62), facing north. The save there keeps a forest failure from going back to Pallet." + ] + } + }, + "metadata": {"phase": "testing"} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.08.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.08.plan.json new file mode 100644 index 0000000000..ddb92f9f99 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.08.plan.json @@ -0,0 +1,83 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "00.08", + "title": "Viridian Forest to Pewter Center", + "start": {"map": "ViridianForest", "tiles": [[29, 62]], "facing": "north"}, + "events": [ + { + "id": "forest_east", + "kind": "legs", + "args": { + "legs": [{"direction": "east", "tiles": 1}, {"direction": "north", "tiles": 4}, {"direction": "east", "tiles": 14}, {"direction": "north", "tiles": 15}], + "fight_wild": true + }, + "why": "up the east side to (44, 43)" + }, + { + "id": "forest_north", + "kind": "route", + "args": { + "target": {"map": "ViridianForest", "tiles": [[39, 25]]}, + "fight_wild": true + }, + "why": "north part" + }, + { + "id": "forest_exit", + "kind": "legs", + "args": { + "legs": [{"direction": "north", "tiles": 10}, {"direction": "west", "tiles": 12}, {"direction": "south", "tiles": 10}, {"direction": "west", "tiles": 6}, {"direction": "north", "tiles": 20}, {"direction": "south", "tiles": 1}, {"direction": "west", "tiles": 10}, {"direction": "south", "tiles": 27}, {"direction": "west", "tiles": 8}, {"direction": "north", "tiles": 20}, {"direction": "east", "tiles": 1}], + "fight_wild": true + }, + "why": "walls all the way to the gate's column" + }, + { + "id": "forest_gate", + "kind": "route", + "args": { + "target": {"map": "Route2_ViridianForest_NorthEntrance", "tiles": [[7, 10]], "facing": "north"}, + "fight_wild": true + }, + "why": "north onto the exit, arriving on the gate's mat" + }, + { + "id": "pewter_nurse", + "kind": "route", + "args": { + "target": {"map": "PewterCity_PokemonCenter_1F", "tiles": [[7, 4]], "facing": "north"} + }, + "why": "Route 2 north to Pewter's Center" + }, + { + "id": "heal_pewter", + "kind": "heal", + "why": "full HP" + } + ] + }, + "execution": { + "menu": "full", + "supplies": { + "potions": 5, + "antidotes": 3, + "parlyz_heals": 1 + }, + "notes": { + "checkpoint": [ + "The supplies bought in 00.07." + ], + "forest_east": [ + "Wild battles are fought for EXP. Straight up the east side from the entrance, each leg ending on a wall (the Boy at (45, 58) stops the east one). Rick (47, 45) sees (42..46, 45), so the last leg meets his battle and is held on to its wall after it. The by-hand run's detour west to (13, 46) and back is dropped." + ], + "forest_exit": [ + "To the gate by legs that end on walls, which the walker holds again after a battle instead of estimating where it stopped: planned routes with open legs lost the player in the north of the forest (console B, 2026-11-01). The two 1-tile legs are single steps." + ], + "pewter_nurse": [ + "Out of the forest, wild battles are run from; trainers are still fought." + ] + } + }, + "metadata": {"phase": "testing"} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.09.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.09.plan.json new file mode 100644 index 0000000000..103deb8066 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.09.plan.json @@ -0,0 +1,88 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "00.09", + "title": "Pewter Gym: Camper Liam, then Brock", + "start": {"map": "PewterCity_PokemonCenter_1F", "tiles": [[7, 4]], "facing": "north"}, + "events": [ + { + "id": "below_liam_line", + "kind": "route", + "args": { + "target": {"map": "PewterCity_Gym", "tiles": [[6, 9]], "facing": "north"} + }, + "why": "in by the door, up column 6 to below Liam's row" + }, + { + "id": "liam_line", + "kind": "step", + "args": { + "direction": "north" + }, + "why": "onto (6, 8), in Liam's line" + }, + { + "id": "camper_liam", + "kind": "battle", + "args": { + "trainer": "TRAINER_CAMPER_LIAM", + "foes": ["geodude", "sandshrew"] + }, + "declared_after": {"map": "PewterCity_Gym", "tiles": [[6, 8]], "facing": "north"}, + "why": "Geodude and Sandshrew; EXP before Brock" + }, + { + "id": "ready_for_brock", + "kind": "ready", + "args": { + "target": {"map": "PewterCity_PokemonCenter_1F", "tiles": [[7, 4]], "facing": "north"} + }, + "why": "items for a status or low HP; the nurse only if they can't" + }, + { + "id": "before_brock", + "kind": "route", + "args": { + "target": {"map": "PewterCity_Gym", "tiles": [[6, 6]], "facing": "north"} + }, + "why": "below Brock (6, 5); Liam, beaten, stands at (5, 8)" + }, + { + "id": "challenge_brock", + "kind": "talk", + "why": "Brock's speech" + }, + { + "id": "brock", + "kind": "battle", + "args": { + "trainer": "TRAINER_LEADER_BROCK", + "foes": ["geodude", "onix"] + }, + "declared_after": {"map": "PewterCity_Gym", "tiles": [[6, 6]], "facing": "north"}, + "why": "Geodude and Onix, with Bubble; Boulder Badge and TM39" + } + ] + }, + "execution": { + "menu": "full", + "supplies": { + "potions": 2, + "antidotes": 1, + "parlyz_heals": 0 + }, + "notes": { + "checkpoint": [ + "The by-hand save: 2 Potions and 1 Antidote left after the forest." + ], + "below_liam_line": [ + "Camper Liam (3, 8) always faces east (MOVEMENT_TYPE_FACE_RIGHT, sight 4) and sees (4..7, 8): walking north up column 6 from the door, the step onto (6, 8) starts his battle. He walks up to the player, who stays put and keeps facing north (FRLG doesn't turn the player to a trainer). That step is taken on its own, so no leg is cut." + ], + "ready_for_brock": [ + "On to Brock unless red HP or a status is left that no item cures." + ] + } + }, + "metadata": {"phase": "testing"} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.10.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.10.plan.json new file mode 100644 index 0000000000..6c4b5e9883 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.10.plan.json @@ -0,0 +1,49 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "00.10", + "title": "Pewter: the Running Shoes from Oak's aide", + "start": {"map": "PewterCity_Gym", "tiles": [[6, 6]], "facing": "north"}, + "events": [ + { + "id": "before_aide_trigger", + "kind": "route", + "args": { + "target": {"map": "PewterCity", "tiles": [[45, 21]], "facing": "east"} + }, + "why": "out of the Gym, east along row 21, short of the top trigger" + }, + { + "id": "aide_trigger", + "kind": "step", + "args": { + "direction": "east" + }, + "why": "onto (46, 21), below the aide" + }, + { + "id": "shoes_from_aide", + "kind": "scene", + "declared_after": {"map": "PewterCity", "tiles": [[46, 21]], "facing": "north"}, + "why": "\"Oh, PLAYER!\" ... the Running Shoes; ends facing north" + } + ] + }, + "execution": { + "menu": "full", + "lead": "after_brock", + "notes": { + "checkpoint": [ + "At the rows after Brock: no items counted, the starter with the moves the story gave it by Lv13. A run that loads a save reads the moves off the lead's summary instead (read_lead_moves()), so a save whose moves differ from these (console B, 2026-11-02: Water Gun where Tackle was) is fought with the moves it has." + ], + "before_aide_trigger": [ + "Brock's win sets VAR_MAP_SCENE_PEWTER_CITY to 1 and shows the aide at (46, 20); his triggers are (46, 21..23) (PewterCity map.json). The Gym guide's triggers at (42..43, 21..23) need the scene at 0." + ], + "shoes_from_aide": [ + "RunningShoesAideTriggerTop: the aide talks from (46, 20), no YES/NO; the player only turns up. He walks off and is removed; FLAG_SYS_B_DASH is set (console B, 2026-11-02: about 20 B presses to the overworld)." + ] + } + }, + "metadata": {"phase": "testing"} +} diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 316ac95e80..647ca0f7e2 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -2036,6 +2036,8 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/PokemonFRLG_Settings.h Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp @@ -2047,6 +2049,9 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleRisk.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleTurns.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCheckpoints.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryIntro.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItemsPocket.h @@ -2057,13 +2062,34 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyMember.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPoses.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPresses.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySave.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySaveChecks.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrameCompare.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrameStore.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartMenu.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrames.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrames.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStartFrames_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStats.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport_Tests.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySupplies.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.cpp Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.h Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorter.cpp diff --git a/devtools/story-export/FRLG.cmake b/devtools/story-export/FRLG.cmake new file mode 100644 index 0000000000..2c217b0480 --- /dev/null +++ b/devtools/story-export/FRLG.cmake @@ -0,0 +1,17 @@ +# Evaluates the real game table without constructing a console executor. +# Full application libraries are build dependencies; this is not PA_CORE_ONLY. +option(PA_FRLG_STORY_EXPORT "Build the offline evaluated FRLG checkpoint exporter" OFF) +if(PA_FRLG_STORY_EXPORT) + execute_process(COMMAND git rev-parse HEAD WORKING_DIRECTORY "${REPO_ROOT_DIR}" + OUTPUT_VARIABLE STORY_EXPORT_REVISION OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND_ERROR_IS_FATAL ANY) + execute_process(COMMAND git diff --quiet HEAD WORKING_DIRECTORY "${REPO_ROOT_DIR}" + RESULT_VARIABLE STORY_EXPORT_DIRTY) + if(NOT STORY_EXPORT_DIRTY EQUAL 0) + message(FATAL_ERROR "Commit tracked changes before configuring a provenance-bearing story export.") + endif() + add_executable(StoryCheckpointExport + ../devtools/story-export/frlg_main.cpp) + target_link_libraries(StoryCheckpointExport PRIVATE SerialProgramsLib) + apply_common_target_properties(StoryCheckpointExport) + target_compile_definitions(StoryCheckpointExport PRIVATE PA_STORY_EXPORT_REVISION="${STORY_EXPORT_REVISION}") +endif() diff --git a/devtools/story-export/README.md b/devtools/story-export/README.md new file mode 100644 index 0000000000..8195c7b3fe --- /dev/null +++ b/devtools/story-export/README.md @@ -0,0 +1,38 @@ +# Evaluated native story checkpoint capture + +This first adapter exports FRLG stage 1's actual `story_checkpoints()` rows. +It does not parse C++ text, construct a story executor, load a save, open a +profile or send controller inputs. It is a full-library build target, not the +Qt-free core target; linking Qt libraries does not create an application/window. + +From a clean committed checkout with the usual native build dependencies: + +```sh +cmake -S SerialPrograms -B build -DPA_FRLG_STORY_EXPORT=ON +cmake --build build --target StoryCheckpointExport -j4 +build/StoryCheckpointExport 00.05 > frlg-parcel.native.json +``` + +On multi-configuration generators add `--config RelWithDebInfo`, then run +`build/RelWithDebInfo/StoryCheckpointExport.exe`. The current full-library CI +builds the target on every platform and captures Parcel as a Linux artifact. +Reconfigure after switching source revisions: `source_revision` names the clean +revision used at configure time. Canonical captures should come from clean CI. + +The `pokesim-native-checkpoint-export/1` capture contains the shared checkpoint +codec plus all fields of this source revision's FRLG checkpoint extension: +menu and supplies (including party moves/PP, optional stats, slot zero, and +foe bookkeeping). Defaults remain native bookkeeping, not measured state or +requirements. No inference of full HP, actual inventory or battle probability +is permitted from this capture alone. + +Runtime configuration, map pins, executor bindings, entry evidence and effective +save/retry policy are explicitly unbound. This is not the proposed executable +story-plan envelope, and must not be passed directly to a console executor. +Other native revisions with more checkpoint fields need an updated adapter. +BDSP `01.03`, policy binding and native/Python execution parity remain next. + +Stdout is machine JSON; import/format it through PokemonSimulation's native +export CLI and compact contract formatter before checking in review data. +Tests next to the adapter check the real Parcel row and every native extension +field using synthetic non-default state. They do not validate console timings. diff --git a/devtools/story-export/frlg_main.cpp b/devtools/story-export/frlg_main.cpp new file mode 100644 index 0000000000..72d3a0bbcf --- /dev/null +++ b/devtools/story-export/frlg_main.cpp @@ -0,0 +1,34 @@ +/* Offline evaluated FRLG table export. No console or profile initialization. + * cmake -S SerialPrograms -B build -DPA_FRLG_STORY_EXPORT=ON + * cmake --build build --target StoryCheckpointExport -j4 + * build/StoryCheckpointExport 00.05 > frlg-parcel.native.json + * Format the captured JSON with PokemonSimulation's contract formatter. + */ +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport.h" +#include "VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h" + +int main(int argc, char** argv){ + if (argc != 2){ + std::cerr << "Usage: StoryCheckpointExport CHECKPOINT_ID\n"; + return 2; + } + try{ + for (const auto& row : PokemonAutomation::NintendoSwitch::PokemonFRLG::story_checkpoints()){ + if (row.id != std::string_view(argv[1])){ + continue; + } + auto result = PokemonAutomation::NintendoSwitch::PokemonFRLG::story_checkpoint_export(row); + result.to_object_throw()["source_revision"] = PA_STORY_EXPORT_REVISION; + std::cout << result.dump(-1) << '\n'; + return 0; + } + std::cerr << "Unknown checkpoint: " << argv[1] << '\n'; + }catch (const PokemonAutomation::Exception& error){ + std::cerr << error.to_str() << '\n'; + } + return 1; +}