From 9167ebacd23f9da0db0dd98538fd74587868bcd0 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 19:33:27 -0800 Subject: [PATCH 1/2] BDSP AutoStory: move the story sim's executor out of its tests SimStoryStepIO, SimExecutor and the run helpers move unchanged from StorySim_Tests.cpp to Simulation/PokemonBDSP_AutoStory_StorySim.{h,cpp}, so other test files can run rows on the same simulation. The header qualifies Pokemon:: names; the helpers that were file-local stay in an anonymous namespace. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StorySim.cpp | 479 +++++++++++++ .../PokemonBDSP_AutoStory_StorySim.h | 292 ++++++++ .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 663 +----------------- SerialPrograms/cmake/SourceFiles.cmake | 2 + 4 files changed, 774 insertions(+), 662 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp new file mode 100644 index 0000000000..fd6b86de1e --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -0,0 +1,479 @@ +/* BDSP AutoStory - Story simulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_SimGround.h" +#include "PokemonBDSP_AutoStory_StorySim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::Outcome; +using Pokemon::Pose; +using Pokemon::RunState; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + + +// A hold until something stops us. A door stops it at the fade, which +// fails the step; a fade missed lets the hold go on past the mouth (r81's +// timed walk south out of the Ravaged Path, onto Route 204's cliff). +void SimStoryStepIO::walk_until_stopped(Direction direction, size_t tiles, const std::string& label){ + m_sim.tap(direction, ROUTE_TURN_TAP, false); + Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); + SimMove move = m_sim.hold(direction, limit, SimPace::WALK); + if (move.stop == SimStop::WARP && fade_missed() && m_far_side()){ + limit -= std::min(limit, move.time); + move = m_sim.hold(direction, limit, SimPace::WALK); + } + if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ + m_route.note(label + ": " + sim_stop_name(move.stop) + " instead of a stop.", RouteNote::FAILURE); + } +} + +// The D-pad, a tile at a time, until `map`'s banner reads; through a door +// the walk goes on beyond it (the fade eats no tiles of a hold). +bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&){ + const bool miss = banner_missed(); + size_t on = 0; + for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ + SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + const bool crossed = move.stop == SimStop::WARP && m_far_side(); + const bool stopped = !crossed && (move.distance == 0 || move.stop != SimStop::DONE); + on = on_map(map) ? on + 1 : 0; + if (on > 0 && (on > SIM_BANNER_TILES || stopped) && !miss){ + return true; + } + if (stopped){ + return false; + } + } + return false; +} + +// D-pad taps, each looked at, until the fade and then the banner (the +// console's ConsoleStoryStepIO::tap_to_banner()): none if the banner shows +// before the first. Each look stands still, so a banner on the far side +// reads at once. A fade seen ends the taps, +// banner or not; with the fade missed the next look still sees the banner. +std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ + if (m_misses.through == m_misses.tap_steps++){ + m_misses.missed = true; + if (m_far_side() && m_misses.through_banner){ + return 0; + } + } + bool crossed = false; + for (size_t tap = 1; tap <= max_taps; tap++){ + const SimMove move = m_sim.tap(direction, 160ms, false); + if (move.stop == SimStop::DIALOG){ + return std::nullopt; + } + bool faded = false; + if (move.stop == SimStop::WARP){ + faded = !fade_missed(); + crossed = m_far_side(); + } + if (crossed && on_map(map) && !banner_missed()){ + return tap; + } + if (faded){ + return std::nullopt; + } + } + return std::nullopt; +} + +// The story variables whose coord events the table walks onto, from the +// row (and step) the table's reasons give, with the maps' coord events +// (Diamond's zone events; Platinum's for the houses): Barry's doorstep and +// Mom's warning in 00.01, Barry's Route 201 warning, then its pull-back +// row 19 once he has warned us (r14, r16); the lake's entrance in 00.02; +// Rowan's stop and Dawn at Sandgem's edge in 00.03; Dawn's catching +// tutorial on Route 202 from 00.04's start, Mom's call once she has healed +// us; the Poketch president on Jubilife's row 40 in 00.05b; Barry on Route +// 203 in 01.01; the Gate's Hiker and Oreburgh's welcome in 01.02; Barry's +// bump in Oreburgh after Roark in 01.05; and Rowan in Jubilife in 01.07. +// Left out: the Twinleaf guitarist (spent upstairs), Platinum's rival +// steps around our bedroom's start, Dawn at Jubilife's steps (BDSP starts +// her below them: an event), and Floaroma's (10..12, 29) (Diamond only). +std::vector story_vars(){ + return { + {.var = "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", .value = 0, .row = "00.01", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 0, .row = "00.01", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 1, .row = "00.01", .after = "barry_warns_us"}, + {.var = "VAR_VERITY_LAKEFRONT_STATE", .value = 0, .row = "00.02", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 2, .row = "00.03", .after = ""}, + {.var = "VAR_SANDGEM_TOWN_STATE", .value = 0, .row = "00.03", .after = ""}, + {.var = "VAR_ROUTE_202_STATE", .value = 0, .row = "00.04", .after = ""}, + {.var = "CONSOLE_MOMS_CALL", .value = 0, .row = "00.04", .after = "mom_heals_us"}, + {.var = "VAR_POKETCH_CAMPAIGN_STATE", .value = 1, .row = "00.05b", .after = ""}, + {.var = "VAR_ROUTE_203_RIVAL_STATE", .value = 0, .row = "01.01", .after = ""}, + {.var = "VAR_OREBURGH_GATE_1F_HIKER_STATE", .value = 1, .row = "01.02", .after = ""}, + {.var = "VAR_OREBURGH_CITY_STATE", .value = 0, .row = "01.02", .after = ""}, + {.var = "VAR_OREBURGH_CITY_STATE", .value = 2, .row = "01.05", .after = ""}, + {.var = "VAR_JUBILIFE_CITY_STATE", .value = 3, .row = "01.07", .after = ""}, + }; +} + +namespace{ + +// The maps' coord events (story_coord_events()) whose variable holds. +std::optional var_state(const CoordEvent& event){ + for (const VarState& state : story_vars()){ + if (state.var == event.var && state.value == event.value){ + return state; + } + } + return std::nullopt; +} + +RowTrigger row_trigger(const std::string& map, const CoordEvent& event, const VarState& state){ + return {.row = state.row, .after = state.after, .map = map, .trigger = {.name = event.name, .tiles = event.tiles}}; +} + +} // namespace + +std::vector story_triggers(){ + std::vector triggers; + for (const auto& [map, json] : bdsp_map_json()){ + for (const CoordEvent& event : story_coord_events(map)){ + const std::optional state = var_state(event); + if (state){ + triggers.push_back(row_trigger(map, event, *state)); + } + } + } + return triggers; +} + +namespace{ + +// Someone the maps do not have, on `tile` of `map`, talked to or walked round: +// from row `row` on, until row `until_row`'s step `until` has run if it is set. +struct SimPerson{ + std::string name; + std::string map; + TilePos tile; + std::string row; + std::string until_row = {}; + std::string until = {}; +}; +std::vector sim_people(){ + return { + // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). + {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04"}, + // Barry in the Gym's door, from the welcome (lab-B 2026-11-08) to his lines (r101, r104). + {.name = "barry", .map = "OreburghCity", .tile = {26, 21}, .row = "01.02b", .until_row = "01.02b", .until = "barrys_lines"}, + }; +} + +// A house's stairs, entered by a step `side` from the map's "stairs" +// point into what the map draws as a wall (the table's 00.01: r8 and r9 +// for ours, r11 for Barry's). +struct SimStairs{ + std::string map; + Direction side; +}; +std::vector sim_stairs(){ + return { + {.map = "PlayerHouse2F", .side = Direction::EAST}, + {.map = "RivalHouse1F", .side = Direction::EAST}, + {.map = "RivalHouse2F", .side = Direction::WEST}, + }; +} + +} // namespace + +// The world the player walks on for `map`: the planner's, with what the +// console showed that the maps lack. Nothing for a room with no map. +const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ + const StoryWorld* world = story_plan_world(map, map); + std::vector here; + std::string who; + for (const SimPerson& person : sim_people()){ + const bool now = m_row >= person.row && (person.until.empty() || m_row < person.until_row || + (m_row == person.until_row && !m_ran.contains(person.until))); + if (world != nullptr && now && story_plan_world(person.map, person.map) == world){ + here.push_back(person); + who += person.name + ";"; + } + } + const SimGround* ground = nullptr; + for (const SimGround& item : sim_ground()){ + if (world != nullptr && m_row >= item.row && story_plan_world(item.map, item.map) == world){ + ground = &item; + who += item.map + " ground;"; + } + } + if (who.empty()){ + return world; + } + std::unique_ptr& peopled = m_peopled[{world, who}]; + if (!peopled){ + peopled = ground != nullptr ? with_ground(*world, *ground) : std::make_unique(*world); + for (const SimPerson& person : here){ + peopled->block(story_to_world(*peopled, person.map, person.tile)); + } + } + return peopled.get(); +} + +SimWorld SimExecutor::setup(const StoryWorld* world) const{ + // B runs once the shoes' scene has given them: the scene ends at home. + SimWorld out{.world = world, .trainers = story_trainers(*world), .can_run = m_walks.can_run()}; + for (const SimStairs& stairs : sim_stairs()){ + if (sim_world(stairs.map) == world){ + out.doors.push_back(story_to_world(*world, stairs.map, map_point(stairs.map, "stairs").next(stairs.side))); + } + } + for (const RowTrigger& armed : m_armed){ + if (sim_world(armed.map) != world){ + continue; + } + SimTrigger trigger{.name = armed.trigger.name, .tiles = {}}; + for (const TilePos& pos : armed.trigger.tiles){ + trigger.tiles.push_back(story_to_world(*world, armed.map, pos)); + } + out.triggers.push_back(std::move(trigger)); + } + return out; +} + +// Arms the triggers of this row that start after `after`. +void SimExecutor::arm(const std::string& after){ + size_t armed = 0; + for (const RowTrigger& trigger : story_triggers()){ + if (trigger.row == m_row && trigger.after == after){ + m_armed.push_back(trigger); + armed++; + } + } + const SimPlayer& player = m_sim.player(); + if (armed > 0 && m_placed && on_grid(player.pos) && !player.dialog){ + m_sim.place(setup(&m_sim.world()), nearest_tile(player.pos), player.facing); + } +} + +// Puts the player on `pose`, on the world `on` if given, unless they stand +// on one of its tiles already. Returns whether the pose is on a map the +// simulation has. +bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ + const std::vector tiles = Pokemon::tiles_of(pose); + const StoryWorld* world = on != nullptr ? on : pose.map.empty() ? nullptr : sim_world(pose.map); + if (world == nullptr || tiles.empty()){ + return false; + } + const SimPlayer& player = m_sim.player(); + const std::optional local = !m_placed || &m_sim.world() != world + ? std::nullopt : story_to_local(*world, pose.map, nearest_tile(player.pos)); + if (local && on_grid(player.pos) && std::find(tiles.begin(), tiles.end(), *local) != tiles.end()){ + return true; + } + m_sim.place(setup(world), story_to_world(*world, pose.map, tiles.front()), Pokemon::facing_of(pose)); + m_placed = true; + return true; +} + +// Through a door or a cave mouth onto the step's far side, the player's +// facing kept: a hold goes on from there. +bool SimExecutor::cross(){ + const StoryWorld* world = m_far ? sim_world(m_far->map) : nullptr; + const std::vector tiles = m_far ? Pokemon::tiles_of(*m_far) : std::vector{}; + if (world == nullptr || tiles.empty()){ + return false; + } + m_sim.place(setup(world), story_to_world(*world, m_far->map, tiles.front()), std::nullopt); + return true; +} + +// Why the player does not stand on one of `pose`'s tiles, or "" if they +// do or the simulation cannot tell (no map, or not placed yet). +std::string SimExecutor::off_pose(const Pose& pose) const{ + const std::vector tiles = Pokemon::tiles_of(pose); + if (!m_placed || tiles.empty() || sim_world(pose.map) == nullptr){ + return ""; + } + const SimPlayer& player = m_sim.player(); + const TilePos at = nearest_tile(player.pos); + // In world tiles: a pose a leg worked out from the map it started on + // may lie past that map's edge, on the next map (Twinleaf's exit). + // story_to_world() throws for a map not on the player's world. + try{ + const auto there = [&](const TilePos& tile){ return story_to_world(m_sim.world(), pose.map, tile) == at; }; + if (on_grid(player.pos) && std::ranges::any_of(tiles, there)){ + return ""; + } + }catch (const InternalProgramError&){} + return std::format("ended at {} ({}), not on {}.", to_string(player.pos), describe(m_sim.world(), at), Pokemon::to_string(pose)); +} + +// The program's run into the Center: past its door, the inside shows, a missed fade or not. +Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ + if (!sync(state.pose)){ + return Pokemon::outcome_ok(); + } + run_into_center(m_io, m_walks.can_run(), [this]{ + m_misses.fade_unseen = false; + return m_sim.player().warped.has_value(); + }, [&]{ + throw GridSimFailure{step.name + ": no door north of " + to_string(m_sim.player().pos)}; + }); + return Pokemon::outcome_ok(); +} + +// Why a walking step did not end where the table says, or "". A step +// through a door the simulation did not cross is not checked: the sim's +// maps have no warps' destinations. +std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome){ + const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP; + const std::optional expected = step.pose_after ? step.pose_after : outcome.pose; + if (!walks || !m_placed){ + return ""; + } + if (!expected || Pokemon::tiles_of(*expected).empty()){ + m_result.unchecked.push_back(m_row + " " + step.name); + return ""; + } + const SimPlayer& player = m_sim.player(); + if (player.warped && !story_to_local(m_sim.world(), expected->map, nearest_tile(player.pos))){ + return ""; + } + return off_pose(*expected); +} + +Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ + if (!m_start_mismatch.empty()){ + return Pokemon::outcome_failed("sim_mismatch", "the row before " + std::exchange(m_start_mismatch, "")); + } + m_far = step.pose_after; + if (story_events().contains(step.variant)){ + return stub(); + } + // A scene goes on from where the step before left us. A route walks + // on the world it plans on (Jubilife alone has no Route 204 north of it). + const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || + step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK; + const StoryWorld* on = step.kind == StoryStepKind::ROUTE && step.target && !state.pose.map.empty() + ? story_plan_world(state.pose.map, step.target->map) : nullptr; + // A world of one map is sim_world()'s, with its people. + if (on != nullptr && on == story_plan_world(state.pose.map, state.pose.map)){ + on = nullptr; + } + if (walks && !sync(state.pose, on)){ + m_logger.log(std::format("[{}] {}: no map for {}; passed over.", m_row, step.name, Pokemon::to_string(state.pose))); + m_passed_over = true; + return Pokemon::outcome_ok(); + } + return Pokemon::StoryStepExecutor::run(state, step); +} + +Outcome SimExecutor::run(RunState& state, const StoryStep& step){ + Outcome outcome; + m_passed_over = false; + try{ + outcome = run_step(state, step); + }catch (const GridSimFailure& e){ + outcome = Pokemon::outcome_failed("sim_failure", e.message); + } + const std::string mismatch = outcome.succeeded() && !m_passed_over ? check(step, outcome) : ""; + if (!mismatch.empty()){ + outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); + } + // What the simulation does not play (scenes, events, battles) ends + // where the table says it does. + if (outcome.succeeded() && step.pose_after){ + sync(*step.pose_after); + } + m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); + if (std::exchange(m_misses.missed, false) && m_result.missed_step.empty()){ + m_result.missed_step = m_row + " " + step.name; + } + if (!outcome.succeeded() && m_result.error.empty()){ + // The walker's last notes, to see why. + for (size_t i = m_notes.size() - std::min(m_notes.size(), 40); i < m_notes.size(); i++){ + m_logger.log(std::format("[{}] note: {}", m_row, m_notes[i])); + } + m_result.error = m_row + " " + Pokemon::to_string(outcome); + m_result.failed_step = m_row + " " + step.name; + } + m_result.world = m_placed ? &m_sim.world() : nullptr; + m_result.end = nearest_tile(m_sim.player().pos); + m_ran.insert(step.name); + arm(step.name); + return outcome; +} + +// Runs `range` of `rows` (the table unless given) on `executor`, stopping +// at the first failure. +Pokemon::SegmentReport run_rows_on( + SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, + const std::vector& rows +){ + std::set saved; + Pokemon::Segment segment = make_story_segment(rows, executor, saved); + Pokemon::SegmentPolicy policy; + policy.stop_at_first_failure = true; + Pokemon::SegmentHooks hooks; + hooks.reload = [](RunState&){ return Pokemon::outcome_ok(); }; + hooks.log = [&logger](const std::string& line){ logger.log(line); }; + RunState state; + return Pokemon::run_segment(state, segment, range, policy, hooks); +} + +// Runs `range` of the table on the simulation, stopping at the first failure. +UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ + SimExecutor executor(logger); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, range); + for (const std::string& step : executor.result().unchecked){ + logger.log("No end to check after " + step + "."); + } + if (!report.completed){ + return std::format("stopped at {} {}: {}", report.failed_checkpoint, report.failed_event, executor.result().error); + } + return true; +} + +// The table with row `row`'s step of `step`'s name replaced by `step`. +std::vector table_with(const std::string& row, const StoryStep& step){ + std::vector rows = story_checkpoints(); + for (StoryCheckpoint& checkpoint : rows){ + for (StoryStep& old : checkpoint.steps){ + if (checkpoint.id == row && old.name == step.name){ + old = step; + return rows; + } + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + step.name + " in " + row); +} + +bool ends_on(const SimRun& run, const Pose& pose){ + const std::vector tiles = Pokemon::tiles_of(pose); + const std::optional local = run.world ? story_to_local(*run.world, pose.map, run.end) : std::nullopt; + return local && std::find(tiles.begin(), tiles.end(), *local) != tiles.end(); +} +std::string end_of(const SimRun& run){ + return run.world ? describe(*run.world, run.end) : "nowhere"; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h new file mode 100644 index 0000000000..7193ac8992 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -0,0 +1,292 @@ +/* BDSP AutoStory - Story simulation + * + * From: https://github.com/PokemonAutomation/ + * + * The story table's rows run as the program runs them (the segment + * runner, make_story_segment()), with the program's own walking steps + * (StoryWalkSteps) on the grid simulation; see StorySim_Tests.cpp for + * what is simulated and what is stubbed. Moved out of the tests so the + * console failure cases (SimFailureCases_Tests) run on the same executor. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StorySim_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StorySim_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_GridSim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Which detections the simulation misses on purpose (#162): the `fade`th +// door fade (run_into_door(), from 0) or the `banner`th map banner +// (run_until_map()) of the run goes unseen, though the player did go +// through. The console missed both (r75, r81). The `dark`th door run reads +// dark SIM_FALSE_DARK in, short of the door, as lab-B's did on 2026-11-08. +// The `through`th tap step (tap_to_banner(), from 0) starts on its far side, +// its banner gone unless `through_banner`: the walk before it slid onto the +// warp (lab-B 2026-11-08). The counts and flags below are the run's: how +// many fades and banners it looked for, whether a miss happened since the +// executor last looked, and whether a missed fade is still unseen. +struct SimMisses{ + std::optional fade; + std::optional banner; + std::optional dark = {}; + std::optional through = {}; + bool through_banner = false; + size_t tap_steps = 0; + size_t fades = 0; + size_t banners = 0; + size_t doors = 0; + bool missed = false; + bool fade_unseen = false; +}; + +// How many tiles a held walk goes on into a map before its location +// banner reads: "it shows a tile or a few past the border" (the table's +// route_201_by_the_path(), measured on the console). Standing still, it +// reads at once. Through a cave mouth the fade comes first, and a hold +// whose fade went unseen goes on the same way (r75, r81). +constexpr size_t SIM_BANNER_TILES = 3; +constexpr Milliseconds SIM_FALSE_DARK = Milliseconds(1800); + +// What a run on the simulation did. +struct SimRun{ + // The first failure, as "row outcome", or "". + std::string error; + // The rows and steps where an injected miss happened and where the run + // first failed, as "row step": "" if none. + std::string missed_step; + std::string failed_step; + // Walking steps that end where nothing says, as "row step". + std::vector unchecked; + // Each row run, with the fades and banners looked for before it. + struct RowStart{ + std::string row; + size_t fades; + size_t banners; + }; + std::vector rows; + // Where the player stood after the last step, if placed. + const StoryWorld* world = nullptr; + Pokemon::TilePos end; +}; + +// StoryStepIO on the simulation. A walk through a door or a cave mouth +// stops on its tile, as the console stops at the fade; a hold that misses +// the fade carries on, onto `far_side()` (the step's pose_after: the +// sim's maps have no warps' destinations) and on along it. +class SimStoryStepIO : public StoryStepIO{ +public: + SimStoryStepIO(GridSim& sim, std::vector& notes, SimMisses& misses, std::function far_side) + : m_sim(sim) + , m_route(sim, notes) + , m_misses(misses) + , m_far_side(std::move(far_side)) + {} + + virtual RouteIO& route() override{ + return m_route; + } + virtual void fight(const std::string&) override{ + m_sim.end_dialogue(); + } + virtual void walk_until_stopped(Pokemon::Direction direction, size_t tiles, const std::string& label) override; + virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; + virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) override{ + const SimPace pace = run ? SimPace::RUN : SimPace::WALK; + if (false_dark() && dark_from <= SIM_FALSE_DARK && SIM_FALSE_DARK < timeout){ + m_sim.hold(direction, SIM_FALSE_DARK, pace); + return true; + } + const bool warped = m_sim.hold(direction, timeout, pace).stop == SimStop::WARP; + if (warped && fade_missed()){ + m_misses.fade_unseen = true; + return false; + } + return warped; + } + // A scene may take us to another map (Mom walks us out, 00.04): with a + // dialogue open the stub scene plays it. Otherwise only a door fades. + // A fade missed on the way in stays missed: it was over before settle() + // looked, which then fails as it does on the console after 120 s. + virtual void settle(Button, const std::string& label, bool fade) override{ + const bool scene_fades = m_sim.player().dialog && m_far_side(); + if (fade && ((!m_sim.player().warped && !scene_fades) || m_misses.fade_unseen)){ + m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); + } + m_misses.fade_unseen = false; + m_sim.end_dialogue(); + } + virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) override; + +private: + // Whether the run misses this fade or this banner (SimMisses). + bool fade_missed(){ + const bool miss = m_misses.fade == m_misses.fades++; + m_misses.missed |= miss; + return miss; + } + bool false_dark(){ + const bool dark = m_misses.dark == m_misses.doors++; + m_misses.missed |= dark; + return dark; + } + bool banner_missed(){ + const bool miss = m_misses.banner == m_misses.banners++; + m_misses.missed |= miss; + return miss; + } + bool on_map(const std::string& map) const{ + return story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)).has_value(); + } + + GridSim& m_sim; + GridSimRouteIO m_route; + SimMisses& m_misses; + std::function m_far_side; +}; + +// A scene's trigger the simulation fires from row `row` on, once the step +// `after` has run ("" from the row's start), on `map`'s `tiles`. +struct RowTrigger{ + std::string row; + std::string after; + std::string map; + SimTrigger trigger; +}; + +// When a story variable holds the value its coord events wait for: from +// row `row` on, once the step `after` has run ("" from the row's start). +struct VarState{ + std::string var; + int value; + std::string row; + std::string after; +}; + +// The story variables whose coord events the table walks onto, and from +// which row and step each holds (the definition says why each). +std::vector story_vars(); +// The maps' coord events whose story variable holds, as triggers. +std::vector story_triggers(); + +// The program's walking steps on the simulation, the rest stubbed. +class SimExecutor : public Pokemon::StoryStepExecutor{ +public: + explicit SimExecutor(Logger& logger, SimMisses misses = {}) + : m_logger(logger) + , m_misses(misses) + , m_sim({}, {0, 0}, Pokemon::Direction::NORTH, false) + , m_io(m_sim, m_notes, m_misses, [this]{ return cross(); }) + , m_walks(m_io) + {} + + const SimMisses& misses() const{ + return m_misses; + } + const SimRun& result() const{ + return m_result; + } + virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ + m_row = data.id; + m_start_mismatch = data.start ? off_pose(*data.start) : ""; + m_ran.clear(); + m_result.rows.push_back({.row = data.id, .fades = m_misses.fades, .banners = m_misses.banners}); + m_walks.begin_attempt(data.id); + arm(""); + } + virtual Pokemon::Outcome run(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; + +protected: + virtual Pokemon::Outcome route(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.route(state, step); } + virtual Pokemon::Outcome legs(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.legs(state, step); } + virtual Pokemon::Outcome step(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.step(state, step); } + virtual Pokemon::Outcome talk(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.talk(state, step); } + virtual Pokemon::Outcome mash(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.mash(state, step); } + virtual Pokemon::Outcome heal(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; + virtual Pokemon::Outcome new_game(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome options(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome answer(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome battle(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome train(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome shop(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome save(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome game(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + +private: + // A step the simulation does not play: its dialogue opened and closed. + Pokemon::Outcome stub(){ + m_sim.end_dialogue(); + return Pokemon::outcome_ok(); + } + const StoryWorld* sim_world(const std::string& map) const; + SimWorld setup(const StoryWorld* world) const; + void arm(const std::string& after); + bool sync(const Pokemon::Pose& pose, const StoryWorld* on = nullptr); + bool cross(); + std::string off_pose(const Pokemon::Pose& pose) const; + std::string check(const Pokemon::StoryStep& step, const Pokemon::Outcome& outcome); + Pokemon::Outcome run_step(Pokemon::RunState& state, const Pokemon::StoryStep& step); + + Logger& m_logger; + std::vector m_notes; + SimMisses m_misses; + GridSim m_sim; + SimStoryStepIO m_io; + StoryWalkSteps m_walks; + // The planner's worlds with sim_people() and sim_ground() on them, by world and who. + mutable std::map, std::unique_ptr> m_peopled; + // The steps of this row that have run. + std::set m_ran; + std::string m_row; + std::vector m_armed; + // Where the step running now ends, if it says: a door's far side. + std::optional m_far; + // Why the player is not on this row's start, or "". + std::string m_start_mismatch; + // Whether the player has been put on a map yet. + bool m_placed = false; + // Whether the step running now is on a room with no map. + bool m_passed_over = false; + SimRun m_result; +}; + +// Runs `range` of `rows` (the table unless given) on `executor`, stopping +// at the first failure. +Pokemon::SegmentReport run_rows_on( + SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, + const std::vector& rows = story_checkpoints() +); +// Runs `range` of the table on the simulation, stopping at the first failure. +UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range); +// The table with row `row`'s step of `step`'s name replaced by `step`. +std::vector table_with(const std::string& row, const Pokemon::StoryStep& step); +// Whether the run ended on one of `pose`'s tiles. +bool ends_on(const SimRun& run, const Pokemon::Pose& pose); +// Where the run ended, described; "nowhere" if never placed. +std::string end_of(const SimRun& run); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index a1d993191b..5097b78bca 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -50,6 +50,7 @@ #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_StorySim.h" #include "PokemonBDSP_AutoStory_StorySim_Tests.h" namespace PokemonAutomation{ @@ -67,668 +68,6 @@ using Pokemon::StoryStep; using Pokemon::StoryStepKind; using Pokemon::TilePos; -// Which detections the simulation misses on purpose (#162): the `fade`th -// door fade (run_into_door(), from 0) or the `banner`th map banner -// (run_until_map()) of the run goes unseen, though the player did go -// through. The console missed both (r75, r81). The `dark`th door run reads -// dark SIM_FALSE_DARK in, short of the door, as lab-B's did on 2026-11-08. -// The `through`th tap step (tap_to_banner(), from 0) starts on its far side, -// its banner gone unless `through_banner`: the walk before it slid onto the -// warp (lab-B 2026-11-08). The counts and flags below are the run's: how -// many fades and banners it looked for, whether a miss happened since the -// executor last looked, and whether a missed fade is still unseen. -struct SimMisses{ - std::optional fade; - std::optional banner; - std::optional dark = {}; - std::optional through = {}; - bool through_banner = false; - size_t tap_steps = 0; - size_t fades = 0; - size_t banners = 0; - size_t doors = 0; - bool missed = false; - bool fade_unseen = false; -}; - -// How many tiles a held walk goes on into a map before its location -// banner reads: "it shows a tile or a few past the border" (the table's -// route_201_by_the_path(), measured on the console). Standing still, it -// reads at once. Through a cave mouth the fade comes first, and a hold -// whose fade went unseen goes on the same way (r75, r81). -constexpr size_t SIM_BANNER_TILES = 3; -constexpr Milliseconds SIM_FALSE_DARK = 1800ms; - -// What a run on the simulation did. -struct SimRun{ - // The first failure, as "row outcome", or "". - std::string error; - // The rows and steps where an injected miss happened and where the run - // first failed, as "row step": "" if none. - std::string missed_step; - std::string failed_step; - // Walking steps that end where nothing says, as "row step". - std::vector unchecked; - // Each row run, with the fades and banners looked for before it. - struct RowStart{ - std::string row; - size_t fades; - size_t banners; - }; - std::vector rows; - // Where the player stood after the last step, if placed. - const StoryWorld* world = nullptr; - TilePos end; -}; - -// StoryStepIO on the simulation. A walk through a door or a cave mouth -// stops on its tile, as the console stops at the fade; a hold that misses -// the fade carries on, onto `far_side()` (the step's pose_after: the -// sim's maps have no warps' destinations) and on along it. -class SimStoryStepIO : public StoryStepIO{ -public: - SimStoryStepIO(GridSim& sim, std::vector& notes, SimMisses& misses, std::function far_side) - : m_sim(sim) - , m_route(sim, notes) - , m_misses(misses) - , m_far_side(std::move(far_side)) - {} - - virtual RouteIO& route() override{ - return m_route; - } - virtual void fight(const std::string&) override{ - m_sim.end_dialogue(); - } - virtual void walk_until_stopped(Direction direction, size_t tiles, const std::string& label) override; - virtual bool run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; - virtual bool run_into_door(Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) override{ - const SimPace pace = run ? SimPace::RUN : SimPace::WALK; - if (false_dark() && dark_from <= SIM_FALSE_DARK && SIM_FALSE_DARK < timeout){ - m_sim.hold(direction, SIM_FALSE_DARK, pace); - return true; - } - const bool warped = m_sim.hold(direction, timeout, pace).stop == SimStop::WARP; - if (warped && fade_missed()){ - m_misses.fade_unseen = true; - return false; - } - return warped; - } - // A scene may take us to another map (Mom walks us out, 00.04): with a - // dialogue open the stub scene plays it. Otherwise only a door fades. - // A fade missed on the way in stays missed: it was over before settle() - // looked, which then fails as it does on the console after 120 s. - virtual void settle(Button, const std::string& label, bool fade) override{ - const bool scene_fades = m_sim.player().dialog && m_far_side(); - if (fade && ((!m_sim.player().warped && !scene_fades) || m_misses.fade_unseen)){ - m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); - } - m_misses.fade_unseen = false; - m_sim.end_dialogue(); - } - virtual std::optional tap_to_banner(Direction direction, const std::string& map, size_t max_taps) override; - -private: - // Whether the run misses this fade or this banner (SimMisses). - bool fade_missed(){ - const bool miss = m_misses.fade == m_misses.fades++; - m_misses.missed |= miss; - return miss; - } - bool false_dark(){ - const bool dark = m_misses.dark == m_misses.doors++; - m_misses.missed |= dark; - return dark; - } - bool banner_missed(){ - const bool miss = m_misses.banner == m_misses.banners++; - m_misses.missed |= miss; - return miss; - } - bool on_map(const std::string& map) const{ - return story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)).has_value(); - } - - GridSim& m_sim; - GridSimRouteIO m_route; - SimMisses& m_misses; - std::function m_far_side; -}; - -// A hold until something stops us. A door stops it at the fade, which -// fails the step; a fade missed lets the hold go on past the mouth (r81's -// timed walk south out of the Ravaged Path, onto Route 204's cliff). -void SimStoryStepIO::walk_until_stopped(Direction direction, size_t tiles, const std::string& label){ - m_sim.tap(direction, ROUTE_TURN_TAP, false); - Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); - SimMove move = m_sim.hold(direction, limit, SimPace::WALK); - if (move.stop == SimStop::WARP && fade_missed() && m_far_side()){ - limit -= std::min(limit, move.time); - move = m_sim.hold(direction, limit, SimPace::WALK); - } - if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ - m_route.note(label + ": " + sim_stop_name(move.stop) + " instead of a stop.", RouteNote::FAILURE); - } -} - -// The D-pad, a tile at a time, until `map`'s banner reads; through a door -// the walk goes on beyond it (the fade eats no tiles of a hold). -bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&){ - const bool miss = banner_missed(); - size_t on = 0; - for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ - SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); - const bool crossed = move.stop == SimStop::WARP && m_far_side(); - const bool stopped = !crossed && (move.distance == 0 || move.stop != SimStop::DONE); - on = on_map(map) ? on + 1 : 0; - if (on > 0 && (on > SIM_BANNER_TILES || stopped) && !miss){ - return true; - } - if (stopped){ - return false; - } - } - return false; -} - -// D-pad taps, each looked at, until the fade and then the banner (the -// console's ConsoleStoryStepIO::tap_to_banner()): none if the banner shows -// before the first. Each look stands still, so a banner on the far side -// reads at once. A fade seen ends the taps, -// banner or not; with the fade missed the next look still sees the banner. -std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ - if (m_misses.through == m_misses.tap_steps++){ - m_misses.missed = true; - if (m_far_side() && m_misses.through_banner){ - return 0; - } - } - bool crossed = false; - for (size_t tap = 1; tap <= max_taps; tap++){ - const SimMove move = m_sim.tap(direction, 160ms, false); - if (move.stop == SimStop::DIALOG){ - return std::nullopt; - } - bool faded = false; - if (move.stop == SimStop::WARP){ - faded = !fade_missed(); - crossed = m_far_side(); - } - if (crossed && on_map(map) && !banner_missed()){ - return tap; - } - if (faded){ - return std::nullopt; - } - } - return std::nullopt; -} - -// A scene's trigger the simulation fires from row `row` on, once the step -// `after` has run ("" from the row's start), on `map`'s `tiles`. -struct RowTrigger{ - std::string row; - std::string after; - std::string map; - SimTrigger trigger; -}; - -// When a story variable holds the value its coord events wait for: from -// row `row` on, once the step `after` has run ("" from the row's start). -struct VarState{ - std::string var; - int value; - std::string row; - std::string after; -}; - -// The story variables whose coord events the table walks onto, from the -// row (and step) the table's reasons give, with the maps' coord events -// (Diamond's zone events; Platinum's for the houses): Barry's doorstep and -// Mom's warning in 00.01, Barry's Route 201 warning, then its pull-back -// row 19 once he has warned us (r14, r16); the lake's entrance in 00.02; -// Rowan's stop and Dawn at Sandgem's edge in 00.03; Dawn's catching -// tutorial on Route 202 from 00.04's start, Mom's call once she has healed -// us; the Poketch president on Jubilife's row 40 in 00.05b; Barry on Route -// 203 in 01.01; the Gate's Hiker and Oreburgh's welcome in 01.02; Barry's -// bump in Oreburgh after Roark in 01.05; and Rowan in Jubilife in 01.07. -// Left out: the Twinleaf guitarist (spent upstairs), Platinum's rival -// steps around our bedroom's start, Dawn at Jubilife's steps (BDSP starts -// her below them: an event), and Floaroma's (10..12, 29) (Diamond only). -std::vector story_vars(){ - return { - {.var = "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", .value = 0, .row = "00.01", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 0, .row = "00.01", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 1, .row = "00.01", .after = "barry_warns_us"}, - {.var = "VAR_VERITY_LAKEFRONT_STATE", .value = 0, .row = "00.02", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 2, .row = "00.03", .after = ""}, - {.var = "VAR_SANDGEM_TOWN_STATE", .value = 0, .row = "00.03", .after = ""}, - {.var = "VAR_ROUTE_202_STATE", .value = 0, .row = "00.04", .after = ""}, - {.var = "CONSOLE_MOMS_CALL", .value = 0, .row = "00.04", .after = "mom_heals_us"}, - {.var = "VAR_POKETCH_CAMPAIGN_STATE", .value = 1, .row = "00.05b", .after = ""}, - {.var = "VAR_ROUTE_203_RIVAL_STATE", .value = 0, .row = "01.01", .after = ""}, - {.var = "VAR_OREBURGH_GATE_1F_HIKER_STATE", .value = 1, .row = "01.02", .after = ""}, - {.var = "VAR_OREBURGH_CITY_STATE", .value = 0, .row = "01.02", .after = ""}, - {.var = "VAR_OREBURGH_CITY_STATE", .value = 2, .row = "01.05", .after = ""}, - {.var = "VAR_JUBILIFE_CITY_STATE", .value = 3, .row = "01.07", .after = ""}, - }; -} - -// The maps' coord events (story_coord_events()) whose variable holds. -std::optional var_state(const CoordEvent& event){ - for (const VarState& state : story_vars()){ - if (state.var == event.var && state.value == event.value){ - return state; - } - } - return std::nullopt; -} - -RowTrigger row_trigger(const std::string& map, const CoordEvent& event, const VarState& state){ - return {.row = state.row, .after = state.after, .map = map, .trigger = {.name = event.name, .tiles = event.tiles}}; -} - -std::vector story_triggers(){ - std::vector triggers; - for (const auto& [map, json] : bdsp_map_json()){ - for (const CoordEvent& event : story_coord_events(map)){ - const std::optional state = var_state(event); - if (state){ - triggers.push_back(row_trigger(map, event, *state)); - } - } - } - return triggers; -} - -// Someone the maps do not have, on `tile` of `map`, talked to or walked round: -// from row `row` on, until row `until_row`'s step `until` has run if it is set. -struct SimPerson{ - std::string name; - std::string map; - TilePos tile; - std::string row; - std::string until_row = {}; - std::string until = {}; -}; -std::vector sim_people(){ - return { - // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). - {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04"}, - // Barry in the Gym's door, from the welcome (lab-B 2026-11-08) to his lines (r101, r104). - {.name = "barry", .map = "OreburghCity", .tile = {26, 21}, .row = "01.02b", .until_row = "01.02b", .until = "barrys_lines"}, - }; -} - -// A house's stairs, entered by a step `side` from the map's "stairs" -// point into what the map draws as a wall (the table's 00.01: r8 and r9 -// for ours, r11 for Barry's). -struct SimStairs{ - std::string map; - Direction side; -}; -std::vector sim_stairs(){ - return { - {.map = "PlayerHouse2F", .side = Direction::EAST}, - {.map = "RivalHouse1F", .side = Direction::EAST}, - {.map = "RivalHouse2F", .side = Direction::WEST}, - }; -} - -// The program's walking steps on the simulation, the rest stubbed. -class SimExecutor : public Pokemon::StoryStepExecutor{ -public: - explicit SimExecutor(Logger& logger, SimMisses misses = {}) - : m_logger(logger) - , m_misses(misses) - , m_sim({}, {0, 0}, Direction::NORTH, false) - , m_io(m_sim, m_notes, m_misses, [this]{ return cross(); }) - , m_walks(m_io) - {} - - const SimMisses& misses() const{ - return m_misses; - } - const SimRun& result() const{ - return m_result; - } - virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ - m_row = data.id; - m_start_mismatch = data.start ? off_pose(*data.start) : ""; - m_ran.clear(); - m_result.rows.push_back({.row = data.id, .fades = m_misses.fades, .banners = m_misses.banners}); - m_walks.begin_attempt(data.id); - arm(""); - } - virtual Outcome run(RunState& state, const StoryStep& step) override; - -protected: - virtual Outcome route(RunState& state, const StoryStep& step) override{ return m_walks.route(state, step); } - virtual Outcome legs(RunState& state, const StoryStep& step) override{ return m_walks.legs(state, step); } - virtual Outcome step(RunState& state, const StoryStep& step) override{ return m_walks.step(state, step); } - virtual Outcome talk(RunState& state, const StoryStep& step) override{ return m_walks.talk(state, step); } - virtual Outcome mash(RunState& state, const StoryStep& step) override{ return m_walks.mash(state, step); } - virtual Outcome heal(RunState& state, const StoryStep& step) override; - virtual Outcome new_game(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome options(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome answer(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome battle(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome train(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome shop(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome save(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome game(RunState&, const StoryStep&) override{ return stub(); } - -private: - // A step the simulation does not play: its dialogue opened and closed. - Outcome stub(){ - m_sim.end_dialogue(); - return Pokemon::outcome_ok(); - } - const StoryWorld* sim_world(const std::string& map) const; - SimWorld setup(const StoryWorld* world) const; - void arm(const std::string& after); - bool sync(const Pose& pose, const StoryWorld* on = nullptr); - bool cross(); - std::string off_pose(const Pose& pose) const; - std::string check(const StoryStep& step, const Outcome& outcome); - Outcome run_step(RunState& state, const StoryStep& step); - - Logger& m_logger; - std::vector m_notes; - SimMisses m_misses; - GridSim m_sim; - SimStoryStepIO m_io; - StoryWalkSteps m_walks; - // The planner's worlds with sim_people() and sim_ground() on them, by world and who. - mutable std::map, std::unique_ptr> m_peopled; - // The steps of this row that have run. - std::set m_ran; - std::string m_row; - std::vector m_armed; - // Where the step running now ends, if it says: a door's far side. - std::optional m_far; - // Why the player is not on this row's start, or "". - std::string m_start_mismatch; - // Whether the player has been put on a map yet. - bool m_placed = false; - // Whether the step running now is on a room with no map. - bool m_passed_over = false; - SimRun m_result; -}; - -// The world the player walks on for `map`: the planner's, with what the -// console showed that the maps lack. Nothing for a room with no map. -const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ - const StoryWorld* world = story_plan_world(map, map); - std::vector here; - std::string who; - for (const SimPerson& person : sim_people()){ - const bool now = m_row >= person.row && (person.until.empty() || m_row < person.until_row || - (m_row == person.until_row && !m_ran.contains(person.until))); - if (world != nullptr && now && story_plan_world(person.map, person.map) == world){ - here.push_back(person); - who += person.name + ";"; - } - } - const SimGround* ground = nullptr; - for (const SimGround& item : sim_ground()){ - if (world != nullptr && m_row >= item.row && story_plan_world(item.map, item.map) == world){ - ground = &item; - who += item.map + " ground;"; - } - } - if (who.empty()){ - return world; - } - std::unique_ptr& peopled = m_peopled[{world, who}]; - if (!peopled){ - peopled = ground != nullptr ? with_ground(*world, *ground) : std::make_unique(*world); - for (const SimPerson& person : here){ - peopled->block(story_to_world(*peopled, person.map, person.tile)); - } - } - return peopled.get(); -} - -SimWorld SimExecutor::setup(const StoryWorld* world) const{ - // B runs once the shoes' scene has given them: the scene ends at home. - SimWorld out{.world = world, .trainers = story_trainers(*world), .can_run = m_walks.can_run()}; - for (const SimStairs& stairs : sim_stairs()){ - if (sim_world(stairs.map) == world){ - out.doors.push_back(story_to_world(*world, stairs.map, map_point(stairs.map, "stairs").next(stairs.side))); - } - } - for (const RowTrigger& armed : m_armed){ - if (sim_world(armed.map) != world){ - continue; - } - SimTrigger trigger{.name = armed.trigger.name, .tiles = {}}; - for (const TilePos& pos : armed.trigger.tiles){ - trigger.tiles.push_back(story_to_world(*world, armed.map, pos)); - } - out.triggers.push_back(std::move(trigger)); - } - return out; -} - -// Arms the triggers of this row that start after `after`. -void SimExecutor::arm(const std::string& after){ - size_t armed = 0; - for (const RowTrigger& trigger : story_triggers()){ - if (trigger.row == m_row && trigger.after == after){ - m_armed.push_back(trigger); - armed++; - } - } - const SimPlayer& player = m_sim.player(); - if (armed > 0 && m_placed && on_grid(player.pos) && !player.dialog){ - m_sim.place(setup(&m_sim.world()), nearest_tile(player.pos), player.facing); - } -} - -// Puts the player on `pose`, on the world `on` if given, unless they stand -// on one of its tiles already. Returns whether the pose is on a map the -// simulation has. -bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ - const std::vector tiles = Pokemon::tiles_of(pose); - const StoryWorld* world = on != nullptr ? on : pose.map.empty() ? nullptr : sim_world(pose.map); - if (world == nullptr || tiles.empty()){ - return false; - } - const SimPlayer& player = m_sim.player(); - const std::optional local = !m_placed || &m_sim.world() != world - ? std::nullopt : story_to_local(*world, pose.map, nearest_tile(player.pos)); - if (local && on_grid(player.pos) && std::find(tiles.begin(), tiles.end(), *local) != tiles.end()){ - return true; - } - m_sim.place(setup(world), story_to_world(*world, pose.map, tiles.front()), Pokemon::facing_of(pose)); - m_placed = true; - return true; -} - -// Through a door or a cave mouth onto the step's far side, the player's -// facing kept: a hold goes on from there. -bool SimExecutor::cross(){ - const StoryWorld* world = m_far ? sim_world(m_far->map) : nullptr; - const std::vector tiles = m_far ? Pokemon::tiles_of(*m_far) : std::vector{}; - if (world == nullptr || tiles.empty()){ - return false; - } - m_sim.place(setup(world), story_to_world(*world, m_far->map, tiles.front()), std::nullopt); - return true; -} - -// Why the player does not stand on one of `pose`'s tiles, or "" if they -// do or the simulation cannot tell (no map, or not placed yet). -std::string SimExecutor::off_pose(const Pose& pose) const{ - const std::vector tiles = Pokemon::tiles_of(pose); - if (!m_placed || tiles.empty() || sim_world(pose.map) == nullptr){ - return ""; - } - const SimPlayer& player = m_sim.player(); - const TilePos at = nearest_tile(player.pos); - // In world tiles: a pose a leg worked out from the map it started on - // may lie past that map's edge, on the next map (Twinleaf's exit). - // story_to_world() throws for a map not on the player's world. - try{ - const auto there = [&](const TilePos& tile){ return story_to_world(m_sim.world(), pose.map, tile) == at; }; - if (on_grid(player.pos) && std::ranges::any_of(tiles, there)){ - return ""; - } - }catch (const InternalProgramError&){} - return std::format("ended at {} ({}), not on {}.", to_string(player.pos), describe(m_sim.world(), at), Pokemon::to_string(pose)); -} - -// The program's run into the Center: past its door, the inside shows, a missed fade or not. -Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ - if (!sync(state.pose)){ - return Pokemon::outcome_ok(); - } - run_into_center(m_io, m_walks.can_run(), [this]{ - m_misses.fade_unseen = false; - return m_sim.player().warped.has_value(); - }, [&]{ - throw GridSimFailure{step.name + ": no door north of " + to_string(m_sim.player().pos)}; - }); - return Pokemon::outcome_ok(); -} - -// Why a walking step did not end where the table says, or "". A step -// through a door the simulation did not cross is not checked: the sim's -// maps have no warps' destinations. -std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome){ - const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP; - const std::optional expected = step.pose_after ? step.pose_after : outcome.pose; - if (!walks || !m_placed){ - return ""; - } - if (!expected || Pokemon::tiles_of(*expected).empty()){ - m_result.unchecked.push_back(m_row + " " + step.name); - return ""; - } - const SimPlayer& player = m_sim.player(); - if (player.warped && !story_to_local(m_sim.world(), expected->map, nearest_tile(player.pos))){ - return ""; - } - return off_pose(*expected); -} - -Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ - if (!m_start_mismatch.empty()){ - return Pokemon::outcome_failed("sim_mismatch", "the row before " + std::exchange(m_start_mismatch, "")); - } - m_far = step.pose_after; - if (story_events().contains(step.variant)){ - return stub(); - } - // A scene goes on from where the step before left us. A route walks - // on the world it plans on (Jubilife alone has no Route 204 north of it). - const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || - step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK; - const StoryWorld* on = step.kind == StoryStepKind::ROUTE && step.target && !state.pose.map.empty() - ? story_plan_world(state.pose.map, step.target->map) : nullptr; - // A world of one map is sim_world()'s, with its people. - if (on != nullptr && on == story_plan_world(state.pose.map, state.pose.map)){ - on = nullptr; - } - if (walks && !sync(state.pose, on)){ - m_logger.log(std::format("[{}] {}: no map for {}; passed over.", m_row, step.name, Pokemon::to_string(state.pose))); - m_passed_over = true; - return Pokemon::outcome_ok(); - } - return Pokemon::StoryStepExecutor::run(state, step); -} - -Outcome SimExecutor::run(RunState& state, const StoryStep& step){ - Outcome outcome; - m_passed_over = false; - try{ - outcome = run_step(state, step); - }catch (const GridSimFailure& e){ - outcome = Pokemon::outcome_failed("sim_failure", e.message); - } - const std::string mismatch = outcome.succeeded() && !m_passed_over ? check(step, outcome) : ""; - if (!mismatch.empty()){ - outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); - } - // What the simulation does not play (scenes, events, battles) ends - // where the table says it does. - if (outcome.succeeded() && step.pose_after){ - sync(*step.pose_after); - } - m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); - if (std::exchange(m_misses.missed, false) && m_result.missed_step.empty()){ - m_result.missed_step = m_row + " " + step.name; - } - if (!outcome.succeeded() && m_result.error.empty()){ - // The walker's last notes, to see why. - for (size_t i = m_notes.size() - std::min(m_notes.size(), 40); i < m_notes.size(); i++){ - m_logger.log(std::format("[{}] note: {}", m_row, m_notes[i])); - } - m_result.error = m_row + " " + Pokemon::to_string(outcome); - m_result.failed_step = m_row + " " + step.name; - } - m_result.world = m_placed ? &m_sim.world() : nullptr; - m_result.end = nearest_tile(m_sim.player().pos); - m_ran.insert(step.name); - arm(step.name); - return outcome; -} - -// Runs `range` of `rows` (the table unless given) on `executor`, stopping -// at the first failure. -Pokemon::SegmentReport run_rows_on( - SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, - const std::vector& rows = story_checkpoints() -){ - std::set saved; - Pokemon::Segment segment = make_story_segment(rows, executor, saved); - Pokemon::SegmentPolicy policy; - policy.stop_at_first_failure = true; - Pokemon::SegmentHooks hooks; - hooks.reload = [](RunState&){ return Pokemon::outcome_ok(); }; - hooks.log = [&logger](const std::string& line){ logger.log(line); }; - RunState state; - return Pokemon::run_segment(state, segment, range, policy, hooks); -} - -// Runs `range` of the table on the simulation, stopping at the first failure. -UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ - SimExecutor executor(logger); - const Pokemon::SegmentReport report = run_rows_on(executor, logger, range); - for (const std::string& step : executor.result().unchecked){ - logger.log("No end to check after " + step + "."); - } - if (!report.completed){ - return std::format("stopped at {} {}: {}", report.failed_checkpoint, report.failed_event, executor.result().error); - } - return true; -} - -// The table with row `row`'s step of `step`'s name replaced by `step`. -std::vector table_with(const std::string& row, const StoryStep& step){ - std::vector rows = story_checkpoints(); - for (StoryCheckpoint& checkpoint : rows){ - for (StoryStep& old : checkpoint.steps){ - if (checkpoint.id == row && old.name == step.name){ - old = step; - return rows; - } - } - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + step.name + " in " + row); -} - -bool ends_on(const SimRun& run, const Pose& pose){ - const std::vector tiles = Pokemon::tiles_of(pose); - const std::optional local = run.world ? story_to_local(*run.world, pose.map, run.end) : std::nullopt; - return local && std::find(tiles.begin(), tiles.end(), *local) != tiles.end(); -} -std::string end_of(const SimRun& run){ - return run.world ? describe(*run.world, run.end) : "nowhere"; -} - UnitTestResult run_exit_test(Logger& logger, const std::string& row_id, const StoryStep& old_step, const SimMisses& misses, const Pose& overshoot){ SimExecutor executor(logger, misses); const std::vector rows = table_with(row_id, old_step); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 3cf67423fd..9d38d35b83 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1714,6 +1714,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp From ca4d9ab7557c4fac4d1cef487501dc1fcec9160f Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 19:41:21 -0800 Subject: [PATCH 2/2] BDSP AutoStory: console failure cases on the story sim, known failing until fixed Sim knobs (SimWorldKnobs, all off unless a case sets them): - slides: an open leg's taps run on; onto a warp the walk sees the fade as it looks to its watchers (black: TRANSITION, dim: nothing, white: a wild battle), and the far map's banner is up or gone for the next step; - floor and fade brightness per map, judged by the program's tap_faded(); - wanderers: everyone with a wander box on the maps walks it, seeded; - late first lines for a talk. SimFailureCases_Tests runs one case per console failure. Those the program fails today are on KNOWN_FAILING with the change that is to fix them; their tests pass while they still fail and fail once they pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 2 + ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 275 ++++++++++++++++++ ...emonBDSP_AutoStory_SimFailureCases_Tests.h | 27 ++ .../PokemonBDSP_AutoStory_StorySim.cpp | 136 ++++++++- .../PokemonBDSP_AutoStory_StorySim.h | 113 ++++++- SerialPrograms/cmake/SourceFiles.cmake | 2 + 6 files changed, 541 insertions(+), 14 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index 72c29a2fa1..04fa3274c4 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -7,6 +7,7 @@ #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.h" +#include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h" @@ -40,6 +41,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_GridSim(database); add_tests_AutoStory_RecoveryWalk(database); add_tests_AutoStory_StorySim(database); + add_tests_AutoStory_SimFailureCases(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp new file mode 100644 index 0000000000..9dd3fd9b47 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -0,0 +1,275 @@ +/* BDSP AutoStory - Console failure cases on the story simulation + * + * From: https://github.com/PokemonAutomation/ + * + * One case per failure console B showed in its events and perception + * (#268's design note, the planner note), run on the story simulation + * with the knobs that make it happen there (SimWorldKnobs, SimMisses): + * walks that slide on onto a warp, fades the walks' watchers miss or read + * as a battle, banners missed or gone, dim floors, late first lines and + * people who wander. + * + * A case the program fails today is on KNOWN_FAILING with the change that + * is to fix it. Its test passes while the case still fails, and fails + * once the case passes: then take it off the list. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_StorySim.h" +#include "PokemonBDSP_AutoStory_SimFailureCases_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +namespace{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::Pose; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + +// Cases the program fails today, with what is to fix each. +const std::map KNOWN_FAILING{ + {"01.05 old walk slides onto the Gate's west mouth, dim fade, banner gone", "#268 slice 2: walkers report warps"}, + {"01.05 old walk slides onto the Gate's west mouth, black fade", "#268 slice 2: walkers report warps"}, + {"01.05 old walk slides onto the Gate's west mouth, white fade", "#268 slices 2 and 3: a fade watcher that tells white from a battle"}, + {"01.05 through_the_gate is one run west", "planner: goal kinds and ms costs (PLANNER_DESIGN.md)"}, + {"any one missed fade or banner from 00.00 to 01.11: every row still passes", "#268 slice 1: door arrival = fade or banner"}, + {"01.08 with Route 204's youngster wandering (12..14, 2)", "planner: one recovery rule, a sidestep round a wanderer (PLANNER_DESIGN.md 4, 7)"}, +}; + +// The table's step `name` in row `row`. +const StoryStep& table_step(const std::string& row, const std::string& name){ + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + for (const StoryStep& step : checkpoint.steps){ + if (checkpoint.id == row && step.name == name){ + return step; + } + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + name + " in " + row); +} + +// Runs rows `from` to `to` of `rows` with `misses` and `knobs`: "" if they +// all pass, else where and why the run stopped. +std::string run_case( + Logger& logger, const std::string& from, const std::string& to, + SimMisses misses, SimWorldKnobs knobs, const std::vector& rows = story_checkpoints() +){ + SimExecutor executor(logger, std::move(misses), std::move(knobs)); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = from, .to = to}, rows); + return report.completed ? "" : std::format("stopped in {}: {}", executor.result().failed_step, executor.result().error); +} +UnitTestResult passes(const std::string& stopped){ + return stopped.empty() ? UnitTestResult(true) : UnitTestResult(stopped); +} + +// The old 01.05 walk west along row 22 to the tile beside the west mouth's +// warp (3, 22), as before #269 stopped routes two short of warps. +StoryStep old_walk_beside_the_west_mouth(){ + StoryStep step = table_step("01.05", "through_the_gate"); + step.target = Pokemon::tile_pose("OreburghGate", {TilePos{4, 22}}, Direction::WEST); + return step; +} + +// 01.05's walk west through the Gate whose last open leg runs a tile on; +// the old walk's slides onto the west mouth's warp to Route 203. +SimWorldKnobs gate_slide(SimFade fade, bool banner_up){ + const Pose far = *table_step("01.05", "out_of_oreburgh_gate").pose_after; + return {.slides = {{.step = "through_the_gate", .direction = Direction::WEST, .tiles = 1, + .far = far, .fade = fade, .banner_up = banner_up}}}; +} +UnitTestResult gate_old_walk_slides(Logger& logger, SimFade fade, bool banner_up){ + const std::vector rows = table_with("01.05", old_walk_beside_the_west_mouth()); + return passes(run_case(logger, "01.05", "01.05", {.fade = {}, .banner = {}}, gate_slide(fade, banner_up), rows)); +} + +// The planner's legs for 01.05's walk through the Gate: one run west +// along row 22 works on the console; at most a hold to find the row first. +UnitTestResult gate_plan_one_run(Logger& logger){ + const StoryWorld* world = story_plan_world("OreburghGate", "OreburghGate"); + const std::vector from{story_to_world(*world, "OreburghGate", {27, 22}), story_to_world(*world, "OreburghGate", {26, 22})}; + const TilePos goal = story_to_world(*world, "OreburghGate", {5, 22}); + const auto plan = plan_recovered_route(*world, from, [&](const TilePos& pos){ return pos == goal; }, *story_route_costs(table_step("01.05", "through_the_gate").variant)); + if (!plan){ + return "no plan"; + } + std::string legs; + for (const PlannedLeg& leg : *plan){ + legs += (legs.empty() ? "" : ", ") + to_string(leg.leg); + } + logger.log("through_the_gate plans: " + legs); + return plan->size() <= 2 ? UnitTestResult(true) : UnitTestResult(std::format("{} legs: {}", plan->size(), legs)); +} + +// Each fade and each banner the clean run looks for, missed alone: the +// row it falls in must still pass. A door step accepts only its fade +// today, so a missed fade there fails a real arrival (#268's Monte Carlo, +// 19/20 on 01.05). +UnitTestResult every_single_miss(Logger& logger){ + SimExecutor clean(logger); + if (!run_rows_on(clean, logger, {.from = "00.00", .to = "01.11"}).completed){ + return "the run fails without misses: " + clean.result().error; + } + const std::vector& rows = clean.result().rows; + std::vector failed; + const auto miss = [&](bool fade, size_t index){ + size_t k = 0; + while (k + 1 < rows.size() && (fade ? rows[k + 1].fades : rows[k + 1].banners) <= index){ + k++; + } + SimMisses misses{.fade = {}, .banner = {}}; + (fade ? misses.fade : misses.banner) = index - (fade ? rows[k].fades : rows[k].banners); + const std::string stopped = run_case(logger, rows[k].row, rows[k].row, misses, {}); + if (!stopped.empty()){ + failed.push_back(std::format("{} {} missed: {}", fade ? "fade" : "banner", index, stopped)); + } + }; + for (size_t i = 0; i < clean.misses().fades; i++){ + miss(true, i); + } + for (size_t i = 0; i < clean.misses().banners; i++){ + miss(false, i); + } + std::string out = std::format("{} of {} single misses fail their row:", failed.size(), clean.misses().fades + clean.misses().banners); + for (const std::string& line : failed){ + out += "\n " + line; + } + return failed.empty() ? UnitTestResult(true) : UnitTestResult(out); +} + +// Oreburgh's street at night (88, game clock 00:25; 104 by day, r74), the +// Gate's dim floor (46) and a cave mouth's dim fade (45 to 64): the tap +// steps judge their fades with tap_faded(), which took the Gate's floor +// for a fade under the old "brightness under 75" (lab-B 2026-11-08). +UnitTestResult night_and_dim_floors(Logger& logger){ + SimWorldKnobs knobs{ + .floor = {{"OreburghCity", 88}, {"Route203", 88}, {"OreburghGate", 46}}, + .fade_into = {{"OreburghGate", 64}, {"OreburghCity", 255}, {"Route203", 255}}, + }; + return passes(run_case(logger, "01.02", "01.05", {.fade = {}, .banner = {}}, knobs)); +} + +// 01.03: Roark's first line in the mine comes after the camera zooms in on +// us, some seconds after the A press (r98; the old event waited 8 s). +UnitTestResult roark_speaks_late(Logger& logger){ + std::string talk; + for (const StoryCheckpoint& row : story_checkpoints()){ + for (const StoryStep& step : row.steps){ + if (row.id == "01.03" && step.kind == StoryStepKind::TALK){ + talk = step.name; + } + } + } + return passes(run_case(logger, "01.03", "01.03", {.fade = {}, .banner = {}}, {.first_line = {{talk, 7000ms}}})); +} + +// `row` with everyone on its maps walking their wander boxes, seeds 1 to 8. +UnitTestResult wanderers_move(Logger& logger, const std::string& row){ + std::vector failed; + for (uint64_t seed = 1; seed <= 8; seed++){ + const std::string stopped = run_case(logger, row, row, {.fade = {}, .banner = {}}, {.wander_seed = seed}); + if (!stopped.empty()){ + failed.push_back(std::format("seed {}: {}", seed, stopped)); + } + } + std::string out = std::format("{} of 8 seeds fail:", failed.size()); + for (const std::string& line : failed){ + out += "\n " + line; + } + return failed.empty() ? UnitTestResult(true) : UnitTestResult(out); +} + +struct FailureCaseInput{ + std::string name; + std::function body; +}; +// Whether a case is expected to fail is KNOWN_FAILING's, by name. +struct FailureCaseExpectation{ +}; +struct FailureCase{ + FailureCaseInput input; + FailureCaseExpectation expectation; +}; + +class Test_AutoStoryFailureCase : public UnitTest{ +public: + explicit Test_AutoStoryFailureCase(FailureCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Console failure on the sim: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + UnitTestResult result; + try{ + result = m_case.input.body(logger); + }catch (Exception& e){ + result = std::string(e.name()) + ": " + e.message(); + } + const auto known = KNOWN_FAILING.find(m_case.input.name); + if (known == KNOWN_FAILING.end()){ + return result; + } + if (result.result == UnitTestResult::PASSED){ + return "on KNOWN_FAILING (" + known->second + ") but passes now: take it off the list."; + } + logger.log("Known failing until " + known->second + ": " + result.message); + return true; + } + +private: + FailureCase m_case; +}; + +} // namespace + +const FailureCase AUTO_STORY_FAILURE_CASES[] = { + {.input = {"01.05 through_the_gate's last leg runs a tile on (lab-B 2026-11-08 15:31)", [](Logger& logger){ + return passes(run_case(logger, "01.05", "01.05", {.fade = {}, .banner = {}}, gate_slide(SimFade::DIM, false))); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, dim fade, banner gone", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::DIM, false); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, dim fade, banner up", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::DIM, true); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, black fade", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::BLACK, true); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, white fade", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::WHITE, true); + }}, .expectation = {}}, + {.input = {"01.05 through_the_gate is one run west", gate_plan_one_run}, .expectation = {}}, + {.input = {"any one missed fade or banner from 00.00 to 01.11: every row still passes", every_single_miss}, .expectation = {}}, + {.input = {"01.02 to 01.05 at night, the Gate's dim floor", night_and_dim_floors}, .expectation = {}}, + {.input = {"01.03 Roark's first line 7 s after the A press", roark_speaks_late}, .expectation = {}}, + {.input = {"01.03 with Oreburgh's people wandering (the pokefan on 45, 37..39)", [](Logger& logger){ + return wanderers_move(logger, "01.03"); + }}, .expectation = {}}, + {.input = {"01.08 with Route 204's youngster wandering (12..14, 2)", [](Logger& logger){ + return wanderers_move(logger, "01.08"); + }}, .expectation = {}}, +}; + +void add_tests_AutoStory_SimFailureCases(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_FAILURE_CASES){ + database.add(item); + } +} + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h new file mode 100644 index 0000000000..b196c4baf9 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h @@ -0,0 +1,27 @@ +/* BDSP AutoStory - Console failure cases on the story simulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_SimFailureCases_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_SimFailureCases_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// Each failure console B showed in events and perception, run on the story +// simulation; the ones the program still fails are known failing. +void add_tests_AutoStory_SimFailureCases(UnitTestDatabase& database); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index fd6b86de1e..6b2fde5764 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -66,11 +66,21 @@ bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, cons return false; } +double SimStoryStepIO::floor_here() const{ + for (const auto& [map, brightness] : m_knobs.floor){ + if (on_map(map)){ + return brightness; + } + } + return SIM_FLOOR; +} + // D-pad taps, each looked at, until the fade and then the banner (the // console's ConsoleStoryStepIO::tap_to_banner()): none if the banner shows // before the first. Each look stands still, so a banner on the far side -// reads at once. A fade seen ends the taps, -// banner or not; with the fade missed the next look still sees the banner. +// reads at once. A look the program's tap_faded() takes for the fade ends +// the taps, banner or not: a warp's fade, or a dim floor read as one; with +// the fade missed the next look still sees the banner. std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ if (m_misses.through == m_misses.tap_steps++){ m_misses.missed = true; @@ -78,27 +88,79 @@ std::optional SimStoryStepIO::tap_to_banner(Direction direction, const s return 0; } } + if (std::exchange(m_misses.banner_up, "") == map){ + return 0; + } bool crossed = false; for (size_t tap = 1; tap <= max_taps; tap++){ + const double before = floor_here(); const SimMove move = m_sim.tap(direction, 160ms, false); if (move.stop == SimStop::DIALOG){ return std::nullopt; } - bool faded = false; + double look = floor_here(); if (move.stop == SimStop::WARP){ - faded = !fade_missed(); + const auto fade = m_knobs.fade_into.find(map); + look = fade_missed() ? look : fade == m_knobs.fade_into.end() ? SIM_DOOR_FADE : fade->second; crossed = m_far_side(); } if (crossed && on_map(map) && !banner_missed()){ return tap; } - if (faded){ + if (tap_faded(before, look)){ return std::nullopt; } } return std::nullopt; } +WalkResult SimKnobRouteIO::walk_taps(Direction direction, size_t tiles, const std::string& label){ + const WalkResult result = GridSimRouteIO::walk_taps(direction, tiles, label); + if (result.stop != WalkStop::LIMIT || m_slid_steps.contains(m_step)){ + return result; + } + for (const SimSlide& item : m_knobs.slides){ + if (item.step == m_step && item.direction == direction){ + m_slid_steps.insert(m_step); + return slide_on(item, result); + } + } + return result; +} + +// The taps past the leg's end. Onto a warp the walk sees what the fade +// looks like to its watchers: a black fade ends it (TRANSITION), a white +// one is a wild battle to it, a dim one nothing. +WalkResult SimKnobRouteIO::slide_on(const SimSlide& slide, WalkResult result){ + m_misses.slid = true; + for (size_t tap = 0; tap < slide.tiles; tap++){ + const SimMove move = m_grid.tap(slide.direction, ROUTE_MS_PER_TILE_ACROSS, false); + if (move.stop != SimStop::WARP){ + note(std::format("[Sim] slid a tile on to {}.", to_string(m_grid.player().pos)), RouteNote::LOG); + continue; + } + note("[Sim] slid onto a warp to " + Pokemon::to_string(slide.far) + ".", RouteNote::LOG); + m_cross(slide.far); + m_misses.banner_up = slide.banner_up ? slide.far.map : ""; + if (slide.fade == SimFade::BLACK){ + result.stop = WalkStop::TRANSITION; + }else if (slide.fade == SimFade::WHITE){ + result.wild_battles++; + } + return result; + } + return result; +} + +bool SimKnobRouteIO::dialog_within(Milliseconds wait, Color color){ + const auto late = m_knobs.first_line.find(m_step); + if (late != m_knobs.first_line.end() && late->second > wait){ + note(std::format("[Sim] {}: the first line comes after {} ms, past the {} ms wait.", m_step, late->second.count(), wait.count()), RouteNote::LOG); + return false; + } + return GridSimRouteIO::dialog_within(wait, color); +} + // The story variables whose coord events the table walks onto, from the // row (and step) the table's reasons give, with the maps' coord events // (Diamond's zone events; Platinum's for the houses): Barry's doorstep and @@ -252,6 +314,50 @@ SimWorld SimExecutor::setup(const StoryWorld* world) const{ } out.triggers.push_back(std::move(trigger)); } + out.wanderers = wanderers(*world); + return out; +} + +namespace{ +bool on_world(const StoryWorld& world, const std::string& map){ + try{ + story_to_world(world, map, {0, 0}); + return true; + }catch (const InternalProgramError&){ + return false; + } +} +} // namespace + +// Everyone with a wander box on `world`'s maps, walking it from their tile +// (SimWorldKnobs::wander_seed), each with their own seed and start time. +std::vector SimExecutor::wanderers(const StoryWorld& world) const{ + std::vector out; + if (!m_knobs.wander_seed){ + return out; + } + for (const auto& [map, json] : bdsp_map_json()){ + if (!on_world(world, map)){ + continue; + } + for (const auto& object : story_map(map).objects){ + if (!object.wander){ + continue; + } + const uint64_t seed = *m_knobs.wander_seed * 1000003 + out.size() * 7919 + (uint64_t)(object.x * 31 + object.y); + const TilePos low = story_to_world(world, map, {object.wander->x0, object.wander->y0}); + const TilePos high = story_to_world(world, map, {object.wander->x1, object.wander->y1}); + out.push_back({ + .name = object.name, + .box = {.x0 = low.x, .y0 = low.y, .x1 = high.x, .y1 = high.y}, + .pos = story_to_world(world, map, {object.x, object.y}), + .seed = seed, + .step_interval = Milliseconds(2000), + .elapsed = Milliseconds(0), + .time_offset = Milliseconds((int64_t)(seed % 2000)), + }); + } + } return out; } @@ -279,6 +385,10 @@ bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ if (world == nullptr || tiles.empty()){ return false; } + // The program thinks we are on `pose`; we walk on from where the slide left us. + if (m_astray && m_placed){ + return true; + } const SimPlayer& player = m_sim.player(); const std::optional local = !m_placed || &m_sim.world() != world ? std::nullopt : story_to_local(*world, pose.map, nearest_tile(player.pos)); @@ -293,12 +403,15 @@ bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ // Through a door or a cave mouth onto the step's far side, the player's // facing kept: a hold goes on from there. bool SimExecutor::cross(){ - const StoryWorld* world = m_far ? sim_world(m_far->map) : nullptr; - const std::vector tiles = m_far ? Pokemon::tiles_of(*m_far) : std::vector{}; + return m_far && cross_to(*m_far); +} +bool SimExecutor::cross_to(const Pose& far){ + const StoryWorld* world = sim_world(far.map); + const std::vector tiles = Pokemon::tiles_of(far); if (world == nullptr || tiles.empty()){ return false; } - m_sim.place(setup(world), story_to_world(*world, m_far->map, tiles.front()), std::nullopt); + m_sim.place(setup(world), story_to_world(*world, far.map, tiles.front()), std::nullopt); return true; } @@ -346,6 +459,10 @@ std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome){ if (!walks || !m_placed){ return ""; } + if (m_astray){ + m_result.unchecked.push_back(m_row + " " + step.name + " (slid on)"); + return ""; + } if (!expected || Pokemon::tiles_of(*expected).empty()){ m_result.unchecked.push_back(m_row + " " + step.name); return ""; @@ -386,11 +503,13 @@ Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ Outcome SimExecutor::run(RunState& state, const StoryStep& step){ Outcome outcome; m_passed_over = false; + m_step = step.name; try{ outcome = run_step(state, step); }catch (const GridSimFailure& e){ outcome = Pokemon::outcome_failed("sim_failure", e.message); } + m_astray |= std::exchange(m_misses.slid, false); const std::string mismatch = outcome.succeeded() && !m_passed_over ? check(step, outcome) : ""; if (!mismatch.empty()){ outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); @@ -398,6 +517,7 @@ Outcome SimExecutor::run(RunState& state, const StoryStep& step){ // What the simulation does not play (scenes, events, battles) ends // where the table says it does. if (outcome.succeeded() && step.pose_after){ + m_astray = false; sync(*step.pose_after); } m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index 7193ac8992..e4bbe4cfc1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -44,7 +44,9 @@ namespace PokemonBDSP{ // its banner gone unless `through_banner`: the walk before it slid onto the // warp (lab-B 2026-11-08). The counts and flags below are the run's: how // many fades and banners it looked for, whether a miss happened since the -// executor last looked, and whether a missed fade is still unseen. +// executor last looked, whether a missed fade is still unseen, whether a +// walk slid on (SimSlide) since the executor last looked, and the map whose +// banner a slide left up for the next step. struct SimMisses{ std::optional fade; std::optional banner; @@ -57,6 +59,82 @@ struct SimMisses{ size_t doors = 0; bool missed = false; bool fade_unseen = false; + bool slid = false; + std::string banner_up = {}; +}; + +// How a warp's fade looks to the console's watchers (#268's design note). +enum class SimFade{ + // A door's: near black. Every watcher of a black screen sees it. + BLACK, + // A cave mouth's: dim, not black. A walk's strict black watcher (rgb + // sum 100, stddev 10; WalkRunner::hold()) misses it and the walk goes + // on (the Oreburgh Gate, lab-B 2026-11-08 16:03). + DIM, + // A cave exit's white: a walk's encounter-flash watcher reads it as a + // wild battle. + WHITE, +}; + +// An open leg that runs on past its end: the walk taps of the step `step` +// toward `direction` go `tiles` further, once per step. Onto a warp, the +// player lands on `far` (the sim's maps have no warps' destinations), the +// walk sees the fade as `fade` looks, and the far map's banner is still up +// for the next step (`banner_up`) or gone (01.05, lab-B 2026-11-08 15:31). +struct SimSlide{ + std::string step; + Pokemon::Direction direction = Pokemon::Direction::WEST; + size_t tiles = 1; + Pokemon::Pose far = {}; + SimFade fade = SimFade::DIM; + bool banner_up = false; +}; + +// What the console showed that the plain simulation leaves out, each off +// unless set. All of it is deterministic: wanderers walk from `wander_seed`. +struct SimWorldKnobs{ + std::vector slides = {}; + // The mean brightness (0 to 255) of a map's floor, by JSON map name, and + // of the fade into a map; a tap step judges its fade from these with the + // program's tap_faded(). Unset: 104 (Oreburgh's street by day) and 7 + // (a door's black). + std::map floor = {}; + std::map fade_into = {}; + // People with a wander box on their map walk it, a step tried every 2 s. + std::optional wander_seed = std::nullopt; + // How long after the A press a talk's first line shows, by step name. + std::map first_line = {}; +}; + +// The walker's RouteIO on the story simulation, with SimWorldKnobs' slides +// and late first lines. `step` names the step running now; `cross` puts +// the player on a pose past a warp. +class SimKnobRouteIO : public GridSimRouteIO{ +public: + SimKnobRouteIO( + GridSim& sim, std::vector& notes, SimMisses& misses, const SimWorldKnobs& knobs, + const std::string& step, std::function cross + ) + : GridSimRouteIO(sim, notes) + , m_grid(sim) + , m_misses(misses) + , m_knobs(knobs) + , m_step(step) + , m_cross(std::move(cross)) + {} + + virtual WalkResult walk_taps(Pokemon::Direction direction, size_t tiles, const std::string& label) override; + virtual bool dialog_within(Milliseconds wait, Color color) override; + +private: + WalkResult slide_on(const SimSlide& slide, WalkResult result); + + GridSim& m_grid; + SimMisses& m_misses; + const SimWorldKnobs& m_knobs; + const std::string& m_step; + std::function m_cross; + std::set m_slid_steps; }; // How many tiles a held walk goes on into a map before its location @@ -65,7 +143,13 @@ struct SimMisses{ // reads at once. Through a cave mouth the fade comes first, and a hold // whose fade went unseen goes on the same way (r75, r81). constexpr size_t SIM_BANNER_TILES = 3; +// How far into a door run SimMisses::dark reads dark, short of the door. constexpr Milliseconds SIM_FALSE_DARK = Milliseconds(1800); +// Brightness (0 to 255) of a floor where SimWorldKnobs does not say: +// Oreburgh's street by day (r74). +constexpr double SIM_FLOOR = 104; +// Brightness of a fade where SimWorldKnobs does not say: a door's black (by hand: 7). +constexpr double SIM_DOOR_FADE = 7; // What a run on the simulation did. struct SimRun{ @@ -95,10 +179,14 @@ struct SimRun{ // sim's maps have no warps' destinations) and on along it. class SimStoryStepIO : public StoryStepIO{ public: - SimStoryStepIO(GridSim& sim, std::vector& notes, SimMisses& misses, std::function far_side) + SimStoryStepIO( + GridSim& sim, std::vector& notes, SimMisses& misses, const SimWorldKnobs& knobs, + const std::string& step, std::function far_side, std::function cross + ) : m_sim(sim) - , m_route(sim, notes) + , m_route(sim, notes, misses, knobs, step, std::move(cross)) , m_misses(misses) + , m_knobs(knobs) , m_far_side(std::move(far_side)) {} @@ -157,10 +245,13 @@ class SimStoryStepIO : public StoryStepIO{ bool on_map(const std::string& map) const{ return story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)).has_value(); } + // The brightness of the floor the player stands on (SimWorldKnobs::floor). + double floor_here() const; GridSim& m_sim; - GridSimRouteIO m_route; + SimKnobRouteIO m_route; SimMisses& m_misses; + const SimWorldKnobs& m_knobs; std::function m_far_side; }; @@ -191,11 +282,12 @@ std::vector story_triggers(); // The program's walking steps on the simulation, the rest stubbed. class SimExecutor : public Pokemon::StoryStepExecutor{ public: - explicit SimExecutor(Logger& logger, SimMisses misses = {}) + explicit SimExecutor(Logger& logger, SimMisses misses = {}, SimWorldKnobs knobs = {}) : m_logger(logger) , m_misses(misses) + , m_knobs(std::move(knobs)) , m_sim({}, {0, 0}, Pokemon::Direction::NORTH, false) - , m_io(m_sim, m_notes, m_misses, [this]{ return cross(); }) + , m_io(m_sim, m_notes, m_misses, m_knobs, m_step, [this]{ return cross(); }, [this](const Pokemon::Pose& far){ cross_to(far); }) , m_walks(m_io) {} @@ -209,6 +301,7 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ m_row = data.id; m_start_mismatch = data.start ? off_pose(*data.start) : ""; m_ran.clear(); + m_astray = false; m_result.rows.push_back({.row = data.id, .fades = m_misses.fades, .banners = m_misses.banners}); m_walks.begin_attempt(data.id); arm(""); @@ -242,6 +335,8 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ void arm(const std::string& after); bool sync(const Pokemon::Pose& pose, const StoryWorld* on = nullptr); bool cross(); + bool cross_to(const Pokemon::Pose& far); + std::vector wanderers(const StoryWorld& world) const; std::string off_pose(const Pokemon::Pose& pose) const; std::string check(const Pokemon::StoryStep& step, const Pokemon::Outcome& outcome); Pokemon::Outcome run_step(Pokemon::RunState& state, const Pokemon::StoryStep& step); @@ -249,6 +344,9 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ Logger& m_logger; std::vector m_notes; SimMisses m_misses; + SimWorldKnobs m_knobs; + // The step running now. + std::string m_step; GridSim m_sim; SimStoryStepIO m_io; StoryWalkSteps m_walks; @@ -266,6 +364,9 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ bool m_placed = false; // Whether the step running now is on a room with no map. bool m_passed_over = false; + // Whether a walk slid on (SimSlide), so the player is not where the + // program thinks, until a step's pose_after puts them right. + bool m_astray = false; SimRun m_result; }; diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 9d38d35b83..7f5a6de0a3 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1712,6 +1712,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimGround.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp