From ee1eca7571d33237aed6fa4b73af6932ef737e75 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Wed, 2 Dec 2026 23:39:09 +0300 Subject: [PATCH 1/2] Trace bounded settler paths and their consulted voxel revisions --- CMakeLists.txt | 2 + docs/agent-workflow/tasks/S03-01.md | 49 ++++ .../settlement/core/voxel_navigation.hpp | 84 ++++++ engine/src/voxel_navigation.cpp | 266 ++++++++++++++++++ 4 files changed, 401 insertions(+) create mode 100644 docs/agent-workflow/tasks/S03-01.md create mode 100644 engine/include/settlement/core/voxel_navigation.hpp create mode 100644 engine/src/voxel_navigation.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 623b1ba..58fcbc7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -48,6 +48,7 @@ add_library(settlement_core engine/src/rules_manifest.cpp engine/src/save_service_win32.cpp engine/src/simulation_runtime.cpp + engine/src/voxel_navigation.cpp engine/src/worker_pool.cpp engine/src/world.cpp engine/src/world_save.cpp @@ -133,6 +134,7 @@ if(BUILD_TESTING) tests/save_service_tests.cpp tests/session_tests.cpp tests/snapshot_tests.cpp + tests/voxel_navigation_tests.cpp tests/test_main.cpp ) target_link_libraries(settlement_core_tests PRIVATE settlement_core Void::Testing) diff --git a/docs/agent-workflow/tasks/S03-01.md b/docs/agent-workflow/tasks/S03-01.md new file mode 100644 index 0000000..5213831 --- /dev/null +++ b/docs/agent-workflow/tasks/S03-01.md @@ -0,0 +1,49 @@ +# Find and revalidate settler routes across editable voxel chunks + +Task ID: S03-01 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Actual isolated system/s03-navigation worktree at 6d1123e has frozen region API voxel_region.hpp, S02 implementation/registration arriving from sibling before testing. M02-P1/F1 reviewed source/algorithm limits; M01 flat assignment_path keys are two-dimensional and World::step advances without revalidation. S03 is disjoint from existing World and S02 implementation. Void 7b0fea6095f603f9e1904f66dfdc7752f4be4792 supplies IndexedGraphView/bfs/shortest_path_unweighted WorkLimits. Generic consulted revision sets absent, already tracked #13. + +## 2. Objective and deliverables +Implement tested bounded 3D ordinary-settler path query, interaction positions, consulted effective chunk revisions and transition revalidation. Ready for the authorized M02 World movement/mining owner to consume; send actual frozen public API early. + +## 3. Scope and non-goals +Only new voxel navigation module, real standalone tests, CMake entries and S03 docs. Use shared S02 data; leave old flat A*, World/serializer/actual HWND/drawing to their assigned M02 consumers. No new navmesh, multi-region streaming, liquids/animals or future profiles. Do not copy any unfinished S02 source. + +## 4. Files to inspect +Read docs/plan/milestones/M02.md, systems/S02/S03, void-library.md and M02-P1/F1/S02-01; frozen engine/include/settlement/core/voxel_region.hpp at6d1123e, root engine/src/world.cpp assignment_path/advance, headers command_dispatcher.hpp::SessionIdentity (UUID epoch), CMake/tests. Official pinned Void/Algorithms/Graph.hpp plus tests in pinned tree, see real limits, edges, start==target early success. + +## 5. Write ownership and coordination +Write scope: engine/include/settlement/core/voxel_navigation.hpp; engine/src/voxel_navigation.cpp; tests/voxel_navigation_tests.cpp; CMakeLists.txt; docs/plan/systems/S03.md +First three paths are new. In CMake add only your source, test and, if needed, a link to the already enabled Void::Algorithms target. +Other people work in separate WTs; never overwrite/revert their work, never change shared Serena project. No Git/remote ops, children, edits to S02 files, existing World or M01. + +## 6. Implementation or investigation approach +Represent foot at one voxel, two vertical cells clear, support directly below. 4 horizontal cardinal neighbors with level/one-step up/down, no unsupported pure flight or diagonal wall/corner clipping. Evaluate the swept body under up/down (needed headroom over raised/descending transition). Reuse S02 voxel_blocks_passage/voxel_provides_support and stamps; DoorOpen+air passable, DoorClosed blocked; soil/stone support only. A stair flight is a sequence of supported steps. Provide single-hop validation and standing check from same queries as solver, and separate API for adjacent accessible task interactions (range/line of contact cannot mine through wall/above unreachable geometric separation). + +## 7. Interfaces and data contracts +NEW request/result includes region and session/incarnation from existing actual UUID type, bounded search volume/goals (deterministic ties), route/current to goal route semantics documented, cost, failure reason, sorted deduplicated consulted chunk stamps incl support/head/blocked/unavailable neighbours, and stale check via Region.matches + owner session. An unrelated edit must preserve result. Opening previously unavailable gateway invalidates negative result, same ID and numeric revisions after world reload still require new session. Distinguish invalid inputs, truly unreachable, unavailable/awaiting activation, boundary/budget and cancellation errors. Small finite known search uses Void::Algorithms::bfs or shortest_path on bounded IndexedGraphView; respect start==goal check before library fast path. For multi-goal choose canonical shortest (distance then stable coordinate and neighbor order); restrict result to reachable interaction positions. Do not allocate full coordinate extent on sparse huge region. Check vertex count, edges/step/aggregate scratch, size_t/int64 computations and bound read-set. Non-exhaustive clipping/budget must not masquerade as proven unreachable. + +## 8. Dependencies and integration +Parent gives compiled S02 implementation and test registration via local merge after worktree is sealed when ready. Can compile your TUs against header first; no mock replaces genuine final evidence. Future M02 authority, persistence, frame/picking will use foot positions/goal and read stamps. Protocol11/legacy file unaffected. Local revision set #13 to be linked with its exact replacement tests in S03. + +## 9. Edge cases security and performance +Include INT extremes/partial bounds/overflow, headroom at source+destination, missing vertical support in a different page, start==same blocked target, path/missing pages and time/epoch; cannot mutate captured VoxelRegion. Keep memory bounded by explicit realistic work limits; e.g. 256*32³ cells must not allocate 136MiB per worker to traverse a four-cell corridor. Check allocation failure/too many input goals gracefully. Avoid per-node heap allocations for bounded neighbor enumeration where appropriate. No hiding application bugs in arbitrary timeout/different path cost. + +## 10. Acceptance criteria +1. Real S02 volume route through two-cell open door and cross-chunk stair to upper interaction; closed door/headwall/no support block and reason. 2. Remove next future support while traveler still safe, route/stamps stale, next-hop rejects; reopen, route returns; unrelated chunk change preserves validation; unavailable-to-loaded negative becomes stale; new session stale. 3. Stable exact cost/goal/tie path on small fixtures vs independent exhaustive reference + multiple worker schedules, direct same-goal invalid case. 4. Explicit bounded-limit behavior before dense allocation/partial proof, integer extremes and deterministic sorted queried stamps. 5. Real cross-build/full tests with S02 and docs issue linkage. + +## 11. Verification commands and evidence +Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s03-navigation-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build --parallel 6, run ctest --test-dir --output-on-failure and your targeted tests. Evidence required. After link run --tag voxel-navigation, full ctest -V and git diff --check with /tmp/stoneheart-milestones.xprJ2SVp/s03-voxel-*.log. Native Windows unavailable. Before full interactive CTest contact root to avoid simultaneous keyboard-driven smoke test. + +## 12. Constraints and stop conditions +No invented S02 or Void API; if integration contract insufficient, send precise new dependency to root and continue self-contained cases. No alternate user workflow, new external tickets, or duplicate library pathfinder. Two unsuccessful same-cause attempts escalate. No remote or children. + +## 13. Authorization and decisions +User requested all milestone/system coding, actual upstream library gaps and per-branch MRs. M02 architecture accepted ordinary one-cell-wide/two-tall profile, one step max; root handles publishing. + +## 14. Return format +Return S03-01 READY or PARTIAL, early stable interface for M02 owner, actual code/test limits, work bounds and cross-branch evidence including cross-boundary route/invalidation and distinct failure outcomes. diff --git a/engine/include/settlement/core/voxel_navigation.hpp b/engine/include/settlement/core/voxel_navigation.hpp new file mode 100644 index 0000000..04c7259 --- /dev/null +++ b/engine/include/settlement/core/voxel_navigation.hpp @@ -0,0 +1,84 @@ +#pragma once + +#include "settlement/core/voxel_region.hpp" +#include +#include +#include +#include +#include +#include + +namespace settlement { + +enum class VoxelNavigationStatus { + Reachable, Unreachable, Unavailable, SearchBoundary, LimitExceeded, + Cancelled, InvalidInput, AllocationFailed +}; + +struct VoxelNavigationLimits { + std::size_t max_vertices = 65'536; + std::size_t max_steps = 1'000'000; + std::size_t max_samples = 4'000'000; + std::size_t max_scratch_bytes = 8 * 1024 * 1024; + std::size_t max_goals = 64; + std::size_t max_dependencies = 4096; +}; + +struct VoxelReadSet { + RegionId region = 0; + Void::Uuid::Uuid session; + // Sorted unique chunk coordinates, including blocked and unavailable reads. + std::vector chunks; + [[nodiscard]] bool current(const VoxelRegion& world, const Void::Uuid::Uuid& epoch) const noexcept; +}; + +struct VoxelTraversalResult { + VoxelNavigationStatus status = VoxelNavigationStatus::InvalidInput; + VoxelReadSet consulted; +}; + +struct VoxelPathRequest { + RegionId region = 0; + Void::Uuid::Uuid session; + VoxelPosition start; + // The caller chooses a finite search window contained in the region. + VoxelBounds search_bounds; + std::vector goals; + VoxelNavigationLimits limits; +}; + +struct VoxelPathResult { + VoxelNavigationStatus status = VoxelNavigationStatus::InvalidInput; + std::optional goal; + // Excludes start, includes goal. An already satisfied goal has an empty route. + std::vector route; + std::size_t cost = 0; + std::size_t visited = 0; + VoxelReadSet consulted; +}; + +// Ordinary settlers occupy the foot cell and the cell above, with solid support +// below. A transition is one cardinal horizontal move and at most one step. +[[nodiscard]] VoxelTraversalResult voxel_standing( + const VoxelRegion& world, const Void::Uuid::Uuid& session, VoxelPosition foot, + VoxelNavigationLimits limits = {}, std::stop_token stop = {}); +[[nodiscard]] VoxelTraversalResult voxel_transition( + const VoxelRegion& world, const Void::Uuid::Uuid& session, + VoxelPosition from, VoxelPosition to, VoxelNavigationLimits limits = {}, + std::stop_token stop = {}); + +// Finds a shortest known route within the requested window. Equal costs choose +// the lexicographically first goal; each vertex's neighbors use coordinate order. +// A negative result distinguishes missing chunks and an escapable window edge. +[[nodiscard]] VoxelPathResult find_voxel_path( + const VoxelRegion& world, const VoxelPathRequest& request, std::stop_token stop = {}); + +// Candidate feet touch the target by a face of either body cell, or stand one +// cell above / two below it. The target must be loaded. Work policy stays with +// the owner; navigation only proves contact and a supported clear body volume. +// request.goals is ignored; the same bounds, identity and limits apply. +[[nodiscard]] VoxelPathResult find_voxel_interaction_path( + const VoxelRegion& world, const VoxelPathRequest& request, + VoxelPosition target, std::stop_token stop = {}); + +} // namespace settlement diff --git a/engine/src/voxel_navigation.cpp b/engine/src/voxel_navigation.cpp new file mode 100644 index 0000000..458d3e4 --- /dev/null +++ b/engine/src/voxel_navigation.cpp @@ -0,0 +1,266 @@ +#include "settlement/core/voxel_navigation.hpp" +#include +#include +#include +#include +#include +#include +#include + +namespace settlement { +namespace { +using Status = VoxelNavigationStatus; +struct NavigationFailure { Status status; }; + +std::optional offset(VoxelPosition p, int x, int y, int z) noexcept { + const auto nx = std::int64_t{p.x} + x, ny = std::int64_t{p.y} + y, nz = std::int64_t{p.z} + z; + constexpr auto low = std::numeric_limits::min(); + constexpr auto high = std::numeric_limits::max(); + if (nx < low || nx > high || ny < low || ny > high || nz < low || nz > high) return {}; + return VoxelPosition{static_cast(nx), static_cast(ny), static_cast(nz)}; +} + +bool valid_bounds(const VoxelBounds& b, const VoxelBounds& region) noexcept { + return b.lower.x < b.upper.x && b.lower.y < b.upper.y && b.lower.z < b.upper.z && + b.lower.x >= region.lower.x && b.lower.y >= region.lower.y && b.lower.z >= region.lower.z && + b.upper.x <= region.upper.x && b.upper.y <= region.upper.y && b.upper.z <= region.upper.z; +} + +class Queries { +public: + Queries(const VoxelRegion& world, const Void::Uuid::Uuid& session, + VoxelNavigationLimits limits, std::stop_token stop) + : world_(world), limits_(limits), stop_(stop), reads{world.descriptor().id, session, {}} { + if (session.is_nil()) throw NavigationFailure{Status::InvalidInput}; + const auto bytes = Void::Numeric::checked_mul(limits.max_dependencies, sizeof(ChunkStamp)); + if (!bytes || *bytes > limits.max_scratch_bytes) throw NavigationFailure{Status::LimitExceeded}; + reads.chunks.reserve(limits.max_dependencies); + } + + VoxelSample sample(VoxelPosition p) { + if (stop_.stop_requested()) throw NavigationFailure{Status::Cancelled}; + if (samples_ == limits_.max_samples) throw NavigationFailure{Status::LimitExceeded}; + ++samples_; + auto value = world_.sample(p); + auto at = std::lower_bound(reads.chunks.begin(), reads.chunks.end(), value.stamp.coordinate, + [](const auto& stamp, const auto& coordinate) { return stamp.coordinate < coordinate; }); + if (at == reads.chunks.end() || at->coordinate != value.stamp.coordinate) { + if (reads.chunks.size() == limits_.max_dependencies) throw NavigationFailure{Status::LimitExceeded}; + reads.chunks.insert(at, value.stamp); + } + unavailable = unavailable || value.availability == VoxelAvailability::Unavailable; + return value; + } + + Status standing(VoxelPosition foot) { + const auto above = offset(foot, 0, 0, 1), below = offset(foot, 0, 0, -1); + if (!above || !below) return Status::Unreachable; + const auto body = sample(foot), head = sample(*above), support = sample(*below); + // A known obstruction is conclusive even if another cell is unavailable. + if (body.availability == VoxelAvailability::Outside || head.availability == VoxelAvailability::Outside || + support.availability == VoxelAvailability::Outside || + (body.availability == VoxelAvailability::Loaded && voxel_blocks_passage(body.material)) || + (head.availability == VoxelAvailability::Loaded && voxel_blocks_passage(head.material)) || + (support.availability == VoxelAvailability::Loaded && !voxel_provides_support(support.material))) return Status::Unreachable; + if (body.availability == VoxelAvailability::Unavailable || head.availability == VoxelAvailability::Unavailable || + support.availability == VoxelAvailability::Unavailable) return Status::Unavailable; + return Status::Reachable; + } + + Status transition(VoxelPosition from, VoxelPosition to) { + const auto dx = std::int64_t{to.x} - from.x, dy = std::int64_t{to.y} - from.y; + const auto dz = std::int64_t{to.z} - from.z; + if (!((dx == -1 || dx == 1) && dy == 0) && !((dy == -1 || dy == 1) && dx == 0)) return Status::Unreachable; + if (dz < -1 || dz > 1) return Status::Unreachable; + const auto first = standing(from), second = standing(to); + Status swept = Status::Reachable; + if (dz != 0) { + const auto upper = offset(dz > 0 ? from : to, 0, 0, 2); + if (!upper) return Status::Unreachable; + const auto cell = sample(*upper); + if (cell.availability == VoxelAvailability::Outside || + (cell.availability == VoxelAvailability::Loaded && voxel_blocks_passage(cell.material))) swept = Status::Unreachable; + else if (cell.availability == VoxelAvailability::Unavailable) swept = Status::Unavailable; + } + if (first == Status::Unreachable || second == Status::Unreachable || swept == Status::Unreachable) return Status::Unreachable; + if (first == Status::Unavailable || second == Status::Unavailable || swept == Status::Unavailable) return Status::Unavailable; + return Status::Reachable; + } + + const VoxelRegion& world_; + VoxelNavigationLimits limits_; + std::stop_token stop_; + VoxelReadSet reads; + bool unavailable = false; +private: + std::size_t samples_ = 0; +}; + +struct NeighborList { + std::array values{}; + std::size_t size = 0; + auto begin() const { return values.begin(); } + auto end() const { return values.begin() + static_cast(size); } +}; + +class WalkingGraph { +public: + WalkingGraph(Queries& queries, VoxelBounds bounds, std::size_t sx, std::size_t sy, std::size_t count) + : queries_(queries), bounds_(bounds), sx_(sx), sy_(sy), count_(count) {} + std::size_t vertex_count() const noexcept { return count_; } + std::size_t index(VoxelPosition p) const noexcept { + return static_cast(std::int64_t{p.x} - bounds_.lower.x) + sx_ * + (static_cast(std::int64_t{p.y} - bounds_.lower.y) + sy_ * + static_cast(std::int64_t{p.z} - bounds_.lower.z)); + } + VoxelPosition position(std::size_t i) const noexcept { + return {static_cast(bounds_.lower.x + static_cast(i % sx_)), + static_cast(bounds_.lower.y + static_cast((i / sx_) % sy_)), + static_cast(bounds_.lower.z + static_cast(i / (sx_ * sy_)))}; + } + NeighborList neighbors(std::size_t i) const { + NeighborList result; + const auto from = position(i); + // This is lexicographic VoxelPosition order, including all step heights. + constexpr std::array, 4> directions{{{-1, 0}, {0, -1}, {0, 1}, {1, 0}}}; + for (auto direction : directions) for (int dz = -1; dz <= 1; ++dz) { + const auto to = offset(from, direction[0], direction[1], dz); + if (!to) continue; + const auto state = queries_.transition(from, *to); + if (state != Status::Reachable) continue; + if (!bounds_.contains(*to)) { boundary = true; continue; } + result.values[result.size++] = index(*to); + } + return result; + } + mutable bool boundary = false; +private: + Queries& queries_; + VoxelBounds bounds_; + std::size_t sx_, sy_, count_; +}; + +VoxelPathResult search(Queries& queries, const VoxelPathRequest& request, std::span goals) { + VoxelPathResult result; + if (request.region != queries.world_.descriptor().id || goals.empty() || + !valid_bounds(request.search_bounds, queries.world_.descriptor().bounds) || + !request.search_bounds.contains(request.start)) return result; + const auto& limits = request.limits; + if (goals.size() > limits.max_goals) { result.status = Status::LimitExceeded; return result; } + for (auto goal : goals) if (!request.search_bounds.contains(goal)) return result; + const auto sx = static_cast(request.search_bounds.upper.x - request.search_bounds.lower.x); + const auto sy = static_cast(request.search_bounds.upper.y - request.search_bounds.lower.y); + const auto sz = static_cast(request.search_bounds.upper.z - request.search_bounds.lower.z); + const auto xy = Void::Numeric::checked_mul(sx, sy); + const auto count = xy ? Void::Numeric::checked_mul(*xy, sz) : std::nullopt; + // Void BFS retains four size_t vectors plus visited. Route construction and + // the read-set reserve coexist with them. No adjacency matrix is allocated. + const auto vertex_bytes = count ? Void::Numeric::checked_mul(*count, 4 * sizeof(std::size_t) + 1 + sizeof(VoxelPosition)) : std::nullopt; + const auto read_bytes = Void::Numeric::checked_mul(limits.max_dependencies, sizeof(ChunkStamp)); + const auto bytes = vertex_bytes && read_bytes ? Void::Numeric::checked_add(*vertex_bytes, *read_bytes) : std::nullopt; + if (!count || *count > limits.max_vertices || !bytes || *bytes > limits.max_scratch_bytes) { + result.status = Status::LimitExceeded; return result; + } + const auto start_state = queries.standing(request.start); + if (start_state != Status::Reachable) { result.status = start_state; return result; } + WalkingGraph graph(queries, request.search_bounds, sx, sy, *count); + const Void::Algorithms::WorkLimits work{ + limits.max_vertices, limits.max_steps, limits.max_scratch_bytes - *read_bytes, 1}; + auto traversal = Void::Algorithms::bfs(graph, graph.index(request.start), work, queries.stop_); + if (!traversal) { + result.status = traversal.error().code == Void::Algorithms::AlgorithmError::Code::cancelled ? Status::Cancelled : Status::LimitExceeded; + return result; + } + result.visited = traversal->order.size(); + std::size_t distance = Void::Algorithms::TraversalResult::npos; + for (auto goal : goals) { + // Explicit validation also covers the library's start==target fast path. + if (queries.standing(goal) != Status::Reachable) continue; + const auto cost = traversal->depth[graph.index(goal)]; + if (cost < distance || (cost == distance && cost != Void::Algorithms::TraversalResult::npos && + (!result.goal || goal < *result.goal))) { distance = cost; result.goal = goal; } + } + if (!result.goal) { + result.status = queries.unavailable ? Status::Unavailable : (graph.boundary ? Status::SearchBoundary : Status::Unreachable); + return result; + } + result.status = Status::Reachable; + result.cost = distance; + result.route.reserve(distance); + auto vertex = graph.index(*result.goal); + const auto start = graph.index(request.start); + while (vertex != start) { + result.route.push_back(graph.position(vertex)); + vertex = traversal->parent[vertex]; + } + std::reverse(result.route.begin(), result.route.end()); + return result; +} + +template +VoxelTraversalResult check(const VoxelRegion& world, const Void::Uuid::Uuid& session, + VoxelNavigationLimits limits, std::stop_token stop, Function&& function) { + VoxelTraversalResult result; + result.consulted = {world.descriptor().id, session, {}}; + try { + Queries queries(world, session, limits, stop); + try { result.status = function(queries); } + catch (const NavigationFailure& failure) { result.status = failure.status; } + result.consulted = std::move(queries.reads); + } catch (const NavigationFailure& failure) { result.status = failure.status; } + catch (const std::bad_alloc&) { result.status = Status::AllocationFailed; } + return result; +} + +VoxelPathResult path(const VoxelRegion& world, const VoxelPathRequest& request, + std::optional target, std::stop_token stop) { + VoxelPathResult result; + result.consulted = {world.descriptor().id, request.session, {}}; + try { + Queries queries(world, request.session, request.limits, stop); + try { + if (target) { + const auto cell = queries.sample(*target); + if (cell.availability != VoxelAvailability::Loaded) { + result.status = cell.availability == VoxelAvailability::Unavailable ? Status::Unavailable : Status::InvalidInput; + } else { + std::array goals{}; + std::size_t size = 0; + constexpr std::array, 4> directions{{{-1, 0}, {0, -1}, {0, 1}, {1, 0}}}; + for (auto direction : directions) for (int dz : {-1, 0}) { + if (auto goal = offset(*target, direction[0], direction[1], dz); goal && request.search_bounds.contains(*goal)) goals[size++] = *goal; + } + for (int dz : {-2, 1}) { + if (auto goal = offset(*target, 0, 0, dz); goal && request.search_bounds.contains(*goal)) goals[size++] = *goal; + } + result = search(queries, request, std::span(goals.data(), size)); + } + } else result = search(queries, request, request.goals); + } catch (const NavigationFailure& failure) { result.status = failure.status; } + result.consulted = std::move(queries.reads); + } catch (const NavigationFailure& failure) { result.status = failure.status; } + catch (const std::bad_alloc&) { result.status = Status::AllocationFailed; } + return result; +} +} // namespace + +bool VoxelReadSet::current(const VoxelRegion& world, const Void::Uuid::Uuid& epoch) const noexcept { + return region == world.descriptor().id && !session.is_nil() && epoch == session && + std::all_of(chunks.begin(), chunks.end(), [&](const auto& stamp) { return world.matches(stamp); }); +} +VoxelTraversalResult voxel_standing(const VoxelRegion& world, const Void::Uuid::Uuid& session, + VoxelPosition foot, VoxelNavigationLimits limits, std::stop_token stop) { + return check(world, session, limits, stop, [&](Queries& queries) { return queries.standing(foot); }); +} +VoxelTraversalResult voxel_transition(const VoxelRegion& world, const Void::Uuid::Uuid& session, + VoxelPosition from, VoxelPosition to, VoxelNavigationLimits limits, std::stop_token stop) { + return check(world, session, limits, stop, [&](Queries& queries) { return queries.transition(from, to); }); +} +VoxelPathResult find_voxel_path(const VoxelRegion& world, const VoxelPathRequest& request, std::stop_token stop) { + return path(world, request, {}, stop); +} +VoxelPathResult find_voxel_interaction_path(const VoxelRegion& world, const VoxelPathRequest& request, + VoxelPosition target, std::stop_token stop) { + return path(world, request, target, stop); +} +} // namespace settlement From 7a7ff32e1499e44d70eca4b6bc1931b5991ef242 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Wed, 2 Dec 2026 23:46:14 +0300 Subject: [PATCH 2/2] Verify door, stair and work access across signed chunk boundaries --- docs/plan/systems/S03.md | 18 ++ engine/src/voxel_navigation.cpp | 25 ++- tests/voxel_navigation_tests.cpp | 280 +++++++++++++++++++++++++++++++ 3 files changed, 314 insertions(+), 9 deletions(-) create mode 100644 tests/voxel_navigation_tests.cpp diff --git a/docs/plan/systems/S03.md b/docs/plan/systems/S03.md index f3cefd8..df172c6 100644 --- a/docs/plan/systems/S03.md +++ b/docs/plan/systems/S03.md @@ -8,6 +8,24 @@ В прототипе есть A*, фиксированный порядок соседей и кэш запросов. Изменение проходимости инвалидирует маршруты. Тесты проверяют проход через отверстие в стене и открытие ранее недоступной шахты. Карта использует двумерную позицию, а маршрут хранится последовательностью клеток внутри жителя. [Мир](../../../engine/src/world.cpp) · [Типы](../../../engine/include/settlement/core/world.hpp) · [Тесты маршрутов](../../../tests/core_tests.cpp) +## Первый исполняемый срез M02 + +Модуль `voxel_navigation` работает с неизменяемым `VoxelRegion`. `voxel_standing` проверяет опору, клетку ног и клетку головы. `voxel_transition` использует те же проверки для одного горизонтального перехода с подъёмом или спуском на одну клетку. При изменении высоты дополнительно проверяется объём, через который проходит голова. Закрытая дверь препятствует движению, открытая дверь допускает проход. Земля и камень предоставляют опору. [Интерфейс](../../../engine/include/settlement/core/voxel_navigation.hpp) · [Реализация](../../../engine/src/voxel_navigation.cpp) + +`find_voxel_path` получает ID региона, UUID текущей инкарнации, старт, множество целей и явное окно поиска. Путь содержит очередные позиции после старта. Его стоимость равна числу переходов. При равной стоимости выбирается первая цель в порядке координат, соседи каждой позиции перечисляются в том же порядке. Поиск использует `Void::Algorithms::bfs` из закреплённой версии библиотеки. Множество вершин относится к заданному окну, список соседей вычисляется по запросу. До выделения массивов проверяется полный размер окна. Разреженный регион с большой протяжённостью требует меньшего окна для конкретной задачи. + +`find_voxel_interaction_path` строит доступные позиции контакта с указанной клеткой. К ней должна примыкать грань тела жителя. Цель может находиться у ног, у головы, под ногами или непосредственно над головой. Цель должна быть загружена. Право добывать материал, менять дверь и удалять опору проверяет владелец работы. Выбранная позиция взаимодействия и следующий переход доступны для повторной проверки перед действием. + +Каждый ответ содержит `VoxelReadSet` с ID региона, инкарнацией и упорядоченными уникальными ревизиями прочитанных чанков. В набор входят опора, свободное место над головой, заблокированные соседи и недоступные страницы. `current` проверяет тот же сеанс и все эти ревизии. Загрузка недоступной страницы делает прежний отрицательный ответ устаревшим. Правка непрочитанного чанка сохраняет ответ пригодным. Сам ответ и его маршрут удерживают собственные данные. Для замены локального набора библиотечным повторить проверки опоры через границу чанка, открытия прохода, загрузки страницы и смены инкарнации. [Void/Library #13](https://git.faumaray.com/Void/Library/issues/13) + +Найденный путь является кратчайшим среди известных переходов в заданном окне. Отрицательный ответ различает доказанную недоступность, недостающие данные и возможность выхода за границу окна. Отдельные результаты обозначают исчерпание бюджета, отмену, неверный запрос и отказ выделения памяти. До быстрого случая совпавших старта и цели проверяется геометрия тела. Применяющий результат код должен проверять и его статус, и актуальность набора чтений. + +Пределы по умолчанию составляют 65 536 вершин, 1 000 000 шагов алгоритма, 4 000 000 чтений клеток, 64 цели, 4096 ревизий и 8 МиБ рабочих данных. Бюджет учитывает четыре массива `size_t` и посещённость из Void BFS, собираемый маршрут и зарезервированный набор ревизий. Список соседей из 12 элементов находится в стеке. Владелец сохраняет входные данные запроса и страницы мира отдельно. Измерение памяти распределителя и принудительный отказ системного распределителя остаются отдельными проверками. + +Селектор `--tag voxel-navigation` проверяет двухклеточную дверь, ступени на границе `x=31/32` и работу наверху, удаление следующей опоры, прежний неизменяемый снимок, место для головы, недоступную опору через отрицательную границу по высоте, постороннюю правку, смену сеанса и предельные координаты. Стоимости сравниваются с независимым полным обходом 16 малых плоских карт. Запросы в настоящем пуле с 2, 6 и 12 потоками дают те же маршруты и ревизии. [Проверки](../../../tests/voxel_navigation_tests.cpp) + +На совместной базе S02 `e7046a9` сборка Windows x64 GCC 16.2 и все десять проверок навигации прошли под Wine 11. Полный `ctest -V` прошёл четыре набора с 165 случаями ядра, 9 LAN, 14 клиента и испытанием кадра с видимой цепочкой D3D11 и WARP. Проверка заняла 4,66 с. Нативная Windows и связь навигации с исполнением работ в `World` проверяются при последующей интеграции M02. + ## Пространственная модель Позицию и материал предоставляет [S02](S02.md). Профиль движения определяет объём тела, высоту шага и разрешённые переходы. Для M02 нужен профиль обычного поселенца, движение по опоре, ступеням и лестницам. Особые способы движения добавляются вместе с соответствующими животными и боевыми участниками. diff --git a/engine/src/voxel_navigation.cpp b/engine/src/voxel_navigation.cpp index 458d3e4..cd7bf0f 100644 --- a/engine/src/voxel_navigation.cpp +++ b/engine/src/voxel_navigation.cpp @@ -142,23 +142,26 @@ private: VoxelPathResult search(Queries& queries, const VoxelPathRequest& request, std::span goals) { VoxelPathResult result; - if (request.region != queries.world_.descriptor().id || goals.empty() || - !valid_bounds(request.search_bounds, queries.world_.descriptor().bounds) || - !request.search_bounds.contains(request.start)) return result; + if (goals.empty()) return result; const auto& limits = request.limits; if (goals.size() > limits.max_goals) { result.status = Status::LimitExceeded; return result; } for (auto goal : goals) if (!request.search_bounds.contains(goal)) return result; const auto sx = static_cast(request.search_bounds.upper.x - request.search_bounds.lower.x); const auto sy = static_cast(request.search_bounds.upper.y - request.search_bounds.lower.y); const auto sz = static_cast(request.search_bounds.upper.z - request.search_bounds.lower.z); - const auto xy = Void::Numeric::checked_mul(sx, sy); - const auto count = xy ? Void::Numeric::checked_mul(*xy, sz) : std::nullopt; + const auto count = Void::Numeric::checked_mul(sx, sy).and_then( + [sz](auto xy) { return Void::Numeric::checked_mul(xy, sz); }); // Void BFS retains four size_t vectors plus visited. Route construction and // the read-set reserve coexist with them. No adjacency matrix is allocated. - const auto vertex_bytes = count ? Void::Numeric::checked_mul(*count, 4 * sizeof(std::size_t) + 1 + sizeof(VoxelPosition)) : std::nullopt; + const auto vertex_bytes = count.and_then([](auto size) { + return Void::Numeric::checked_mul(size, 4 * sizeof(std::size_t) + 1 + sizeof(VoxelPosition)); + }); const auto read_bytes = Void::Numeric::checked_mul(limits.max_dependencies, sizeof(ChunkStamp)); - const auto bytes = vertex_bytes && read_bytes ? Void::Numeric::checked_add(*vertex_bytes, *read_bytes) : std::nullopt; - if (!count || *count > limits.max_vertices || !bytes || *bytes > limits.max_scratch_bytes) { + if (!count || *count > limits.max_vertices || !vertex_bytes || !read_bytes) { + result.status = Status::LimitExceeded; return result; + } + const auto bytes = Void::Numeric::checked_add(*vertex_bytes, *read_bytes); + if (!bytes || *bytes > limits.max_scratch_bytes) { result.status = Status::LimitExceeded; return result; } const auto start_state = queries.standing(request.start); @@ -216,6 +219,9 @@ VoxelPathResult path(const VoxelRegion& world, const VoxelPathRequest& request, std::optional target, std::stop_token stop) { VoxelPathResult result; result.consulted = {world.descriptor().id, request.session, {}}; + if (request.region != world.descriptor().id || request.session.is_nil() || + !valid_bounds(request.search_bounds, world.descriptor().bounds) || + !request.search_bounds.contains(request.start)) return result; try { Queries queries(world, request.session, request.limits, stop); try { @@ -233,7 +239,8 @@ VoxelPathResult path(const VoxelRegion& world, const VoxelPathRequest& request, for (int dz : {-2, 1}) { if (auto goal = offset(*target, 0, 0, dz); goal && request.search_bounds.contains(*goal)) goals[size++] = *goal; } - result = search(queries, request, std::span(goals.data(), size)); + if (size == 0) result.status = Status::SearchBoundary; + else result = search(queries, request, std::span(goals.data(), size)); } } else result = search(queries, request, request.goals); } catch (const NavigationFailure& failure) { result.status = failure.status; } diff --git a/tests/voxel_navigation_tests.cpp b/tests/voxel_navigation_tests.cpp new file mode 100644 index 0000000..3aa0142 --- /dev/null +++ b/tests/voxel_navigation_tests.cpp @@ -0,0 +1,280 @@ +#include "settlement/core/voxel_navigation.hpp" +#include "settlement/core/worker_pool.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace settlement; +using Status = VoxelNavigationStatus; +using Void::Testing::Test; +void require(bool condition, const char* message) { + if (!condition) throw std::runtime_error(message); +} +Void::Uuid::Uuid epoch(std::uint8_t value = 1) { + Void::Uuid::Uuid result; + result.bytes.back() = value; + return result; +} +template +void install(VoxelRegion& world, ChunkCoordinate chunk, Material material) { + std::array cells{}; + for (std::uint8_t z = 0; z < 32; ++z) for (std::uint8_t y = 0; y < 32; ++y) for (std::uint8_t x = 0; x < 32; ++x) { + const auto p = join_voxel(chunk, {x, y, z}); + if (p && world.descriptor().bounds.contains(*p)) cells[*voxel_index({x, y, z})] = material(*p); + } + auto candidate = world.prepare_restored(chunk, 1, cells); + require(candidate.has_value(), "valid fixture page refused"); + require(world.activate(std::span(&*candidate, 1)).has_value(), "valid fixture activation refused"); +} +void edit(VoxelRegion& world, VoxelPosition p, MaterialId material) { + const VoxelEdit change{p, material, world.sample(p).stamp.revision}; + require(world.edit(std::span(&change, 1)).has_value(), "fixture edit refused"); +} +VoxelRegion flat(VoxelBounds bounds = {{0, 0, 0}, {8, 8, 4}}) { + VoxelRegion world({1, 42, 1, bounds}); + const auto low = split_voxel({static_cast(bounds.lower.x), static_cast(bounds.lower.y), static_cast(bounds.lower.z)}).chunk; + const auto high = split_voxel({static_cast(bounds.upper.x - 1), static_cast(bounds.upper.y - 1), static_cast(bounds.upper.z - 1)}).chunk; + for (auto z = low.z; z <= high.z; ++z) for (auto y = low.y; y <= high.y; ++y) for (auto x = low.x; x <= high.x; ++x) { + install(world, {x, y, z}, [](auto p) { return p.z == 0 ? MaterialId::Stone : MaterialId::Air; }); + } + return world; +} +VoxelPathRequest request(const VoxelRegion& world, VoxelPosition start, std::vector goals) { + return {world.descriptor().id, epoch(), start, world.descriptor().bounds, std::move(goals), {}}; +} +VoxelRegion stairs(bool closed) { + VoxelRegion world({7, 42, 1, {{28, 0, 0}, {38, 3, 8}}}); + for (int x : {0, 1}) install(world, {x, 0, 0}, [closed](auto p) { + const auto height = std::clamp(p.x - 31, 0, 3); + if (p.z <= height) return MaterialId::Stone; + if ((p.y == 0 || p.y == 2) && p.z <= height + 2) return MaterialId::Stone; + if (p.x == 30 && p.y == 1 && (p.z == 1 || p.z == 2)) return closed ? MaterialId::DoorClosed : MaterialId::DoorOpen; + return MaterialId::Air; + }); + return world; +} +void require_route(const VoxelRegion& world, const VoxelPathRequest& query, const VoxelPathResult& result) { + require(result.status == Status::Reachable && result.goal.has_value(), "expected a reachable goal"); + require(result.cost == result.route.size(), "cost differs from actual route"); + auto from = query.start; + for (auto to : result.route) { + require(voxel_transition(world, query.session, from, to).status == Status::Reachable, "returned route crosses invalid transition"); + from = to; + } + require(from == *result.goal && result.consulted.current(world, query.session), "route target or read stamps invalid"); + require(std::is_sorted(result.consulted.chunks.begin(), result.consulted.chunks.end(), + [](const auto& a, const auto& b) { return a.coordinate < b.coordinate; }), "read stamps not canonical"); +} + +struct [[= Void::Testing::name("VoxelNavigationTests")]] VoxelNavigationTests : Void::Testing::Suite { + [[= Void::Testing::tag("voxel-navigation")]] Test doorway_stairs_and_upper_work_contact(); + [[= Void::Testing::tag("voxel-navigation")]] Test support_edit_invalidates_route_before_next_step(); + [[= Void::Testing::tag("voxel-navigation")]] Test body_headroom_and_step_sweep_are_required(); + [[= Void::Testing::tag("voxel-navigation")]] Test missing_support_page_and_negative_answer_are_dependencies(); + [[= Void::Testing::tag("voxel-navigation")]] Test unchanged_chunks_and_old_snapshots_remain_usable(); + [[= Void::Testing::tag("voxel-navigation")]] Test bounded_search_has_distinct_incomplete_and_error_results(); + [[= Void::Testing::tag("voxel-navigation")]] Test invalid_same_goal_and_extreme_coordinate_windows(); + [[= Void::Testing::tag("voxel-navigation")]] Test goals_and_neighbors_have_stable_shortest_ties(); + [[= Void::Testing::tag("voxel-navigation")]] Test shortest_costs_match_exhaustive_small_grid(); + [[= Void::Testing::tag("voxel-navigation")]] Test real_parallel_queries_preserve_route_and_readsets(); +}; + +Test VoxelNavigationTests::doorway_stairs_and_upper_work_contact() { + auto world = stairs(true); + auto query = request(world, {29, 1, 1}, {{36, 1, 4}}); + auto blocked = find_voxel_path(world, query); + require(blocked.status == Status::Unreachable, "closed two-cell door was passable"); + const std::array changes{VoxelEdit{{30, 1, 1}, MaterialId::DoorOpen, 1}, VoxelEdit{{30, 1, 2}, MaterialId::DoorOpen, 1}}; + require(world.edit(changes).has_value(), "door opening failed"); + require(!blocked.consulted.current(world, epoch()), "door change retained negative result"); + auto found = find_voxel_path(world, query); + require_route(world, query, found); + require(found.cost == 7 && std::any_of(found.route.begin(), found.route.end(), [](auto p) { return p.x == 32 && p.z == 2; }), "path failed actual border stair"); + edit(world, {37, 1, 4}, MaterialId::Stone); + auto work = find_voxel_interaction_path(world, query, {37, 1, 4}); + require_route(world, query, work); + require(work.goal == VoxelPosition{36, 1, 4}, "upper work position lacks direct face contact"); +} +Test VoxelNavigationTests::support_edit_invalidates_route_before_next_step() { + auto world = stairs(false); + const auto query = request(world, {32, 1, 2}, {{36, 1, 4}}); + auto found = find_voxel_path(world, query); + require_route(world, query, found); + const auto held = world; + edit(world, {33, 1, 2}, MaterialId::Air); + require(!found.consulted.current(world, epoch()), "support change did not expire route"); + require(voxel_standing(world, epoch(), query.start).status == Status::Reachable, "future support edit invalidated current foot"); + require(voxel_transition(world, epoch(), query.start, found.route.front()).status == Status::Unreachable, "unsafe stored next step still allowed"); + require(find_voxel_path(world, query).status == Status::Unreachable, "missing stair allowed a two-cell rise"); + require(found.consulted.current(held, epoch()), "retained immutable geometry changed"); + edit(world, {33, 1, 2}, MaterialId::Stone); + require_route(world, query, find_voxel_path(world, query)); +} +Test VoxelNavigationTests::body_headroom_and_step_sweep_are_required() { + auto world = flat(); + require(voxel_standing(world, epoch(), {2, 2, 1}).status == Status::Reachable, "ordinary stance refused"); + edit(world, {3, 2, 1}, MaterialId::Stone); + require(voxel_transition(world, epoch(), {2, 2, 1}, {3, 2, 2}).status == Status::Reachable, "single stair refused"); + edit(world, {2, 2, 3}, MaterialId::Stone); + require(voxel_transition(world, epoch(), {2, 2, 1}, {3, 2, 2}).status == Status::Unreachable, "step rose through source ceiling"); + require(voxel_transition(world, epoch(), {3, 2, 2}, {2, 2, 1}).status == Status::Unreachable, "step descended through swept ceiling"); + edit(world, {2, 2, 3}, MaterialId::Air); + edit(world, {3, 2, 3}, MaterialId::DoorClosed); + require(voxel_standing(world, epoch(), {3, 2, 2}).status == Status::Unreachable, "head entered closed upper door"); + edit(world, {3, 2, 3}, MaterialId::DoorOpen); + require(voxel_transition(world, epoch(), {2, 2, 1}, {3, 2, 2}).status == Status::Reachable, "open door blocked head"); + require(voxel_transition(world, epoch(), {2, 2, 1}, {3, 3, 1}).status == Status::Unreachable, "diagonal corner cutting accepted"); + require(voxel_transition(world, epoch(), {2, 2, 1}, {2, 2, 2}).status == Status::Unreachable, "unsupported vertical movement accepted"); +} +Test VoxelNavigationTests::missing_support_page_and_negative_answer_are_dependencies() { + VoxelRegion world({1, 42, 1, {{-3, 0, -1}, {3, 3, 4}}}); + install(world, {-1, 0, 0}, [](auto) { return MaterialId::Air; }); + install(world, {0, 0, 0}, [](auto) { return MaterialId::Air; }); + auto check = voxel_standing(world, epoch(), {-1, 1, 0}); + require(check.status == Status::Unavailable, "unloaded support treated as empty or solid"); + require(std::any_of(check.consulted.chunks.begin(), check.consulted.chunks.end(), [](const auto& s) { return s.coordinate == ChunkCoordinate{-1, 0, -1} && s.availability == VoxelAvailability::Unavailable; }), "missing support page omitted from reads"); + install(world, {-1, 0, -1}, [](auto) { return MaterialId::Stone; }); + require(!check.consulted.current(world, epoch()), "missing-to-loaded support kept stale result"); + require(voxel_standing(world, epoch(), {-1, 1, 0}).status == Status::Reachable, "new support still unavailable"); + auto query = request(world, {-1, 1, 0}, {{1, 1, 0}}); + auto negative = find_voxel_path(world, query); + require(negative.status == Status::Unavailable, "missing route support was proven unreachable"); + install(world, {0, 0, -1}, [](auto) { return MaterialId::Stone; }); + require(!negative.consulted.current(world, epoch()), "negative path omitted queried missing chunk"); + require_route(world, query, find_voxel_path(world, query)); +} +Test VoxelNavigationTests::unchanged_chunks_and_old_snapshots_remain_usable() { + auto world = flat({{0, 0, 0}, {100, 8, 4}}); + auto query = request(world, {1, 1, 1}, {{5, 5, 1}}); + query.search_bounds.upper.x = 8; + auto route = find_voxel_path(world, query); + require_route(world, query, route); + edit(world, {97, 2, 1}, MaterialId::Stone); + require(route.consulted.current(world, epoch()), "unconsulted page invalidated a path"); + require(!route.consulted.current(world, epoch(2)), "old session accepted same numeric revisions"); + VoxelRegion other({2, 42, 1, world.descriptor().bounds}); + require(!route.consulted.current(other, epoch()), "another region accepted old route"); +} +Test VoxelNavigationTests::bounded_search_has_distinct_incomplete_and_error_results() { + auto world = flat(); + auto query = request(world, {1, 1, 1}, {{5, 5, 1}}); + query.limits.max_vertices = 1; + require(find_voxel_path(world, query).status == Status::LimitExceeded, "vertex budget fabricated unreachable"); + query.limits = {}; query.limits.max_scratch_bytes = 8; + require(find_voxel_path(world, query).status == Status::LimitExceeded, "scratch budget ignored"); + query.limits = {}; query.limits.max_steps = 1; + require(find_voxel_path(world, query).status == Status::LimitExceeded, "traversal budget fabricated unreachable"); + query.limits = {}; query.limits.max_samples = 2; + require(find_voxel_path(world, query).status == Status::LimitExceeded, "material query budget ignored"); + query.limits = {}; query.limits.max_dependencies = 0; + require(find_voxel_path(world, query).status == Status::LimitExceeded, "read-set bound ignored"); + query.limits = {}; query.limits.max_goals = 0; + require(find_voxel_path(world, query).status == Status::LimitExceeded, "goal bound ignored"); + query.limits = {}; + std::stop_source cancelled; cancelled.request_stop(); + require(find_voxel_path(world, query, cancelled.get_token()).status == Status::Cancelled, "cancellation fabricated unreachable"); + auto clipped_interaction = query; + clipped_interaction.search_bounds.upper = {2, 2, 4}; + require(find_voxel_interaction_path(world, clipped_interaction, {6, 6, 1}).status == Status::SearchBoundary, + "interaction with all feet clipped fabricated invalid input"); + clipped_interaction.region = 2; + require(find_voxel_interaction_path(world, clipped_interaction, {6, 6, 1}).status == Status::InvalidInput, + "clipped interaction bypassed region identity"); + query.search_bounds.upper.x = 4; query.goals = {{3, 5, 1}}; + for (int y = 0; y < 8; ++y) { edit(world, {2, y, 1}, MaterialId::Stone); edit(world, {2, y, 2}, MaterialId::Stone); } + // The accessible edge at x=0 has no escape (region bound), but y edges do + // not either. Make a window smaller than the region along y as well. + query.search_bounds.upper.y = 6; + require(find_voxel_path(world, query).status == Status::SearchBoundary, "clipped search claimed global unreachability"); + VoxelRegion sparse({1, 42, 1, {{std::numeric_limits::min(), 0, 0}, {std::int64_t{std::numeric_limits::max()} + 1, 8, 4}}}); + auto huge = request(sparse, {0, 1, 1}, {{1, 1, 1}}); + require(find_voxel_path(sparse, huge).status == Status::LimitExceeded, "sparse huge extent allocated densely"); +} +Test VoxelNavigationTests::invalid_same_goal_and_extreme_coordinate_windows() { + auto world = flat(); + auto query = request(world, {1, 1, 1}, {{1, 1, 1}}); + auto same = find_voxel_path(world, query); + require_route(world, query, same); + require(same.route.empty() && same.cost == 0, "already-at-goal result wrong"); + edit(world, {1, 1, 2}, MaterialId::Stone); + require(find_voxel_path(world, query).status == Status::Unreachable, "blocked start==goal bypassed geometry"); + query.session = {}; + require(find_voxel_path(world, query).status == Status::InvalidInput, "nil session accepted"); + for (auto x : {std::numeric_limits::min(), std::numeric_limits::max() - 3}) { + const VoxelBounds b{{x, 0, 0}, {std::int64_t{x} + 4, 3, 4}}; + auto edge = flat(b); + auto edge_query = request(edge, {x, 1, 1}, {{static_cast(std::int64_t{x} + 3), 1, 1}}); + const auto route = find_voxel_path(edge, edge_query); + require_route(edge, edge_query, route); + require(route.cost == 3, "extreme coordinate route wrapped"); + } +} +Test VoxelNavigationTests::goals_and_neighbors_have_stable_shortest_ties() { + auto world = flat(); + auto query = request(world, {3, 3, 1}, {{4, 3, 1}, {2, 3, 1}, {3, 4, 1}}); + auto result = find_voxel_path(world, query); + require(result.goal == VoxelPosition{2, 3, 1} && result.cost == 1, "equal goals depend on request order"); + std::reverse(query.goals.begin(), query.goals.end()); + require(find_voxel_path(world, query).route == result.route, "goal order changed route"); + query.goals = {{4, 4, 1}}; + result = find_voxel_path(world, query); + require(result.route == std::vector{{3, 4, 1}, {4, 4, 1}}, "equal paths violated coordinate neighbor order"); +} +Test VoxelNavigationTests::shortest_costs_match_exhaustive_small_grid() { + for (std::uint32_t pattern = 0; pattern < 16; ++pattern) { + std::array walls{}; + for (std::size_t i = 0; i < walls.size(); ++i) walls[i] = ((i * 13 + pattern * 7) % 17) < 4; + walls[8] = false; walls[40] = false; + auto world = flat({{0, 0, 0}, {7, 7, 4}}); + std::vector changes; + for (int y = 0; y < 7; ++y) for (int x = 0; x < 7; ++x) if (walls[static_cast(x + 7 * y)]) { + changes.push_back({{x, y, 1}, MaterialId::Stone, 1}); changes.push_back({{x, y, 2}, MaterialId::Stone, 1}); + } + require(world.edit(changes).has_value(), "small oracle fixture failed"); + std::array distance; distance.fill(-1); distance[8] = 0; + std::queue queue; queue.push(8); + while (!queue.empty()) { + const auto v = queue.front(); queue.pop(); + for (auto d : std::array, 4>{{{-1, 0}, {0, -1}, {0, 1}, {1, 0}}}) { + const int x = v % 7 + d[0], y = v / 7 + d[1]; + if (x < 0 || x >= 7 || y < 0 || y >= 7) continue; + const auto n = static_cast(x + 7 * y); + if (walls[n] || distance[n] >= 0) continue; + distance[n] = distance[static_cast(v)] + 1; queue.push(static_cast(n)); + } + } + auto query = request(world, {1, 1, 1}, {{5, 5, 1}}); + auto result = find_voxel_path(world, query); + if (distance[40] < 0) require(result.status == Status::Unreachable, "oracle blocked path found"); + else { + require_route(world, query, result); + require(result.cost == static_cast(distance[40]), "Void graph route differs from exhaustive grid cost"); + } + } +} +Test VoxelNavigationTests::real_parallel_queries_preserve_route_and_readsets() { + const auto world = stairs(false); + const auto query = request(world, {29, 1, 1}, {{36, 1, 4}}); + const auto expected = find_voxel_path(world, query); + require_route(world, query, expected); + for (std::size_t workers : {2U, 6U, 12U}) { + WorkerPool pool(workers); + std::vector> futures; + for (int i = 0; i < 12; ++i) futures.push_back(pool.submit([&] { return find_voxel_path(world, query); })); + std::reverse(futures.begin(), futures.end()); + for (auto& future : futures) { + auto result = future.get(); + require(result.status == expected.status && result.route == expected.route && result.goal == expected.goal && + result.consulted.chunks == expected.consulted.chunks, "worker completion order altered navigation"); + } + } +} +} // namespace