Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2017e5685a | ||
|
|
17389b23d7 | ||
|
|
7a7ff32e14 | ||
|
|
e7046a92a1 | ||
|
|
ee1eca7571 | ||
|
|
1ca481b8f9 | ||
|
|
6d1123e172 | ||
|
|
6279a60bf7 | ||
|
|
0d71bcf5d8 |
No files matched your search
@@ -48,7 +48,9 @@ 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/voxel_region.cpp
|
||||
engine/src/world.cpp
|
||||
engine/src/world_save.cpp
|
||||
)
|
||||
@@ -133,6 +135,8 @@ if(BUILD_TESTING)
|
||||
tests/save_service_tests.cpp
|
||||
tests/session_tests.cpp
|
||||
tests/snapshot_tests.cpp
|
||||
tests/voxel_navigation_tests.cpp
|
||||
tests/voxel_region_tests.cpp
|
||||
tests/test_main.cpp
|
||||
)
|
||||
target_link_libraries(settlement_core_tests PRIVATE settlement_core Void::Testing)
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# Review finite voxel region contracts before implementation
|
||||
|
||||
Task ID: M02-F1
|
||||
Role: astra_reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Read-only preflight of M02-P1 initial design from actual 455630f M02 worktree. The signed 32³ sparse page foundation is independent of M01 custody 539cea0 now in progress. Existing renderer already uses z as vertical height via x−y, (x+y)−z and existing viewer picks the z=0 plane. Library first M02-R1 confirmed pin 7b0fea6, upstream #11 signed division and #14 sparse atomic edits, #12 ray traversal, #13 revision readsets, #10 RNG; actual public math/binary/hash available.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Independently decide whether bounded S02 geometry/generation contract is safe to implement now. Review the later S03/normal runtime/save/presentation boundaries insofar as they constrain S02 data. Send foundation verdict early; root may later supply planner final addendum.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only M02 correctness preflight with first S02 slice priority. No implementation, release/PR acceptance, M03+ design or approval of unchecked future code.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read real M02 worktree docs/agent-workflow/tasks/M02-P1.md, M02-R1 and plans M02/S02/S03/S15/S17/S18, void-library.md; root existing world.hpp, world.cpp WorldState::capture, worker_pool, world_save and checkpoint, app/map_camera.hpp, d3d_scene_win32.cpp shader, viewer_win32.cpp pick_grid, first_colony and actual tests; private current15 in /tmp/stoneheart-milestones.xprJ2SVp/combined-custody. Inspect exact graph root only if relevant; direct sibling sources required.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No mutations/builds/remote posting, shared project switching, user contact or children.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Attack proposed NEW VoxelRegion/value view with nonzero RegionId, int32 voxel xyz, finite half-open bounds, ordered key directory/sharing immutable 32³ pages, generator keyed by exact seed+version+absolute xyz, queries separate outside/unloaded/loaded air. Page publication precedes ready only at logical designated step. Edits validate all expected revisions/bounds/materials/caps/unsupported operations, finite canonical order and no partial mutation, publish touched revisions once and invalidate face neighbors without fictitious content changes. Focus on material id stability, thin bounds intersecting pages and border operations. Query correctness at both signed extremes and boundary examples, no pointer/reference mutation. Check which exact domain is expected to be represented.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Review ownership/constructor/geometry exposure, immutable page pointers vs mutable alias to page/cache/directory, exact all-or-nothing publication, result visibility/cache invalidation incl reads of inactive/neighbors, validity of one stable geometry revision for render and path when head changes due to activation/deactivation. Propose minimal interfaces and stable tests without duplicating future WorldState. Check D3D renderer z-up and slice/face tie contract.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Foundation worker has isolated file ownership in NEW voxel_region.hpp/cpp/test plus CMake and S02 docs. World/runtime/save protocol integrating with S15/16 requires final agreed schema and cannot clobber S06 custody15. Preserve protocol11 by explicit representability; original 2D first colony must remain readable/playable.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Negative division at INT_MIN and max half-open bounds, dirty neighbor overflow at extreme chunk ids, seed sign/ordering/algorithm version, bounded page/batch memory and worst-case old snapshot retention, revision rollover/admission, no-op/duplicates/conflicting expectations; negative/zero ray incl edge tie, stale auth, work/tick exposure, failed chunk activation/crossing. Differentiate genre policies/materials and requested Void issues.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. READY or BLOCKED with precise mandatory first-slice fixes and testable criteria. 2. State if parallel independent implementation is sound within compiled M02 base before M01 finished. 3. Capture edge behavior and feasible tests for generation, bounds, stale atomic recompute, immutable view, deterministic batch and subsequent consumers. 4. Mark unknown physical target verification. Do not review a future code diff prematurely.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only git status/rev-parse and source refs in the M02 and combined worktrees. Compare pinned source with M02-R1 and note no binary evidence unless reading actual existing logs. Project index root-only; direct reads for sibling files. Later CTest should use exact Windows x64 GCC16/Wine test setup in M02-P1.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No approval of M01 scope or M02 implementation, no code, no Git/Gitea changes/children. If a substantial missing contract is identifiable, provide counterexample and precise remedy without tacking on speculative features.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User requested end-to-end milestone implementation and library gap filing. Preflight gates first edits, not engineering judgment on reversible local choices. Root integrates findings into worker specs and owns upstream effects.
|
||||
|
||||
## 14. Return format
|
||||
Return M02-F1 preflight with earliest foundation assessment then notes for remaining consumers, actual source references, required tests and stop conditions for implementation.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Design the first playable editable voxel region and its integration
|
||||
|
||||
Task ID: M02-P1
|
||||
Role: astra_planner
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
The user approved implementing M00–M12 on milestone and system branches. M01 currently provides a 50 ms authoritative World, immutable snapshots, authenticated commands, released rules profiles, protocol11 and modern checkpoints. M02 worktree at 455630f has S17 immutable frames and S21 real scheduler tests. Local M01 candidate 539cea0 adds modern raw15/checkpoint3 transfer persistence. An independent pin/API audit M02-R1 at Void 7b0fea6095f603f9e1904f66dfdc7752f4be4792 found library gaps reported as Void/Library #10–14. This is a preparatory design while M01 exit evidence is in flight.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Provide actionable dependency boundaries for M02 and the first implementable S02 region/chunk/component that can be built now without conflicting with M01 custody work. Continue to cover S03, S17/S18, S15 and normal owner/runtime end to end so the first terrain output has real consumers.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Read-only milestone architecture and phased, playable acceptance. Focus limited M02 editable voxel scenario through two levels and chunk edge. Defer M03 colony storage/building changes, water, other worlds, plugin changes and release. No arbitrary lowering of approved roadmap scope or new UI product choice.
|
||||
|
||||
## 4. Files to inspect
|
||||
Inspect docs/plan/milestones/M01.md and M02.md; docs/plan/systems/{S02,S03,S15,S17,S18,S21}.md, docs/plan/void-library.md and M02-R1; engine/include/settlement/core/{world,simulation_runtime,command_dispatcher,worker_pool,deterministic_rng}.hpp and world/first_colony/world_save CPU paths; app/d3d_scene_win32.*, map_camera.hpp, viewer_win32.cpp, tests/frame/replay/identity/checkpoint. Use actual names in results. Read sibling custody.hpp and checkpoint.hpp at combined 539cea0 to avoid schema collision. No fetching private data outside project.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
No edits, branch/remote ops, builds that modify worktrees, project switch or children. Parent persists results. Root and sibling agents are working in separate checkouts. For isolated M02 use direct files and avoid changing shared Serena project.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Map owner/tick/frame/file architecture, deterministic generation keyed by signed world location, gates for snapshots/cache and async activation. Specify finite 32³ sparse page representation and signed Euclidean division, fatal and retriable edit paths, exact row/coordinate order, native Win32 interaction scenario, known old-save/old-LAN behavior and how these can be tested using real consumers. Identify the first S02 slice that can receive an independent concrete coding contract at once; send it early.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Propose NEW clear types and methods by responsibility with essentials only: region identities/int coords with z up, bounds/limits, material query/source/support+edit revision set and undo on failure, copy-on-write pages immutable to snapshots, deterministic per-chunk source and edit overlay; S03 use cases incl stable ties, minimum profile/door/stairs and consulted revision sets incl misses and neighbors; ray/pick face from D3D Y-up conversion and actual commands; M02 persistent version/generator identity; reconcile normal M01 World lifecycle, actual public source/test consumers and authored test scenario. Distinguish proposed APIs from existing ones.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root reconciles M02-R1, planner, independent preflight and starts S02 in an isolated branch before coupling to mutable M01 sources when safe. Make ownership/dependency ordering and concrete integration points clear. Source-only private S06/S15 candidates must never be treated as published.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Bound coordinate overflow (INT_MIN, ±32), sparse memory and checked edit count, stale/mixed revisions, border invalidation, optimistic deterministic admission/queued jobs, signed normal/cell at equally crossed faces, old saves and LAN projections of edited maps, delayed/out-of-order and corrupted chunk I/O, camera/view consistency and finite scheduling. Respect pinned Void API/tests and replacement cases for #10–14 in repository matrix.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Concrete HOW/WHAT for S02 first worker including new files/headers/CMake and behavioral tests with cross-boundary negative coordinates, immutable snapshots, failed multi-page edit and independent generation. 2. Bounded follow-on packages S03, authoritative/edit/tick+save, real UI and exit verification with actual dependencies. 3. Identify genuine missing library contract only after checking pin and issues. 4. Normal small scenario is visible, editable, traversable and survives save/restore across thread order.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only git -C <m02> rev-parse HEAD/status/diff and git -C /tmp/stoneheart-milestones.xprJ2SVp/combined-custody show as needed; use direct source in sibling worktrees. Give real proposed CMake GCC16 cross and CTest commands for later workers based on /tmp/stoneheart-verify.KoZwE4o8/env.sh and existing target. Native Windows cannot be asserted from Wine.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Stop and report if a required product choice truly blocks first slice; use reversible decisions matching approved M02 otherwise. No source mutation, speculative library ticket, user messages, or children. Do not claim test execution.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User explicitly asks to implement all milestones, reuse library APIs and file concrete gaps. Root owns all side effects. User authorization already covers bounded M02 foundation and branch/MRs.
|
||||
|
||||
## 14. Return format
|
||||
Return M02-P1 PLAN with early immediately implementable S02 slice, dependency order/ownership, immutable contracts, concrete tests/risks/source refs and remaining evidence. No approval or merge decisions.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Implement immutable finite voxel regions and atomic multi-chunk edits
|
||||
|
||||
Task ID: S02-01
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Actual isolated system/s02-voxel-world at 0d71bcf, parent milestone/m02-voxel-world. M02-P1 plan and F1 independently accepted first slice. Existing first colony WorldState copied on capture and flat terrain remains, renderer z-up. Cross-toolchain CMake pin 7b0fea6095f603f9e1904f66dfdc7752f4be4792. Void Math::Numeric checked arithmetic, Binary::Writer and Hash public, signed split/atomic pages absent and tracked upstream #11/#14. M01 final custody in isolated siblings, no overlapping source needed.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Build a tested, ready-to-integrate finite authoritative voxel region with deterministic versioned terrain, signed coords and immutable chunk pages, checked all-or-nothing multi-page edits and accurate surface invalidation. The first file consumers are S03 nav queries, S17 surfaces and M02 World/serializer/activation. Freeze a usable header early and send actual declarations to root.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Only memory representation, generation, prepared page installation, querying and edits for the finite one-region M02 foundation. No unrelated RNG, terrain viewer, WorldState or format edits, S03 path solver, resource ledger, gameplay or network. Input/outcome types below are NEW and may be named idiomatically.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read docs/plan/milestones/M02.md, systems/S02 + S03, dependency matrix section M02 + actual pin headers/tests for Math/Numeric, Binary and Hash. Inspect world.hpp/world.cpp capture, default 2D semantics, actual 3D shader at app/d3d_scene_win32.cpp, CMake targets and registered Void::Testing suites. S06 / S15 provisional custody data unneeded. Read M02-P1/F1.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: NEW engine/include/settlement/core/voxel_region.hpp; NEW engine/src/voxel_region.cpp; NEW tests/voxel_region_tests.cpp; CMakeLists.txt only two source/test entries; docs/plan/systems/S02.md
|
||||
Your isolated s02 checkout only. Others work in separate WTs, do not overwrite or revert their changes. No Git/remote operations, shared Serena switch, children.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Define checked nonzero uint64 RegionId, int32 xyz with z-up, int64 half-open endpoints verifying within [INT32_MIN,INT32_MAX+1], strictly positive volume per axis (finite coordinate bounds need not densely allocate), chunk/local split no -INT_MIN, x-fast 32³ index. Stable material identifiers air/soil/stone, configurable bounded resident pages (default256), edit count (default4096), and actual checked staging/result/directory sizes (default allow full bounded batch). Region copies or dedicated immutable views share complete directory/pages via const ownership; no retained mutable aliases or mutable raw span. Immutable generator candidate is keyed by metadata/coords, source initialized independent of job ordering, deterministic generator1 with plausible soil surface/stone below and canonical absolute-coordinate encoding via actual Void Binary/Hash, uses no shared RNG. Mask all cells outside partial region.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Ordinary query distinguishes outside bounds vs unavailable vs loaded air; returns stable coordinate/read stamp matching caller lifetime. Separate pure generation/preparation from explicit all-or-nothing publication so later M02 owner controls logical tick. Region may not install result from a different region/seed/generator/coordinate or expired expectation. Keep page/availability paths usable by future persistence. A bounded atomic edit requires exact revision expectations for each touched chunk (including no-op), rejects duplicate cells, unsupported material/coords/bad expectations before publishing. Empty/all-identical edit has no changes. Sort changed cells/pages and actual neighbor invalidations canonically; increment once per truly changed page, unchanged neighbors keep material stamp, loading must be observable by dependencies. Extreme revision denies change before first effect. No need for unload until a later consumer, if implemented prevent ABA with persistent stamp. Define what finite bounds/unavailable neighbor contributes to dirty key.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Host only builds Windows; unit checks linked in actual settlement_core_tests. Root merges S02 into M02 and cumulative only after review. Need write stable header before dependent S03/S17 and alert parent if implementation materially changes contract. Other workers own old World/codec/camera, never edit those. Local implementation explicitly references Void/Library #11/#14 in S02 docs with exact replacement tests.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Widen origins, local indexes and neighbor math before conversion; avoid INT overflow/padding/endian and unbounded directory/grid construction. Bound working + staging memory before allocations and reject insufficient limits unchanged. Stage all pages and result list before final nonthrowing swap; preserve original content/pointer/revision on bad batch, allocation failure and MAX counter. External retained snapshots own memory separately, state its limit precisely. Prefer compact materials and deterministic column generation; full active 256 pages must not cause unrelated pages to be recopied on each edit. No nondeterministic unordered serialization or generation.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Exact split/join and x-fast indices at INT_MIN,−33,−32,−1,0,31,32,INT_MAX incl [max,max+1) and partial negative/extreme bounds. 2. Canonical full material content and revisions independent of forward/reverse/parallel preparation, real neighboring signed coordinate continuity/golden seed, precise different availability/air. 3. Two-page edit succeeds atomically and old view unchanged; stale second/unloaded/duplicate/unknown/budget/MAX fail unchanged, unchanged writes validate expectation and do not increment; correct face vs edge neighbor invalidation across boundaries. 4. No additional unlinked generic shim outside #11/#14; real release compilation and focused/full CTest, report actual footprint/copy behavior and evidence. 5. Document useful public operations in S02 and share frozen header.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s02-voxel-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 <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run --tag voxel-region at your build, complete CTest -V (coordinate any real windows via root) and git diff --check; logs /tmp/stoneheart-milestones.xprJ2SVp/s02-voxel-*.log. Native Windows beyond cross tests not verified. Test revision exhaustion via meaningful persistence/import or narrow deterministic seam without exposing an unchecked arbitrary setter.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not silently expand M02 to full renderer/World or change prior save formats. If dependency contract missing, verify pin plus check existing issues, report exact consumer/guarantee and root handles any filing. Two unsuccessful same-cause fixes escalate with original contract/evidence. No publishing or other checkout edits.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorizes all milestone/system coding, Gitea PRs and true Void gaps. Root chose region identity and finite signed z-up cells, M02 product decisions in milestone doc; planner/preflight complete for this slice. Concrete bounded storage/container choices delegated.
|
||||
|
||||
## 14. Return format
|
||||
Return S02-01 READY or PARTIAL, early frozen API and relevant coordinate/frame assumptions, controlled failure cases, working paths, actual verification counts/measurements/limits and remaining integration seams.
|
||||
|
||||
The M02 door uses two stable non-generated cell kinds, `MaterialId::DoorClosed` and `MaterialId::DoorOpen`, appended after Air, Soil and Stone. A closed door blocks body clearance; an open door and air permit clearance. Only Soil and Stone provide standing support. Publish NEW `voxel_blocks_passage(MaterialId)` and `voxel_provides_support(MaterialId)` queries for the navigation and presentation owners. Both halves of a door can be changed in the same checked edit batch. Invalid materials remain rejected. The generator produces natural materials only, and the gameplay owner controls who may operate or mine a door. Add tests for these shared semantics, both updating over a page boundary if applicable, and tell root when the adjusted header is frozen. This prevents a second source of door geometry, occupancy and invalidation in navigation.
|
||||
@@ -0,0 +1,52 @@
|
||||
# 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 <that dir> --parallel 6, run ctest --test-dir <that 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.
|
||||
|
||||
Review at `7a7ff32` found a confirmed negative-result bug. On a solid, loaded z=0 floor a downward candidate may sample an unloaded z=-1 support while the known solid destination foot conclusively forbids the transition. A two-high closed wall then appears to be waiting for unrelated activation. Retain the actual sampled stamps but classify missing data as a potential frontier only if the corresponding transition, standing goal or reachable continuation cannot already be ruled out. Add the walled-floor regression and a positive genuinely unavailable frontier. Check analogous search-boundary handling and real interaction targets. Keep the existing signature and scoped files.
|
||||
Independent interaction clipping finding at `17389b2`: a known blocked list of in-window contacts does not prove a global negative when additional valid interaction candidates lie outside the finite window and the reached search frontier can leave it. Reproduce in a flat 8×8×4 fixture, start (1,1,1), search upper.x=4, target stone (3,3,1), blockers (2,3,2), (3,2,2), (3,4,2) and (3,3,3). With a reachable contact at (4,3,1) the narrow search returns SearchBoundary; upper.x=6 must reach it. Preserve all prior fixed direct-goal and unknown-frontier contracts. Include cases without any traversable exit and with an unavailable exit, freeze actual before/after code and run 13 previous focused cases, new regression and full CTest under the shared GUI lock.
|
||||
@@ -22,6 +22,18 @@
|
||||
|
||||
## Проверки и выход
|
||||
|
||||
### Контракты первой реализации
|
||||
|
||||
Воксели имеют знаковые 32-битные координаты, высота растёт по оси `z`. Границы конечного региона задаются полуинтервалами с 64-битными концами, чтобы в них можно было включить последний положительный воксель. Чанк содержит 32³ ячеек; быстрее всего меняется индекс `x`. Отдельные результаты чтения обозначают воздух, недоступный чанк и координату за пределами региона. Генератор получает версию, seed и абсолютные координаты. Порядок подготовки страниц не влияет на материал.
|
||||
|
||||
Снимок региона разделяет неизменяемые страницы. Операция проверяет все ожидаемые ревизии, размер и бюджет до публикации. Пустая операция или запись прежнего материала сохраняет ревизию после проверки ожиданий. Дублированная координата отклоняет весь запрос. Изменение на грани оповещает соседний чанк, сохраняя его собственную ревизию материала. Реализация и проверки замены библиотечным API связаны с задачами о [знаковых координатах](https://git.faumaray.com/Void/Library/issues/11), [транзакциях страниц](https://git.faumaray.com/Void/Library/issues/14) и [зависимостях по ревизиям](https://git.faumaray.com/Void/Library/issues/13).
|
||||
|
||||
Житель занимает одну клетку в плане и две по высоте, поднимается на одну ступень. Поиск учитывает опору, свободное место для головы, дверь и соседние чанки, включая чтения, из-за которых путь не найден. Перед очередным перемещением житель перепроверяет переход. Удаление следующей ступени сохраняет его собственную позицию, груз и цель. Поиск через ещё не подготовленный чанк либо за пределами бюджета имеет отдельный результат.
|
||||
|
||||
Добыча создаёт авторитетный заказ с доступной соседней рабочей позицией. При завершении мир заранее проверяет правку и возможность зачислить материал по правилам S06. Удаление грунта и передача добычи выполняются одной операцией. Если для добычи нет места, заказ ждёт с указанием причины. Повтор принятой команды находит исходный заказ. Режим тестовой колонии имеет собственный манифест с версией генератора и определениями материалов.
|
||||
|
||||
Координатор принимает подготовленные чанки на назначенной границе такта в порядке координат. Во время ожидания он обслуживает загрузку и завершение программы. В сохранение попадают требуемые чанки, назначения работ и безопасная позиция после правки. Прежние колонии сохраняют прежнюю геометрию на высоте ноль. Форматы нового региона согласуются с подтверждённой версией сохранений M01. Текущий шейдер уже проецирует высоту `z`; луч выбора и видимый срез должны пользоваться той же проекцией. [Проектирование](../../agent-workflow/tasks/M02-P1.md) · [Проверка контрактов](../../agent-workflow/tasks/M02-F1.md)
|
||||
|
||||
- Житель проходит через вход, поднимается и работает на верхнем этаже. Закрытая стена не считается проходом. После перекрытия маршрута он строит обход либо показывает недоступность.
|
||||
- Игрок выкапывает тоннель и изменяет опору у края чанка. Геометрия, выбор мышью и проход согласованы с обеих сторон границы после сохранения и загрузки.
|
||||
- При перестановке порядка чтения и генерации журнал команд создаёт одинаковое состояние на каждом такте. Повреждённые данные не публикуются как загруженный чанк.
|
||||
|
||||
@@ -10,6 +10,34 @@
|
||||
|
||||
## Данные и ответственность
|
||||
|
||||
### Исполняемая основа ограниченного региона
|
||||
|
||||
`VoxelRegion` хранит ненулевой ID, seed, версию генератора и границы. Ячейки имеют знаковые координаты `int32`, а концы полуинтервалов используют `int64`, включая верхнюю границу `INT32_MAX + 1`. Деление на размер чанка округляет вниз, поэтому координата −1 попадает в чанк −1 и локальную ячейку 31. Индекс внутри страницы вычисляется как `x + 32 * (y + 32 * z)`. Результат `sample()` различает загруженный воздух, недоступную страницу и выход за границы. [Публичный контракт](../../../engine/include/settlement/core/voxel_region.hpp) · [Реализация](../../../engine/src/voxel_region.cpp)
|
||||
|
||||
Копия региона разделяет каталог и страницы через неизменяемые объекты. `directory()` возвращает владеющую ссылку на прежний каталог. Изменение создаёт новый каталог и копирует затронутые страницы. Срок жизни снимка охватывает все его материалы. Номер региона и `ChunkStamp` связывают чтение с состоянием доступности и ревизией страницы. Владелец мира дополнительно проверяет инкарнацию сеанса при загрузке партии.
|
||||
|
||||
`prepare_generated()` независимо готовит страницу генератора 1. Он кодирует seed, версию и координаты опорных столбцов в little-endian через `Void::Binary::Writer`, затем использует FNV-1a из `Void::Hash`. Интерполяция сетки с шагом 16 даёт высоты от −8 до 8. Верхние три слоя состоят из почвы, нижние — из камня. Соседние столбцы по горизонтальной оси отличаются по высоте максимум на одну ячейку. Область вне частичного чанка заполнена воздухом. Для seed 42 чанк (−1, −1, −1) имеет FNV-1a `13302332479434111011`; этот результат отдельно воспроизведён по закодированным полям. Подготовка не меняет каталог региона.
|
||||
|
||||
`prepare_restored()` проверяет полный размер страницы, ненулевую ревизию, материалы и воздух за границами, затем копирует данные вызывающего кода. `activate()` принимает весь набор подготовленных страниц одной операцией. Она проверяет точный дескриптор региона, дубликаты, бюджет и отсутствие уже опубликованной страницы. `edit()` проверяет ожидаемую ревизию каждой ячейки, даже если материал уже совпадает. Повтор координаты отклоняет весь запрос. Пустая и тождественная запись сохраняют ревизии. Исчерпанная ревизия запрещает изменение страницы. Все новые страницы, каталог и результат готовятся до публикации. При отказе прежние указатели, материалы и ревизии сохраняются.
|
||||
|
||||
Список изменённых чанков упорядочен по координатам `x,y,z`; список ячеек — по мировым координатам. Правка на грани добавляет пересекающего регион соседа в `dirty_chunks`. Это касается и недоступных соседей. Диагонали не включаются. Неизменившийся сосед сохраняет свою ревизию материала. Активация страницы оповещает все её соседние грани. Выгрузка страниц появится с отдельным контрактом сохранения их ревизий.
|
||||
|
||||
| Материал | Значение | Проход | Опора |
|
||||
| --- | --- | --- | --- |
|
||||
| Воздух | 0 | Свободен | Нет |
|
||||
| Почва | 1 | Занят | Есть |
|
||||
| Камень | 2 | Занят | Есть |
|
||||
| Закрытая дверь | 3 | Занят | Нет |
|
||||
| Открытая дверь | 4 | Свободен | Нет |
|
||||
|
||||
Навигация и изображение используют общие `voxel_blocks_passage()` и `voxel_provides_support()`. Генератор создаёт природные материалы. Игровая команда определяет право изменить дверь и обновляет обе её ячейки одной операцией, в том числе через границу страниц.
|
||||
|
||||
По умолчанию разрешены 256 страниц и 4096 ячеек в запросе. Лимиты полезных данных резидентного региона и одной транзакции равны 16 МиБ каждый. Проверяемая арифметика учитывает объекты страниц, каталог, сортируемый запрос, временную страницу и массивы результата до их выделения. На проверенной Windows x64-сборке страница занимает 32 776 байтов, запись каталога — 32 байта, каталог с 256 страницами — 8 398 872 байта. Служебные данные распределителя, подготовленные страницы и старые снимки, удерживаемые потребителями, имеют отдельный расход памяти. Будущий владелец ограничивает число таких потребителей.
|
||||
|
||||
Проверки `--tag voxel-region` покрывают отрицательные и предельные координаты, частичные страницы, порядок завершения настоящих задач на 2/6/12 исполнителях, границы двери, загрузку, точный отказ целого набора и неизменяемые снимки. На заполненном каталоге правка одной ячейки сохранила прежние 255 страниц. Отдельная программа по очереди вызвала отказ каждого выделения памяти при генерации, восстановлении, активации и правке двух страниц; все отказы сохранили прежний каталог. Переход на библиотечную реализацию должен повторить эти проверки. [Тесты региона](../../../tests/voxel_region_tests.cpp) · [Знаковая арифметика в VoidLibrary](https://git.faumaray.com/Void/Library/issues/11) · [Атомарные страницы в VoidLibrary](https://git.faumaray.com/Void/Library/issues/14)
|
||||
|
||||
Windows x64 Release с GCC 16.2 под Wine 11 прошла 14 проверок региона и весь CTest — 155 тестов ядра, 9 LAN, 14 клиента и испытание кадра с видимым D3D11 и WARP. В одном прогоне подготовка и активация 256 страниц заняли 57 917 мкс, правка одной ячейки — 11 мкс. Это измерение относится к данному прогону под Wine. Нативная Windows и аппаратная частота кадров ещё не проверены.
|
||||
|
||||
| Новый контракт | Содержимое и владелец |
|
||||
| --- | --- |
|
||||
| Позиция мира | Постоянный ID региона и знаковые целочисленные координаты вокселя. Вертикальная ось — `z`, горизонтальная плоскость — `x,y`. |
|
||||
|
||||
@@ -8,6 +8,34 @@
|
||||
|
||||
В прототипе есть 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` строит доступные позиции контакта с указанной клеткой. К ней должна примыкать грань тела жителя. Цель может находиться у ног, у головы, под ногами или непосредственно над головой. Цель должна быть загружена. Право добывать материал, менять дверь и удалять опору проверяет владелец работы. Выбранная позиция взаимодействия и следующий переход доступны для повторной проверки перед действием.
|
||||
|
||||
Позиции контакта за пределами окна поиска сохраняются для проверки отрицательного ответа. Если такой контакт допускает размещение жителя, достигнутый допустимый выход из окна даёт `SearchBoundary`, а достигнутый неопределённый переход требует загрузки данных. При известном отсутствии выхода результат остаётся `Unreachable`. Заблокированные контакты внутри окна не доказывают недоступность всех внешних позиций. Общий предел целей учитывает и пропущенные контакты.
|
||||
|
||||
Каждый ответ содержит `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 элементов находится в стеке. Владелец сохраняет входные данные запроса и страницы мира отдельно. Измерение памяти распределителя и принудительный отказ системного распределителя остаются отдельными проверками.
|
||||
|
||||
Ёмкости проверяются также против `vector::max_size()`. Непредставимая ёмкость возвращает `LimitExceeded` через каждую из четырёх публичных операций. Проверка с `max_dependencies = max_size() + 1` и максимальным байтовым бюджетом воспроизводит этот отказ без выделения указанной памяти.
|
||||
|
||||
Селектор `--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.
|
||||
|
||||
Проверка замечаний к `7a7ff32` воспроизвела ожидание отсутствующей страницы под сплошным полом и исключение `vector::reserve` при непредставимой ёмкости. После исправления прошли 13 проверок навигации и четыре полных набора с 168 случаями ядра, 9 LAN, 14 клиента и испытанием кадра за 4,61 с. Отдельно проверены недоступная цель за известной стеной, загруженная цель взаимодействия за ней, запрещённый переход за границу окна и настоящий ожидающий загрузки проход. Один предыдущий полный прогон встретил прежнюю проверку немедленного допуска при восстановлении клиента после сбоя, `viewer_session_tests.cpp:363`. Повтор этого набора и итоговый полный прогон прошли. Проверяемый файл клиента в этом срезе не изменялся.
|
||||
|
||||
Проверка замечания к `17389b2` воспроизвела ложную недоступность при единственном пригодном контакте за границей окна. После исправления узкое окно возвращает `SearchBoundary`, расширенное достигает той же позиции контакта. Изолированный старт и незагруженный проход проверены отдельно. Под Wine прошли 14 проверок навигации и полный `ctest -V` с блокировкой общего интерактивного окружения. Все четыре набора прошли, включая 169 случаев ядра, 9 LAN, 14 клиента и испытание кадра за 4,74 с.
|
||||
|
||||
## Пространственная модель
|
||||
|
||||
Позицию и материал предоставляет [S02](S02.md). Профиль движения определяет объём тела, высоту шага и разрешённые переходы. Для M02 нужен профиль обычного поселенца, движение по опоре, ступеням и лестницам. Особые способы движения добавляются вместе с соответствующими животными и боевыми участниками.
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
#include "settlement/core/voxel_region.hpp"
|
||||
#include <Void/Core/Uuid.hpp>
|
||||
#include <cstddef>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <stop_token>
|
||||
#include <vector>
|
||||
|
||||
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<ChunkStamp> 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<VoxelPosition> goals;
|
||||
VoxelNavigationLimits limits;
|
||||
};
|
||||
|
||||
struct VoxelPathResult {
|
||||
VoxelNavigationStatus status = VoxelNavigationStatus::InvalidInput;
|
||||
std::optional<VoxelPosition> goal;
|
||||
// Excludes start, includes goal. An already satisfied goal has an empty route.
|
||||
std::vector<VoxelPosition> 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
|
||||
@@ -0,0 +1,168 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <compare>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
namespace settlement {
|
||||
|
||||
using RegionId = std::uint64_t;
|
||||
inline constexpr std::int32_t voxel_chunk_side = 32;
|
||||
inline constexpr std::size_t voxel_chunk_cells = 32 * 32 * 32;
|
||||
inline constexpr std::uint32_t voxel_generator_version = 1;
|
||||
|
||||
struct VoxelPosition {
|
||||
std::int32_t x = 0, y = 0, z = 0;
|
||||
auto operator<=>(const VoxelPosition&) const = default;
|
||||
};
|
||||
struct ChunkCoordinate {
|
||||
std::int32_t x = 0, y = 0, z = 0;
|
||||
auto operator<=>(const ChunkCoordinate&) const = default;
|
||||
};
|
||||
struct VoxelEndpoint {
|
||||
std::int64_t x = 0, y = 0, z = 0;
|
||||
bool operator==(const VoxelEndpoint&) const = default;
|
||||
};
|
||||
struct VoxelBounds {
|
||||
VoxelEndpoint lower, upper;
|
||||
[[nodiscard]] bool contains(VoxelPosition position) const noexcept;
|
||||
bool operator==(const VoxelBounds&) const = default;
|
||||
};
|
||||
struct LocalVoxel {
|
||||
std::uint8_t x = 0, y = 0, z = 0;
|
||||
bool operator==(const LocalVoxel&) const = default;
|
||||
};
|
||||
struct VoxelAddress {
|
||||
ChunkCoordinate chunk;
|
||||
LocalVoxel local;
|
||||
};
|
||||
|
||||
[[nodiscard]] VoxelAddress split_voxel(VoxelPosition position) noexcept;
|
||||
[[nodiscard]] std::optional<VoxelPosition> join_voxel(ChunkCoordinate chunk, LocalVoxel local) noexcept;
|
||||
[[nodiscard]] std::optional<std::size_t> voxel_index(LocalVoxel local) noexcept;
|
||||
|
||||
enum class MaterialId : std::uint8_t { Air = 0, Soil = 1, Stone = 2, DoorClosed = 3, DoorOpen = 4 };
|
||||
[[nodiscard]] bool valid_voxel_material(MaterialId material) noexcept;
|
||||
[[nodiscard]] bool voxel_blocks_passage(MaterialId material) noexcept;
|
||||
[[nodiscard]] bool voxel_provides_support(MaterialId material) noexcept;
|
||||
|
||||
struct VoxelRegionDescriptor {
|
||||
RegionId id = 0;
|
||||
std::uint64_t seed = 0;
|
||||
std::uint32_t generator_version = voxel_generator_version;
|
||||
VoxelBounds bounds;
|
||||
bool operator==(const VoxelRegionDescriptor&) const = default;
|
||||
};
|
||||
struct VoxelLimits {
|
||||
std::size_t max_resident_chunks = 256;
|
||||
std::size_t max_edit_cells = 4096;
|
||||
// Budgets charge object and vector payloads. Allocator bookkeeping and
|
||||
// snapshots/prepared pages retained by the caller have separate lifetimes.
|
||||
std::size_t max_resident_bytes = 16 * 1024 * 1024;
|
||||
std::size_t max_transaction_bytes = 16 * 1024 * 1024;
|
||||
};
|
||||
enum class VoxelAvailability : std::uint8_t { Outside, Unavailable, Loaded };
|
||||
struct ChunkStamp {
|
||||
RegionId region = 0;
|
||||
ChunkCoordinate coordinate;
|
||||
VoxelAvailability availability = VoxelAvailability::Unavailable;
|
||||
std::uint64_t revision = 0;
|
||||
bool operator==(const ChunkStamp&) const = default;
|
||||
};
|
||||
struct VoxelSample {
|
||||
VoxelAvailability availability = VoxelAvailability::Outside;
|
||||
MaterialId material = MaterialId::Air;
|
||||
ChunkStamp stamp;
|
||||
};
|
||||
|
||||
class VoxelChunk {
|
||||
public:
|
||||
[[nodiscard]] std::uint64_t revision() const noexcept { return revision_; }
|
||||
[[nodiscard]] std::span<const MaterialId, voxel_chunk_cells> cells() const noexcept { return cells_; }
|
||||
private:
|
||||
friend class VoxelRegion;
|
||||
VoxelChunk(std::uint64_t revision, std::span<const MaterialId, voxel_chunk_cells> cells);
|
||||
std::uint64_t revision_;
|
||||
std::array<MaterialId, voxel_chunk_cells> cells_;
|
||||
};
|
||||
struct VoxelChunkEntry {
|
||||
ChunkCoordinate coordinate;
|
||||
std::shared_ptr<const VoxelChunk> chunk;
|
||||
};
|
||||
using VoxelDirectory = std::vector<VoxelChunkEntry>;
|
||||
|
||||
class PreparedVoxelChunk {
|
||||
public:
|
||||
[[nodiscard]] const VoxelRegionDescriptor& descriptor() const noexcept { return descriptor_; }
|
||||
[[nodiscard]] ChunkCoordinate coordinate() const noexcept { return coordinate_; }
|
||||
[[nodiscard]] const std::shared_ptr<const VoxelChunk>& chunk() const noexcept { return chunk_; }
|
||||
private:
|
||||
friend class VoxelRegion;
|
||||
PreparedVoxelChunk(VoxelRegionDescriptor descriptor, ChunkCoordinate coordinate,
|
||||
std::shared_ptr<const VoxelChunk> chunk);
|
||||
VoxelRegionDescriptor descriptor_;
|
||||
ChunkCoordinate coordinate_;
|
||||
std::shared_ptr<const VoxelChunk> chunk_;
|
||||
};
|
||||
|
||||
enum class VoxelError : std::uint8_t {
|
||||
InvalidCoordinate, InvalidMaterial, InvalidRevision, InvalidSource,
|
||||
Duplicate, Unavailable, Stale, RevisionExhausted, LimitExceeded, AllocationFailed
|
||||
};
|
||||
struct VoxelEdit {
|
||||
VoxelPosition position;
|
||||
MaterialId material = MaterialId::Air;
|
||||
std::uint64_t expected_revision = 0;
|
||||
};
|
||||
struct VoxelChange {
|
||||
VoxelPosition position;
|
||||
MaterialId before = MaterialId::Air;
|
||||
MaterialId after = MaterialId::Air;
|
||||
bool operator==(const VoxelChange&) const = default;
|
||||
};
|
||||
struct VoxelCommit {
|
||||
std::vector<ChunkStamp> changed_chunks;
|
||||
std::vector<VoxelChange> changed_cells;
|
||||
// Changed chunks and intersecting face-neighbors, including unavailable
|
||||
// neighbors. Unchanged neighbors keep their own material revision.
|
||||
std::vector<ChunkCoordinate> dirty_chunks;
|
||||
};
|
||||
|
||||
// Copies retain the complete immutable directory. A reader keeps its own copy
|
||||
// while the single owner publishes changes. Session identity fences snapshots
|
||||
// across save/load; this layer does not unload or reuse chunk revisions.
|
||||
class VoxelRegion {
|
||||
public:
|
||||
explicit VoxelRegion(VoxelRegionDescriptor descriptor, VoxelLimits limits = {});
|
||||
[[nodiscard]] const VoxelRegionDescriptor& descriptor() const noexcept { return descriptor_; }
|
||||
[[nodiscard]] const VoxelLimits& limits() const noexcept { return limits_; }
|
||||
[[nodiscard]] std::shared_ptr<const VoxelDirectory> directory() const noexcept { return directory_; }
|
||||
[[nodiscard]] std::size_t resident_bytes() const noexcept;
|
||||
[[nodiscard]] bool intersects(ChunkCoordinate coordinate) const noexcept;
|
||||
[[nodiscard]] ChunkStamp chunk_stamp(ChunkCoordinate coordinate) const noexcept;
|
||||
[[nodiscard]] bool matches(const ChunkStamp& stamp) const noexcept;
|
||||
[[nodiscard]] VoxelSample sample(VoxelPosition position) const noexcept;
|
||||
|
||||
[[nodiscard]] std::expected<PreparedVoxelChunk, VoxelError> prepare_generated(ChunkCoordinate coordinate) const;
|
||||
// Validated, deep-copied import for persistence, including exhausted valid
|
||||
// revisions. Cells outside a partial region must be canonical air.
|
||||
[[nodiscard]] std::expected<PreparedVoxelChunk, VoxelError> prepare_restored(
|
||||
ChunkCoordinate coordinate, std::uint64_t revision, std::span<const MaterialId> cells) const;
|
||||
// Activation only accepts unavailable chunks from this exact descriptor.
|
||||
// Every candidate is installed together or the directory is preserved.
|
||||
[[nodiscard]] std::expected<VoxelCommit, VoxelError> activate(std::span<const PreparedVoxelChunk> candidates);
|
||||
[[nodiscard]] std::expected<VoxelCommit, VoxelError> edit(std::span<const VoxelEdit> edits);
|
||||
|
||||
private:
|
||||
VoxelRegionDescriptor descriptor_;
|
||||
VoxelLimits limits_;
|
||||
std::shared_ptr<const VoxelDirectory> directory_;
|
||||
};
|
||||
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,306 @@
|
||||
#include "settlement/core/voxel_navigation.hpp"
|
||||
#include <Void/Algorithms/Graph.hpp>
|
||||
#include <Void/Math/Numeric.hpp>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace settlement {
|
||||
namespace {
|
||||
using Status = VoxelNavigationStatus;
|
||||
struct NavigationFailure { Status status; };
|
||||
|
||||
std::optional<VoxelPosition> 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<std::int32_t>::min();
|
||||
constexpr auto high = std::numeric_limits<std::int32_t>::max();
|
||||
if (nx < low || nx > high || ny < low || ny > high || nz < low || nz > high) return {};
|
||||
return VoxelPosition{static_cast<std::int32_t>(nx), static_cast<std::int32_t>(ny), static_cast<std::int32_t>(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};
|
||||
if (limits.max_dependencies > reads.chunks.max_size()) throw NavigationFailure{Status::LimitExceeded};
|
||||
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);
|
||||
}
|
||||
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;
|
||||
private:
|
||||
std::size_t samples_ = 0;
|
||||
};
|
||||
|
||||
struct NeighborList {
|
||||
std::array<std::size_t, 12> values{};
|
||||
std::size_t size = 0;
|
||||
auto begin() const { return values.begin(); }
|
||||
auto end() const { return values.begin() + static_cast<std::ptrdiff_t>(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::size_t>(std::int64_t{p.x} - bounds_.lower.x) + sx_ *
|
||||
(static_cast<std::size_t>(std::int64_t{p.y} - bounds_.lower.y) + sy_ *
|
||||
static_cast<std::size_t>(std::int64_t{p.z} - bounds_.lower.z));
|
||||
}
|
||||
VoxelPosition position(std::size_t i) const noexcept {
|
||||
return {static_cast<std::int32_t>(bounds_.lower.x + static_cast<std::int64_t>(i % sx_)),
|
||||
static_cast<std::int32_t>(bounds_.lower.y + static_cast<std::int64_t>((i / sx_) % sy_)),
|
||||
static_cast<std::int32_t>(bounds_.lower.z + static_cast<std::int64_t>(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<std::array<int, 2>, 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);
|
||||
// Only inconclusive edges out of reached vertices can extend the
|
||||
// search into missing data. Raw reads may already have been ruled
|
||||
// out by a known wall, floor or obstructed swept body volume.
|
||||
if (state == Status::Unavailable) unavailable = true;
|
||||
if (state != Status::Reachable) continue;
|
||||
if (!bounds_.contains(*to)) { boundary = true; continue; }
|
||||
result.values[result.size++] = index(*to);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
mutable bool boundary = false;
|
||||
mutable bool unavailable = false;
|
||||
private:
|
||||
Queries& queries_;
|
||||
VoxelBounds bounds_;
|
||||
std::size_t sx_, sy_, count_;
|
||||
};
|
||||
|
||||
VoxelPathResult search(Queries& queries, const VoxelPathRequest& request,
|
||||
std::span<const VoxelPosition> goals, std::span<const VoxelPosition> omitted = {}) {
|
||||
VoxelPathResult result;
|
||||
if (goals.empty() && omitted.empty()) return result;
|
||||
const auto& limits = request.limits;
|
||||
if (omitted.size() > limits.max_goals || goals.size() > limits.max_goals - omitted.size()) {
|
||||
result.status = Status::LimitExceeded; return result;
|
||||
}
|
||||
for (auto goal : goals) if (!request.search_bounds.contains(goal)) return result;
|
||||
const auto sx = static_cast<std::size_t>(request.search_bounds.upper.x - request.search_bounds.lower.x);
|
||||
const auto sy = static_cast<std::size_t>(request.search_bounds.upper.y - request.search_bounds.lower.y);
|
||||
const auto sz = static_cast<std::size_t>(request.search_bounds.upper.z - request.search_bounds.lower.z);
|
||||
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.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));
|
||||
if (!count || *count > limits.max_vertices || !vertex_bytes || !read_bytes ||
|
||||
*count > std::vector<std::size_t>{}.max_size() ||
|
||||
*count > std::vector<std::uint8_t>{}.max_size() ||
|
||||
*count > std::vector<VoxelPosition>{}.max_size()) {
|
||||
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);
|
||||
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;
|
||||
bool possible_goal = false;
|
||||
for (auto goal : goals) {
|
||||
// Explicit validation also covers the library's start==target fast path.
|
||||
const auto standing = queries.standing(goal);
|
||||
possible_goal = possible_goal || standing != Status::Unreachable;
|
||||
if (standing != 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) {
|
||||
// Interaction contacts outside the selected window still matter to a
|
||||
// global negative. Their feasibility cannot manufacture a frontier;
|
||||
// BFS must also have reached a valid exit or an unresolved transition.
|
||||
for (auto goal : omitted) {
|
||||
const auto standing = queries.standing(goal);
|
||||
possible_goal = possible_goal || standing != Status::Unreachable;
|
||||
}
|
||||
result.status = Status::Unreachable;
|
||||
if (possible_goal) {
|
||||
if (graph.unavailable) result.status = Status::Unavailable;
|
||||
else if (graph.boundary) result.status = Status::SearchBoundary;
|
||||
}
|
||||
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<class Function>
|
||||
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::length_error&) { result.status = Status::LimitExceeded; }
|
||||
catch (const std::bad_alloc&) { result.status = Status::AllocationFailed; }
|
||||
return result;
|
||||
}
|
||||
|
||||
VoxelPathResult path(const VoxelRegion& world, const VoxelPathRequest& request,
|
||||
std::optional<VoxelPosition> 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 {
|
||||
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<VoxelPosition, 10> goals{};
|
||||
std::array<VoxelPosition, 10> omitted{};
|
||||
std::size_t size = 0, omitted_size = 0;
|
||||
const auto add_goal = [&](std::optional<VoxelPosition> goal) {
|
||||
if (!goal) return;
|
||||
if (request.search_bounds.contains(*goal)) goals[size++] = *goal;
|
||||
else omitted[omitted_size++] = *goal;
|
||||
};
|
||||
constexpr std::array<std::array<int, 2>, 4> directions{{{-1, 0}, {0, -1}, {0, 1}, {1, 0}}};
|
||||
for (auto direction : directions) for (int dz : {-1, 0}) {
|
||||
add_goal(offset(*target, direction[0], direction[1], dz));
|
||||
}
|
||||
for (int dz : {-2, 1}) {
|
||||
add_goal(offset(*target, 0, 0, dz));
|
||||
}
|
||||
result = search(queries, request, std::span(goals.data(), size),
|
||||
std::span(omitted.data(), omitted_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::length_error&) { result.status = Status::LimitExceeded; }
|
||||
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
|
||||
@@ -0,0 +1,383 @@
|
||||
#include "settlement/core/voxel_region.hpp"
|
||||
|
||||
#include <Void/Binary/Writer.hpp>
|
||||
#include <Void/Core/Hash.hpp>
|
||||
#include <Void/Math/Numeric.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace settlement {
|
||||
namespace {
|
||||
constexpr auto coordinate_min = std::int64_t{std::numeric_limits<std::int32_t>::min()};
|
||||
constexpr auto coordinate_end = std::int64_t{std::numeric_limits<std::int32_t>::max()} + 1;
|
||||
|
||||
bool valid_interval(std::int64_t lower, std::int64_t upper) noexcept {
|
||||
return lower >= coordinate_min && upper <= coordinate_end && lower < upper;
|
||||
}
|
||||
std::pair<std::int32_t, std::uint8_t> split_axis(std::int32_t value) noexcept {
|
||||
auto chunk = value / voxel_chunk_side;
|
||||
auto local = value % voxel_chunk_side;
|
||||
if (local < 0) {
|
||||
--chunk;
|
||||
local += voxel_chunk_side;
|
||||
}
|
||||
return {chunk, static_cast<std::uint8_t>(local)};
|
||||
}
|
||||
VoxelEndpoint chunk_origin(ChunkCoordinate coordinate) noexcept {
|
||||
return {std::int64_t{coordinate.x} * voxel_chunk_side,
|
||||
std::int64_t{coordinate.y} * voxel_chunk_side,
|
||||
std::int64_t{coordinate.z} * voxel_chunk_side};
|
||||
}
|
||||
bool overlapping_axis(std::int64_t origin, std::int64_t lower, std::int64_t upper) noexcept {
|
||||
return origin < upper && origin + voxel_chunk_side > lower;
|
||||
}
|
||||
auto find_chunk(const VoxelDirectory& directory, ChunkCoordinate coordinate) noexcept {
|
||||
return std::lower_bound(directory.begin(), directory.end(), coordinate,
|
||||
[](const auto& entry, auto key) { return entry.coordinate < key; });
|
||||
}
|
||||
class PayloadBudget {
|
||||
public:
|
||||
explicit PayloadBudget(std::size_t limit) : remaining_(limit) {}
|
||||
bool take(std::size_t count, std::size_t size) noexcept {
|
||||
const auto bytes = Void::Numeric::checked_mul(count, size);
|
||||
if (!bytes || *bytes > remaining_) return false;
|
||||
remaining_ -= *bytes;
|
||||
return true;
|
||||
}
|
||||
private:
|
||||
std::size_t remaining_;
|
||||
};
|
||||
|
||||
std::uint64_t terrain_hash(std::uint64_t seed, std::int64_t x, std::int64_t y) {
|
||||
std::array<std::byte, 40> bytes{};
|
||||
Void::Binary::Writer writer(bytes);
|
||||
if (!writer.writeLittle(seed) || !writer.writeLittle(voxel_generator_version) ||
|
||||
!writer.writeLittle(std::uint32_t{1}) || !writer.writeLittle(x) ||
|
||||
!writer.writeLittle(y) || !writer.writeLittle(std::int64_t{0})) {
|
||||
throw std::logic_error("voxel generator field layout exceeds its fixed buffer");
|
||||
}
|
||||
return Void::Hash::fnv1a64(writer.written());
|
||||
}
|
||||
std::int64_t surface_height(std::uint64_t seed, std::int32_t x, std::int32_t y) {
|
||||
// Interpolate absolute lattice columns to keep adjacent heights within one
|
||||
// voxel. Widened lattice endpoints also cover the final int32 column.
|
||||
const auto lattice = [](std::int32_t value) {
|
||||
std::int64_t quotient = value / 16;
|
||||
if (value % 16 < 0) --quotient;
|
||||
return quotient * 16;
|
||||
};
|
||||
const auto x0 = lattice(x), y0 = lattice(y);
|
||||
const auto dx = std::int64_t{x} - x0, dy = std::int64_t{y} - y0;
|
||||
const auto height = [seed](std::int64_t a, std::int64_t b) {
|
||||
return static_cast<std::int64_t>(terrain_hash(seed, a, b) % 17) - 8;
|
||||
};
|
||||
const auto numerator = height(x0, y0) * (16 - dx) * (16 - dy) +
|
||||
height(x0 + 16, y0) * dx * (16 - dy) +
|
||||
height(x0, y0 + 16) * (16 - dx) * dy + height(x0 + 16, y0 + 16) * dx * dy;
|
||||
auto result = numerator / 256;
|
||||
if (numerator % 256 < 0) --result;
|
||||
return result;
|
||||
}
|
||||
void add_neighbor(const VoxelRegion& region, std::vector<ChunkCoordinate>& dirty,
|
||||
ChunkCoordinate coordinate, int axis, int delta) {
|
||||
std::array<std::int64_t, 3> values{coordinate.x, coordinate.y, coordinate.z};
|
||||
values[static_cast<std::size_t>(axis)] += delta;
|
||||
if (values[static_cast<std::size_t>(axis)] < coordinate_min ||
|
||||
values[static_cast<std::size_t>(axis)] >= coordinate_end) return;
|
||||
const ChunkCoordinate neighbor{static_cast<std::int32_t>(values[0]),
|
||||
static_cast<std::int32_t>(values[1]), static_cast<std::int32_t>(values[2])};
|
||||
if (region.intersects(neighbor)) dirty.push_back(neighbor);
|
||||
}
|
||||
void canonicalize(std::vector<ChunkCoordinate>& coordinates) {
|
||||
std::sort(coordinates.begin(), coordinates.end());
|
||||
coordinates.erase(std::unique(coordinates.begin(), coordinates.end()), coordinates.end());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool VoxelBounds::contains(VoxelPosition position) const noexcept {
|
||||
return position.x >= lower.x && position.x < upper.x &&
|
||||
position.y >= lower.y && position.y < upper.y &&
|
||||
position.z >= lower.z && position.z < upper.z;
|
||||
}
|
||||
VoxelAddress split_voxel(VoxelPosition position) noexcept {
|
||||
const auto [cx, lx] = split_axis(position.x);
|
||||
const auto [cy, ly] = split_axis(position.y);
|
||||
const auto [cz, lz] = split_axis(position.z);
|
||||
return {{cx, cy, cz}, {lx, ly, lz}};
|
||||
}
|
||||
std::optional<std::size_t> voxel_index(LocalVoxel local) noexcept {
|
||||
if (local.x >= voxel_chunk_side || local.y >= voxel_chunk_side || local.z >= voxel_chunk_side) return {};
|
||||
return std::size_t{local.x} + 32 * (std::size_t{local.y} + 32 * std::size_t{local.z});
|
||||
}
|
||||
std::optional<VoxelPosition> join_voxel(ChunkCoordinate chunk, LocalVoxel local) noexcept {
|
||||
if (!voxel_index(local)) return {};
|
||||
const auto origin = chunk_origin(chunk);
|
||||
const auto x = origin.x + local.x, y = origin.y + local.y, z = origin.z + local.z;
|
||||
if (x < coordinate_min || x >= coordinate_end || y < coordinate_min || y >= coordinate_end ||
|
||||
z < coordinate_min || z >= coordinate_end) return {};
|
||||
return VoxelPosition{static_cast<std::int32_t>(x), static_cast<std::int32_t>(y), static_cast<std::int32_t>(z)};
|
||||
}
|
||||
bool valid_voxel_material(MaterialId material) noexcept {
|
||||
return material >= MaterialId::Air && material <= MaterialId::DoorOpen;
|
||||
}
|
||||
bool voxel_blocks_passage(MaterialId material) noexcept {
|
||||
return material == MaterialId::Soil || material == MaterialId::Stone || material == MaterialId::DoorClosed;
|
||||
}
|
||||
bool voxel_provides_support(MaterialId material) noexcept {
|
||||
return material == MaterialId::Soil || material == MaterialId::Stone;
|
||||
}
|
||||
|
||||
VoxelChunk::VoxelChunk(std::uint64_t revision, std::span<const MaterialId, voxel_chunk_cells> cells)
|
||||
: revision_(revision) {
|
||||
std::copy(cells.begin(), cells.end(), cells_.begin());
|
||||
}
|
||||
PreparedVoxelChunk::PreparedVoxelChunk(VoxelRegionDescriptor descriptor, ChunkCoordinate coordinate,
|
||||
std::shared_ptr<const VoxelChunk> chunk)
|
||||
: descriptor_(descriptor), coordinate_(coordinate), chunk_(std::move(chunk)) {}
|
||||
|
||||
VoxelRegion::VoxelRegion(VoxelRegionDescriptor descriptor, VoxelLimits limits)
|
||||
: descriptor_(descriptor), limits_(limits) {
|
||||
const auto& bounds = descriptor.bounds;
|
||||
if (!descriptor.id || descriptor.generator_version != voxel_generator_version ||
|
||||
!valid_interval(bounds.lower.x, bounds.upper.x) || !valid_interval(bounds.lower.y, bounds.upper.y) ||
|
||||
!valid_interval(bounds.lower.z, bounds.upper.z) || !limits.max_resident_chunks || !limits.max_edit_cells ||
|
||||
limits.max_resident_bytes < sizeof(VoxelDirectory) || !limits.max_transaction_bytes) {
|
||||
throw std::invalid_argument("invalid voxel region descriptor or limits");
|
||||
}
|
||||
directory_ = std::make_shared<const VoxelDirectory>();
|
||||
}
|
||||
std::size_t VoxelRegion::resident_bytes() const noexcept {
|
||||
return sizeof(VoxelDirectory) + directory_->size() * (sizeof(VoxelChunkEntry) + sizeof(VoxelChunk));
|
||||
}
|
||||
bool VoxelRegion::intersects(ChunkCoordinate coordinate) const noexcept {
|
||||
const auto origin = chunk_origin(coordinate);
|
||||
const auto& bounds = descriptor_.bounds;
|
||||
return overlapping_axis(origin.x, bounds.lower.x, bounds.upper.x) &&
|
||||
overlapping_axis(origin.y, bounds.lower.y, bounds.upper.y) &&
|
||||
overlapping_axis(origin.z, bounds.lower.z, bounds.upper.z);
|
||||
}
|
||||
ChunkStamp VoxelRegion::chunk_stamp(ChunkCoordinate coordinate) const noexcept {
|
||||
ChunkStamp result{descriptor_.id, coordinate, VoxelAvailability::Outside, 0};
|
||||
if (!intersects(coordinate)) return result;
|
||||
const auto entry = find_chunk(*directory_, coordinate);
|
||||
result.availability = VoxelAvailability::Unavailable;
|
||||
if (entry != directory_->end() && entry->coordinate == coordinate) {
|
||||
result.availability = VoxelAvailability::Loaded;
|
||||
result.revision = entry->chunk->revision();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
bool VoxelRegion::matches(const ChunkStamp& stamp) const noexcept {
|
||||
return chunk_stamp(stamp.coordinate) == stamp;
|
||||
}
|
||||
VoxelSample VoxelRegion::sample(VoxelPosition position) const noexcept {
|
||||
const auto address = split_voxel(position);
|
||||
VoxelSample result{VoxelAvailability::Outside, MaterialId::Air, chunk_stamp(address.chunk)};
|
||||
if (!descriptor_.bounds.contains(position)) return result;
|
||||
result.availability = result.stamp.availability;
|
||||
if (result.availability == VoxelAvailability::Loaded) {
|
||||
result.material = find_chunk(*directory_, address.chunk)->chunk->cells()[*voxel_index(address.local)];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::expected<PreparedVoxelChunk, VoxelError> VoxelRegion::prepare_generated(ChunkCoordinate coordinate) const {
|
||||
if (!intersects(coordinate)) return std::unexpected(VoxelError::InvalidCoordinate);
|
||||
PayloadBudget budget(limits_.max_transaction_bytes);
|
||||
if (!budget.take(1, sizeof(VoxelChunk)) || !budget.take(voxel_chunk_cells, sizeof(MaterialId))) {
|
||||
return std::unexpected(VoxelError::LimitExceeded);
|
||||
}
|
||||
try {
|
||||
std::array<MaterialId, voxel_chunk_cells> cells{};
|
||||
const auto origin = chunk_origin(coordinate);
|
||||
for (std::int32_t y = 0; y < voxel_chunk_side; ++y) {
|
||||
for (std::int32_t x = 0; x < voxel_chunk_side; ++x) {
|
||||
const auto px = static_cast<std::int32_t>(origin.x + x);
|
||||
const auto py = static_cast<std::int32_t>(origin.y + y);
|
||||
const auto height = surface_height(descriptor_.seed, px, py);
|
||||
for (std::int32_t z = 0; z < voxel_chunk_side; ++z) {
|
||||
const VoxelPosition position{px, py, static_cast<std::int32_t>(origin.z + z)};
|
||||
if (!descriptor_.bounds.contains(position) || position.z > height) continue;
|
||||
const auto material = position.z > height - 3 ? MaterialId::Soil : MaterialId::Stone;
|
||||
const auto index = static_cast<std::size_t>(x + 32 * (y + 32 * z));
|
||||
cells[index] = material;
|
||||
}
|
||||
}
|
||||
}
|
||||
auto chunk = std::shared_ptr<const VoxelChunk>(new const VoxelChunk(1, cells));
|
||||
return PreparedVoxelChunk(descriptor_, coordinate, std::move(chunk));
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected(VoxelError::AllocationFailed);
|
||||
}
|
||||
}
|
||||
std::expected<PreparedVoxelChunk, VoxelError> VoxelRegion::prepare_restored(
|
||||
ChunkCoordinate coordinate, std::uint64_t revision, std::span<const MaterialId> cells) const {
|
||||
if (!intersects(coordinate)) return std::unexpected(VoxelError::InvalidCoordinate);
|
||||
if (!revision) return std::unexpected(VoxelError::InvalidRevision);
|
||||
if (cells.size() != voxel_chunk_cells) return std::unexpected(VoxelError::InvalidSource);
|
||||
if (limits_.max_transaction_bytes < sizeof(VoxelChunk)) return std::unexpected(VoxelError::LimitExceeded);
|
||||
for (std::size_t i = 0; i < cells.size(); ++i) {
|
||||
if (!valid_voxel_material(cells[i])) return std::unexpected(VoxelError::InvalidMaterial);
|
||||
const auto position = join_voxel(coordinate,
|
||||
{static_cast<std::uint8_t>(i % 32), static_cast<std::uint8_t>((i / 32) % 32),
|
||||
static_cast<std::uint8_t>(i / 1024)});
|
||||
if (!position || (!descriptor_.bounds.contains(*position) && cells[i] != MaterialId::Air)) {
|
||||
return std::unexpected(VoxelError::InvalidCoordinate);
|
||||
}
|
||||
}
|
||||
try {
|
||||
const std::span<const MaterialId, voxel_chunk_cells> fixed(cells.data(), voxel_chunk_cells);
|
||||
auto chunk = std::shared_ptr<const VoxelChunk>(new const VoxelChunk(revision, fixed));
|
||||
return PreparedVoxelChunk(descriptor_, coordinate, std::move(chunk));
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected(VoxelError::AllocationFailed);
|
||||
}
|
||||
}
|
||||
|
||||
std::expected<VoxelCommit, VoxelError> VoxelRegion::activate(std::span<const PreparedVoxelChunk> candidates) {
|
||||
if (candidates.empty()) return VoxelCommit{};
|
||||
if (candidates.size() > limits_.max_resident_chunks - directory_->size()) {
|
||||
return std::unexpected(VoxelError::LimitExceeded);
|
||||
}
|
||||
const auto count = directory_->size() + candidates.size();
|
||||
PayloadBudget resident(limits_.max_resident_bytes);
|
||||
PayloadBudget staging(limits_.max_transaction_bytes);
|
||||
const auto dirty_count = Void::Numeric::checked_mul(candidates.size(), std::size_t{7});
|
||||
if (!dirty_count || !resident.take(1, sizeof(VoxelDirectory)) ||
|
||||
!resident.take(count, sizeof(VoxelChunkEntry) + sizeof(VoxelChunk)) ||
|
||||
!staging.take(1, sizeof(VoxelDirectory)) || !staging.take(count, sizeof(VoxelChunkEntry)) ||
|
||||
!staging.take(candidates.size(), sizeof(VoxelChunk) + sizeof(ChunkStamp)) ||
|
||||
!staging.take(*dirty_count, sizeof(ChunkCoordinate))) {
|
||||
return std::unexpected(VoxelError::LimitExceeded);
|
||||
}
|
||||
try {
|
||||
auto next = std::make_shared<VoxelDirectory>();
|
||||
next->reserve(count);
|
||||
next->insert(next->end(), directory_->begin(), directory_->end());
|
||||
VoxelCommit result;
|
||||
result.changed_chunks.reserve(candidates.size());
|
||||
result.dirty_chunks.reserve(*dirty_count);
|
||||
for (const auto& candidate : candidates) {
|
||||
if (candidate.descriptor_ != descriptor_ || !candidate.chunk_ || !intersects(candidate.coordinate_)) {
|
||||
return std::unexpected(VoxelError::InvalidSource);
|
||||
}
|
||||
if (chunk_stamp(candidate.coordinate_).availability != VoxelAvailability::Unavailable) {
|
||||
return std::unexpected(VoxelError::Stale);
|
||||
}
|
||||
next->push_back({candidate.coordinate_, candidate.chunk_});
|
||||
result.changed_chunks.push_back({descriptor_.id, candidate.coordinate_,
|
||||
VoxelAvailability::Loaded, candidate.chunk_->revision()});
|
||||
result.dirty_chunks.push_back(candidate.coordinate_);
|
||||
for (int axis = 0; axis < 3; ++axis) {
|
||||
add_neighbor(*this, result.dirty_chunks, candidate.coordinate_, axis, -1);
|
||||
add_neighbor(*this, result.dirty_chunks, candidate.coordinate_, axis, 1);
|
||||
}
|
||||
}
|
||||
std::sort(next->begin(), next->end(), [](const auto& a, const auto& b) { return a.coordinate < b.coordinate; });
|
||||
for (std::size_t i = 1; i < next->size(); ++i) {
|
||||
if ((*next)[i - 1].coordinate == (*next)[i].coordinate) return std::unexpected(VoxelError::Duplicate);
|
||||
}
|
||||
std::sort(result.changed_chunks.begin(), result.changed_chunks.end(),
|
||||
[](const auto& a, const auto& b) { return a.coordinate < b.coordinate; });
|
||||
canonicalize(result.dirty_chunks);
|
||||
std::shared_ptr<const VoxelDirectory> publication(std::move(next));
|
||||
directory_.swap(publication);
|
||||
return result;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected(VoxelError::AllocationFailed);
|
||||
}
|
||||
}
|
||||
|
||||
std::expected<VoxelCommit, VoxelError> VoxelRegion::edit(std::span<const VoxelEdit> edits) {
|
||||
if (edits.empty()) return VoxelCommit{};
|
||||
if (edits.size() > limits_.max_edit_cells) return std::unexpected(VoxelError::LimitExceeded);
|
||||
PayloadBudget staging(limits_.max_transaction_bytes);
|
||||
if (!staging.take(edits.size(), sizeof(VoxelEdit))) return std::unexpected(VoxelError::LimitExceeded);
|
||||
try {
|
||||
std::vector<VoxelEdit> ordered(edits.begin(), edits.end());
|
||||
std::sort(ordered.begin(), ordered.end(), [](const auto& a, const auto& b) {
|
||||
const auto ca = split_voxel(a.position).chunk, cb = split_voxel(b.position).chunk;
|
||||
return ca == cb ? a.position < b.position : ca < cb;
|
||||
});
|
||||
std::size_t changed_pages = 0, changed_cells = 0;
|
||||
std::optional<ChunkCoordinate> last_changed;
|
||||
for (std::size_t i = 0; i < ordered.size(); ++i) {
|
||||
const auto& change = ordered[i];
|
||||
if (i && ordered[i - 1].position == change.position) return std::unexpected(VoxelError::Duplicate);
|
||||
if (!valid_voxel_material(change.material)) return std::unexpected(VoxelError::InvalidMaterial);
|
||||
const auto current = sample(change.position);
|
||||
if (current.availability == VoxelAvailability::Outside) return std::unexpected(VoxelError::InvalidCoordinate);
|
||||
if (current.availability == VoxelAvailability::Unavailable) return std::unexpected(VoxelError::Unavailable);
|
||||
if (current.stamp.revision != change.expected_revision) return std::unexpected(VoxelError::Stale);
|
||||
if (current.material == change.material) continue;
|
||||
if (current.stamp.revision == std::numeric_limits<std::uint64_t>::max()) {
|
||||
return std::unexpected(VoxelError::RevisionExhausted);
|
||||
}
|
||||
++changed_cells;
|
||||
if (!last_changed || *last_changed != current.stamp.coordinate) {
|
||||
++changed_pages;
|
||||
last_changed = current.stamp.coordinate;
|
||||
}
|
||||
}
|
||||
if (!changed_cells) return VoxelCommit{};
|
||||
const auto dirty_count = Void::Numeric::checked_mul(changed_cells, std::size_t{4});
|
||||
if (!dirty_count || !staging.take(1, sizeof(VoxelDirectory)) ||
|
||||
!staging.take(directory_->size(), sizeof(VoxelChunkEntry)) ||
|
||||
!staging.take(changed_pages, sizeof(VoxelChunk) + sizeof(ChunkStamp)) ||
|
||||
!staging.take(voxel_chunk_cells, sizeof(MaterialId)) ||
|
||||
!staging.take(changed_cells, sizeof(VoxelChange)) ||
|
||||
!staging.take(*dirty_count, sizeof(ChunkCoordinate))) {
|
||||
return std::unexpected(VoxelError::LimitExceeded);
|
||||
}
|
||||
auto next = std::make_shared<VoxelDirectory>(*directory_);
|
||||
VoxelCommit result;
|
||||
result.changed_cells.reserve(changed_cells);
|
||||
result.changed_chunks.reserve(changed_pages);
|
||||
result.dirty_chunks.reserve(*dirty_count);
|
||||
for (std::size_t first = 0; first < ordered.size();) {
|
||||
const auto coordinate = split_voxel(ordered[first].position).chunk;
|
||||
auto last = first + 1;
|
||||
while (last < ordered.size() && split_voxel(ordered[last].position).chunk == coordinate) ++last;
|
||||
const auto old = find_chunk(*directory_, coordinate);
|
||||
std::array<MaterialId, voxel_chunk_cells> cells;
|
||||
std::copy(old->chunk->cells().begin(), old->chunk->cells().end(), cells.begin());
|
||||
const auto count_before = result.changed_cells.size();
|
||||
for (auto i = first; i < last; ++i) {
|
||||
const auto& change = ordered[i];
|
||||
const auto local = split_voxel(change.position).local;
|
||||
auto& material = cells[*voxel_index(local)];
|
||||
if (material == change.material) continue;
|
||||
result.changed_cells.push_back({change.position, material, change.material});
|
||||
material = change.material;
|
||||
result.dirty_chunks.push_back(coordinate);
|
||||
const std::array<std::uint8_t, 3> axes{local.x, local.y, local.z};
|
||||
for (int axis = 0; axis < 3; ++axis) {
|
||||
if (axes[static_cast<std::size_t>(axis)] == 0) add_neighbor(*this, result.dirty_chunks, coordinate, axis, -1);
|
||||
if (axes[static_cast<std::size_t>(axis)] == 31) add_neighbor(*this, result.dirty_chunks, coordinate, axis, 1);
|
||||
}
|
||||
}
|
||||
if (result.changed_cells.size() != count_before) {
|
||||
const auto revision = old->chunk->revision() + 1;
|
||||
auto chunk = std::shared_ptr<const VoxelChunk>(new const VoxelChunk(revision, cells));
|
||||
const auto index = static_cast<std::size_t>(old - directory_->begin());
|
||||
(*next)[index].chunk = std::move(chunk);
|
||||
result.changed_chunks.push_back({descriptor_.id, coordinate, VoxelAvailability::Loaded, revision});
|
||||
}
|
||||
first = last;
|
||||
}
|
||||
std::sort(result.changed_cells.begin(), result.changed_cells.end(),
|
||||
[](const auto& a, const auto& b) { return a.position < b.position; });
|
||||
canonicalize(result.dirty_chunks);
|
||||
std::shared_ptr<const VoxelDirectory> publication(std::move(next));
|
||||
directory_.swap(publication);
|
||||
return result;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected(VoxelError::AllocationFailed);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace settlement
|
||||
@@ -0,0 +1,392 @@
|
||||
#include "settlement/core/voxel_navigation.hpp"
|
||||
#include "settlement/core/worker_pool.hpp"
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <future>
|
||||
#include <limits>
|
||||
#include <queue>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<class Material>
|
||||
void install(VoxelRegion& world, ChunkCoordinate chunk, Material material) {
|
||||
std::array<MaterialId, voxel_chunk_cells> 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<std::int32_t>(bounds.lower.x), static_cast<std::int32_t>(bounds.lower.y), static_cast<std::int32_t>(bounds.lower.z)}).chunk;
|
||||
const auto high = split_voxel({static_cast<std::int32_t>(bounds.upper.x - 1), static_cast<std::int32_t>(bounds.upper.y - 1), static_cast<std::int32_t>(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<VoxelPosition> 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<VoxelNavigationTests> {
|
||||
[[= 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 known_blockers_do_not_require_unrelated_missing_data();
|
||||
[[= Void::Testing::tag("voxel-navigation")]] Test reachable_missing_frontier_waits_for_actual_gateway();
|
||||
[[= Void::Testing::tag("voxel-navigation")]] Test unrepresentable_vector_capacity_is_a_bounded_refusal();
|
||||
[[= Void::Testing::tag("voxel-navigation")]] Test interaction_contacts_outside_window_need_frontier_evidence();
|
||||
[[= 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::known_blockers_do_not_require_unrelated_missing_data() {
|
||||
VoxelRegion world({1, 42, 1, {{0, 0, -1}, {64, 8, 4}}});
|
||||
install(world, {0, 0, 0}, [](auto p) {
|
||||
return p.z == 0 || (p.x == 2 && p.z <= 2) ? MaterialId::Stone : MaterialId::Air;
|
||||
});
|
||||
auto query = request(world, {1, 1, 1}, {{5, 5, 1}});
|
||||
auto result = find_voxel_path(world, query);
|
||||
require(result.status == Status::Unreachable, "solid floor and closed wall unnecessarily wait for missing lower page");
|
||||
require(find_voxel_interaction_path(world, query, {5, 5, 1}).status == Status::Unreachable,
|
||||
"loaded interaction behind known wall unnecessarily waits for missing lower page");
|
||||
require(std::any_of(result.consulted.chunks.begin(), result.consulted.chunks.end(), [](const auto& s) {
|
||||
return s.coordinate == ChunkCoordinate{0, 0, -1} && s.availability == VoxelAvailability::Unavailable;
|
||||
}), "conclusively blocked reads lost their actual dependency stamps");
|
||||
query.goals = {{35, 5, 1}};
|
||||
result = find_voxel_path(world, query);
|
||||
require(result.status == Status::Unreachable, "disconnected unknown goal manufactured reachable frontier");
|
||||
require(std::any_of(result.consulted.chunks.begin(), result.consulted.chunks.end(), [](const auto& s) {
|
||||
return s.coordinate == ChunkCoordinate{1, 0, 0} && s.availability == VoxelAvailability::Unavailable;
|
||||
}), "unknown goal reads were not retained");
|
||||
query.goals = {{5, 5, 1}};
|
||||
query.search_bounds.upper = {8, 6, 4};
|
||||
require(find_voxel_path(world, query).status == Status::SearchBoundary,
|
||||
"actual reachable window exit was replaced by irrelevant missing data");
|
||||
install(world, {0, 0, -1}, [](auto) { return MaterialId::Stone; });
|
||||
query.search_bounds = world.descriptor().bounds;
|
||||
require(find_voxel_path(world, query).status == Status::Unreachable,
|
||||
"lower-page activation changed proven blocked reachability");
|
||||
for (int x : {0, 1}) for (int z : {1, 2}) edit(world, {x, 3, z}, MaterialId::Stone);
|
||||
query.goals = {{1, 5, 1}};
|
||||
query.search_bounds.upper.x = 2;
|
||||
require(find_voxel_path(world, query).status == Status::Unreachable,
|
||||
"known blocked transitions beyond search window manufactured an exit");
|
||||
}
|
||||
Test VoxelNavigationTests::reachable_missing_frontier_waits_for_actual_gateway() {
|
||||
VoxelRegion world({1, 42, 1, {{0, 0, -1}, {64, 8, 4}}});
|
||||
const auto floor = [](auto p) { return p.z == 0 ? MaterialId::Stone : MaterialId::Air; };
|
||||
install(world, {0, 0, 0}, floor);
|
||||
auto blocked_goal = request(world, {1, 1, 1}, {{5, 5, 1}});
|
||||
edit(world, {5, 5, 2}, MaterialId::Stone);
|
||||
require(find_voxel_path(world, blocked_goal).status == Status::Unreachable,
|
||||
"missing branch elsewhere manufactured access to conclusively blocked goal");
|
||||
edit(world, {5, 5, 2}, MaterialId::Air);
|
||||
auto query = request(world, {1, 1, 1}, {{35, 5, 1}});
|
||||
auto pending = find_voxel_path(world, query);
|
||||
require(pending.status == Status::Unavailable, "reachable missing gateway was proven unreachable");
|
||||
install(world, {1, 0, 0}, floor);
|
||||
require(!pending.consulted.current(world, epoch()), "gateway activation did not invalidate pending answer");
|
||||
auto result = find_voxel_path(world, query);
|
||||
require_route(world, query, result);
|
||||
require(result.cost == 38, "loaded gateway changed shortest path cost");
|
||||
}
|
||||
Test VoxelNavigationTests::unrepresentable_vector_capacity_is_a_bounded_refusal() {
|
||||
auto world = flat();
|
||||
auto query = request(world, {1, 1, 1}, {{5, 5, 1}});
|
||||
query.limits.max_dependencies = std::vector<ChunkStamp>{}.max_size() + 1;
|
||||
query.limits.max_scratch_bytes = std::numeric_limits<std::size_t>::max();
|
||||
require(find_voxel_path(world, query).status == Status::LimitExceeded, "unrepresentable read reserve escaped path API");
|
||||
require(find_voxel_interaction_path(world, query, {5, 5, 1}).status == Status::LimitExceeded,
|
||||
"unrepresentable read reserve escaped interaction API");
|
||||
require(voxel_standing(world, epoch(), query.start, query.limits).status == Status::LimitExceeded,
|
||||
"unrepresentable read reserve escaped stance API");
|
||||
require(voxel_transition(world, epoch(), query.start, {2, 1, 1}, query.limits).status == Status::LimitExceeded,
|
||||
"unrepresentable read reserve escaped transition API");
|
||||
}
|
||||
Test VoxelNavigationTests::interaction_contacts_outside_window_need_frontier_evidence() {
|
||||
auto world = flat();
|
||||
edit(world, {3, 3, 1}, MaterialId::Stone);
|
||||
for (auto blocker : {VoxelPosition{2, 3, 2}, VoxelPosition{3, 2, 2}, VoxelPosition{3, 4, 2}, VoxelPosition{3, 3, 3}}) {
|
||||
edit(world, blocker, MaterialId::Stone);
|
||||
}
|
||||
auto query = request(world, {1, 1, 1}, {});
|
||||
query.search_bounds.upper.x = 6;
|
||||
auto complete = find_voxel_interaction_path(world, query, {3, 3, 1});
|
||||
require_route(world, query, complete);
|
||||
require(complete.goal == VoxelPosition{4, 3, 1}, "expanded window did not reach sole valid contact");
|
||||
query.search_bounds.upper.x = 4;
|
||||
require(find_voxel_interaction_path(world, query, {3, 3, 1}).status == Status::SearchBoundary,
|
||||
"clipped valid interaction contact was classified globally unreachable");
|
||||
|
||||
// A valid omitted goal cannot manufacture an exit from an enclosed start.
|
||||
for (auto p : {VoxelPosition{0, 1, 1}, VoxelPosition{1, 0, 1}, VoxelPosition{1, 2, 1}, VoxelPosition{2, 1, 1}}) {
|
||||
edit(world, p, MaterialId::Stone);
|
||||
edit(world, {p.x, p.y, 2}, MaterialId::Stone);
|
||||
}
|
||||
require(find_voxel_interaction_path(world, query, {3, 3, 1}).status == Status::Unreachable,
|
||||
"omitted contact manufactured an escape from a known enclosed start");
|
||||
|
||||
// The only useful contact is beyond x=31, in an unavailable page.
|
||||
VoxelRegion pending({1, 42, 1, {{0, 0, 0}, {40, 8, 4}}});
|
||||
install(pending, {0, 0, 0}, [](auto p) {
|
||||
if (p.z == 0 || p == VoxelPosition{31, 3, 1}) return MaterialId::Stone;
|
||||
if (p == VoxelPosition{30, 3, 2} || p == VoxelPosition{31, 2, 2} ||
|
||||
p == VoxelPosition{31, 4, 2} || p == VoxelPosition{31, 3, 3}) return MaterialId::Stone;
|
||||
return MaterialId::Air;
|
||||
});
|
||||
auto partial = request(pending, {29, 1, 1}, {});
|
||||
partial.search_bounds.upper.x = 32;
|
||||
const auto waiting = find_voxel_interaction_path(pending, partial, {31, 3, 1});
|
||||
require(waiting.status == Status::Unavailable, "unresolved interaction exit was proven unreachable");
|
||||
install(pending, {1, 0, 0}, [](auto p) { return p.z == 0 ? MaterialId::Stone : MaterialId::Air; });
|
||||
require(!waiting.consulted.current(pending, epoch()), "missing omitted contact was absent from dependencies");
|
||||
require(find_voxel_interaction_path(pending, partial, {31, 3, 1}).status == Status::SearchBoundary,
|
||||
"loaded omitted contact failed to expose reachable window exit");
|
||||
partial.search_bounds.upper.x = 36;
|
||||
auto reached = find_voxel_interaction_path(pending, partial, {31, 3, 1});
|
||||
require_route(pending, partial, reached);
|
||||
require(reached.goal == VoxelPosition{32, 3, 1}, "expanded gateway did not expose actual contact");
|
||||
}
|
||||
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<std::int32_t>::min(), 0, 0}, {std::int64_t{std::numeric_limits<std::int32_t>::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<std::int32_t>::min(), std::numeric_limits<std::int32_t>::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::int32_t>(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<VoxelPosition>{{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<bool, 49> 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<VoxelEdit> changes;
|
||||
for (int y = 0; y < 7; ++y) for (int x = 0; x < 7; ++x) if (walls[static_cast<std::size_t>(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<int, 49> distance; distance.fill(-1); distance[8] = 0;
|
||||
std::queue<int> queue; queue.push(8);
|
||||
while (!queue.empty()) {
|
||||
const auto v = queue.front(); queue.pop();
|
||||
for (auto d : std::array<std::array<int, 2>, 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<std::size_t>(x + 7 * y);
|
||||
if (walls[n] || distance[n] >= 0) continue;
|
||||
distance[n] = distance[static_cast<std::size_t>(v)] + 1; queue.push(static_cast<int>(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<std::size_t>(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<std::future<VoxelPathResult>> 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
|
||||
@@ -0,0 +1,479 @@
|
||||
#include "settlement/core/voxel_region.hpp"
|
||||
#include "settlement/core/worker_pool.hpp"
|
||||
|
||||
#include <Void/Core/Hash.hpp>
|
||||
#include <Void/Core/Scope.hpp>
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <future>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <mutex>
|
||||
#include <span>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
using namespace settlement;
|
||||
using Void::Testing::Test;
|
||||
constexpr auto smallest = std::numeric_limits<std::int32_t>::min();
|
||||
constexpr auto largest = std::numeric_limits<std::int32_t>::max();
|
||||
constexpr auto exhausted = std::numeric_limits<std::uint64_t>::max();
|
||||
|
||||
void require(bool condition, const char* message = "voxel region invariant failed") {
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
}
|
||||
VoxelRegionDescriptor descriptor(VoxelBounds bounds = {{-64, -64, -32}, {64, 64, 32}}) {
|
||||
return {7, 42, voxel_generator_version, bounds};
|
||||
}
|
||||
PreparedVoxelChunk generated(const VoxelRegion& region, ChunkCoordinate coordinate) {
|
||||
auto candidate = region.prepare_generated(coordinate);
|
||||
require(candidate.has_value(), "valid chunk generation refused");
|
||||
return std::move(*candidate);
|
||||
}
|
||||
void activate(VoxelRegion& region, std::span<const ChunkCoordinate> coordinates) {
|
||||
std::vector<PreparedVoxelChunk> candidates;
|
||||
for (auto coordinate : coordinates) candidates.push_back(generated(region, coordinate));
|
||||
require(region.activate(candidates).has_value(), "valid chunk activation refused");
|
||||
}
|
||||
VoxelEdit change(const VoxelRegion& region, VoxelPosition position) {
|
||||
const auto sample = region.sample(position);
|
||||
require(sample.availability == VoxelAvailability::Loaded);
|
||||
return {position, sample.material == MaterialId::Air ? MaterialId::Stone : MaterialId::Air, sample.stamp.revision};
|
||||
}
|
||||
void equivalent(const VoxelRegion& left, const VoxelRegion& right) {
|
||||
require(left.descriptor() == right.descriptor());
|
||||
const auto a = left.directory(), b = right.directory();
|
||||
require(a->size() == b->size());
|
||||
for (std::size_t i = 0; i < a->size(); ++i) {
|
||||
require((*a)[i].coordinate == (*b)[i].coordinate &&
|
||||
(*a)[i].chunk->revision() == (*b)[i].chunk->revision());
|
||||
require(std::equal((*a)[i].chunk->cells().begin(), (*a)[i].chunk->cells().end(), (*b)[i].chunk->cells().begin()),
|
||||
"complete material pages differ");
|
||||
}
|
||||
}
|
||||
template<class T> void error(const std::expected<T, VoxelError>& result, VoxelError expected) {
|
||||
require(!result && result.error() == expected, "unexpected operation result");
|
||||
}
|
||||
bool contains(const std::vector<ChunkCoordinate>& coordinates, ChunkCoordinate coordinate) {
|
||||
return std::binary_search(coordinates.begin(), coordinates.end(), coordinate);
|
||||
}
|
||||
|
||||
struct [[= Void::Testing::name("VoxelRegionTests")]] VoxelRegionTests : Void::Testing::Suite<VoxelRegionTests> {
|
||||
[[= Void::Testing::tag("voxel-region")]] Test signed_coordinates_and_x_fast_layout();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test descriptor_validation_and_sparse_extreme_bounds();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test generated_pages_have_fixed_materials_and_continuous_surface();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test preparation_order_and_worker_order_preserve_complete_pages();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test partial_pages_mask_outside_and_validate_import();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test availability_and_snapshot_lifetimes();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test atomic_multichunk_edit_reuses_unchanged_pages();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test refused_batches_and_identical_writes_preserve_publication();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test face_neighbors_and_unavailable_boundaries();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test activation_checks_source_duplicates_and_prior_publication();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test imported_revision_exhaustion_preserves_all_pages();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test page_edit_and_staging_budgets_are_atomic();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test doorway_crossing_two_chunks_opens_atomically();
|
||||
[[= Void::Testing::tag("voxel-region")]] Test full_resident_directory_copies_one_changed_page();
|
||||
};
|
||||
|
||||
Test VoxelRegionTests::signed_coordinates_and_x_fast_layout() {
|
||||
constexpr std::array values{smallest, -33, -32, -1, 0, 31, 32, largest};
|
||||
constexpr std::array chunks{-67108864, -2, -1, -1, 0, 0, 1, 67108863};
|
||||
constexpr std::array locals{0, 31, 0, 31, 0, 31, 0, 31};
|
||||
for (std::size_t i = 0; i < values.size(); ++i) {
|
||||
for (auto y : values) for (auto z : values) {
|
||||
const VoxelPosition position{values[i], y, z};
|
||||
const auto address = split_voxel(position);
|
||||
require(address.chunk.x == chunks[i] && address.local.x == locals[i]);
|
||||
require(join_voxel(address.chunk, address.local) == position);
|
||||
}
|
||||
}
|
||||
require(voxel_index({1, 0, 0}) == 1 && voxel_index({0, 1, 0}) == 32 &&
|
||||
voxel_index({0, 0, 1}) == 1024 && voxel_index({31, 31, 31}) == voxel_chunk_cells - 1);
|
||||
require(!voxel_index({32, 0, 0}) && !voxel_index({0, 255, 0}));
|
||||
require(!join_voxel({67108864, 0, 0}, {}) && !join_voxel({-67108865, 0, 0}, {31, 0, 0}));
|
||||
require(!join_voxel({}, {0, 0, 32}));
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::descriptor_validation_and_sparse_extreme_bounds() {
|
||||
const auto rejected = [](VoxelRegionDescriptor definition) {
|
||||
try { const VoxelRegion region(definition); }
|
||||
catch (const std::invalid_argument&) { return true; }
|
||||
return false;
|
||||
};
|
||||
auto definition = descriptor(); definition.id = 0; require(rejected(definition));
|
||||
definition = descriptor(); definition.generator_version = 0; require(rejected(definition));
|
||||
definition.generator_version = 2; require(rejected(definition));
|
||||
definition = descriptor(); definition.bounds.upper.x = definition.bounds.lower.x; require(rejected(definition));
|
||||
definition = descriptor(); definition.bounds.lower.z = std::int64_t{smallest} - 1; require(rejected(definition));
|
||||
definition = descriptor(); definition.bounds.upper.y = std::int64_t{largest} + 2; require(rejected(definition));
|
||||
VoxelRegion sparse(descriptor({{smallest, smallest, smallest},
|
||||
{std::int64_t{largest} + 1, std::int64_t{largest} + 1, std::int64_t{largest} + 1}}));
|
||||
require(sparse.directory()->empty() && sparse.resident_bytes() == sizeof(VoxelDirectory));
|
||||
const std::array coordinates{ChunkCoordinate{-67108864, -67108864, -67108864},
|
||||
ChunkCoordinate{67108863, 67108863, 67108863}};
|
||||
activate(sparse, coordinates);
|
||||
require(sparse.sample({smallest, smallest, smallest}).material == MaterialId::Stone);
|
||||
require(sparse.sample({largest, largest, largest}).availability == VoxelAvailability::Loaded &&
|
||||
sparse.sample({largest, largest, largest}).material == MaterialId::Air);
|
||||
error(sparse.prepare_generated({largest, 0, 0}), VoxelError::InvalidCoordinate);
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::generated_pages_have_fixed_materials_and_continuous_surface() {
|
||||
VoxelRegion region(descriptor());
|
||||
std::vector<ChunkCoordinate> coordinates;
|
||||
for (int x = -1; x <= 0; ++x) for (int y = -1; y <= 0; ++y) for (int z = -1; z <= 0; ++z) {
|
||||
coordinates.push_back({x, y, z});
|
||||
}
|
||||
activate(region, coordinates);
|
||||
const auto height = [&](int x, int y) {
|
||||
int top = -20;
|
||||
for (int z = -16; z < 16; ++z) if (region.sample({x, y, z}).material != MaterialId::Air) top = z;
|
||||
require(top >= -8 && top <= 8);
|
||||
require(region.sample({x, y, top}).material == MaterialId::Soil &&
|
||||
region.sample({x, y, top - 2}).material == MaterialId::Soil &&
|
||||
region.sample({x, y, top - 3}).material == MaterialId::Stone &&
|
||||
region.sample({x, y, top + 1}).material == MaterialId::Air);
|
||||
return top;
|
||||
};
|
||||
for (int x = -31; x < 31; ++x) for (int y = -31; y < 31; ++y) {
|
||||
const auto top = height(x, y);
|
||||
require(std::abs(top - height(x + 1, y)) <= 1 && std::abs(top - height(x, y + 1)) <= 1,
|
||||
"generator has a discontinuous chunk/lattice surface");
|
||||
}
|
||||
const auto page = region.directory()->front().chunk;
|
||||
const auto hash = Void::Hash::fnv1a64(std::as_bytes(page->cells()));
|
||||
std::cout << "generator1 seed42 chunk(-1,-1,-1) fnv1a64=" << hash << '\n';
|
||||
// Recorded against the canonical little-endian generator, independently
|
||||
// reproduced by the fixture calculation before accepting this revision.
|
||||
require(hash == 13302332479434111011ULL, "canonical generator fixture changed");
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::preparation_order_and_worker_order_preserve_complete_pages() {
|
||||
const std::array coordinates{ChunkCoordinate{0, 0, 0}, ChunkCoordinate{-1, 0, 0},
|
||||
ChunkCoordinate{0, -1, -1}, ChunkCoordinate{1, 1, 0}};
|
||||
VoxelRegion forward(descriptor());
|
||||
activate(forward, coordinates);
|
||||
VoxelRegion reverse(descriptor());
|
||||
auto reversed = coordinates; std::reverse(reversed.begin(), reversed.end());
|
||||
activate(reverse, reversed);
|
||||
equivalent(forward, reverse);
|
||||
for (std::size_t workers : {2, 6, 12}) for (bool reverse_completion : {false, true}) {
|
||||
VoxelRegion parallel(descriptor());
|
||||
WorkerPool pool(workers);
|
||||
std::vector<PreparedVoxelChunk> candidates;
|
||||
for (std::size_t pair = 0; pair < coordinates.size(); pair += 2) {
|
||||
std::mutex mutex;
|
||||
std::condition_variable changed;
|
||||
int ready = 0;
|
||||
std::array<bool, 2> permitted{};
|
||||
bool released = false;
|
||||
std::array<std::future<std::expected<PreparedVoxelChunk, VoxelError>>, 2> futures;
|
||||
// Release and drain every accepted task before its captured gate
|
||||
// dies, including a failed submission or assertion.
|
||||
auto release = Void::Scope::on_exit([&] {
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
released = true;
|
||||
changed.notify_all();
|
||||
}
|
||||
for (auto& future : futures) if (future.valid()) future.wait();
|
||||
});
|
||||
for (std::size_t index = 0; index < 2; ++index) {
|
||||
futures[index] = pool.submit([&, parallel, coordinate = coordinates[pair + index], index] {
|
||||
auto result = parallel.prepare_generated(coordinate);
|
||||
std::unique_lock lock(mutex);
|
||||
++ready;
|
||||
changed.notify_all();
|
||||
changed.wait(lock, [&] { return released || permitted[index]; });
|
||||
return result;
|
||||
});
|
||||
}
|
||||
{
|
||||
std::unique_lock lock(mutex);
|
||||
require(changed.wait_for(lock, std::chrono::seconds(5), [&] { return ready == 2; }),
|
||||
"two real generator tasks did not reach completion gates");
|
||||
}
|
||||
const std::array<std::size_t, 2> order = reverse_completion ?
|
||||
std::array<std::size_t, 2>{1, 0} : std::array<std::size_t, 2>{0, 1};
|
||||
for (auto index : order) {
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
permitted[index] = true;
|
||||
changed.notify_all();
|
||||
}
|
||||
require(futures[index].wait_for(std::chrono::seconds(5)) == std::future_status::ready);
|
||||
auto result = futures[index].get();
|
||||
require(result.has_value());
|
||||
candidates.push_back(std::move(*result));
|
||||
}
|
||||
}
|
||||
require(parallel.activate(candidates).has_value());
|
||||
equivalent(forward, parallel);
|
||||
}
|
||||
auto other_definition = descriptor(); ++other_definition.seed;
|
||||
VoxelRegion other(other_definition); activate(other, coordinates);
|
||||
require(!std::equal(forward.directory()->front().chunk->cells().begin(),
|
||||
forward.directory()->front().chunk->cells().end(), other.directory()->front().chunk->cells().begin()));
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::partial_pages_mask_outside_and_validate_import() {
|
||||
const std::array bounds{VoxelBounds{{-1, -1, -1}, {1, 1, 1}},
|
||||
VoxelBounds{{largest, largest, largest}, {std::int64_t{largest} + 1,
|
||||
std::int64_t{largest} + 1, std::int64_t{largest} + 1}},
|
||||
VoxelBounds{{smallest, smallest, smallest}, {std::int64_t{smallest} + 1,
|
||||
std::int64_t{smallest} + 1, std::int64_t{smallest} + 1}}};
|
||||
for (const auto& bound : bounds) {
|
||||
VoxelRegion region(descriptor(bound));
|
||||
const VoxelPosition position{static_cast<std::int32_t>(bound.lower.x),
|
||||
static_cast<std::int32_t>(bound.lower.y), static_cast<std::int32_t>(bound.lower.z)};
|
||||
const auto coordinate = split_voxel(position).chunk;
|
||||
auto candidate = generated(region, coordinate);
|
||||
const auto cells = candidate.chunk()->cells();
|
||||
for (std::size_t i = 0; i < cells.size(); ++i) {
|
||||
const auto p = join_voxel(coordinate, {static_cast<std::uint8_t>(i % 32),
|
||||
static_cast<std::uint8_t>((i / 32) % 32), static_cast<std::uint8_t>(i / 1024)});
|
||||
require(p.has_value());
|
||||
if (!bound.contains(*p)) require(cells[i] == MaterialId::Air);
|
||||
}
|
||||
auto restored = region.prepare_restored(coordinate, 72, cells);
|
||||
require(restored.has_value() && restored->chunk()->revision() == 72);
|
||||
std::array<MaterialId, voxel_chunk_cells> owned;
|
||||
std::copy(cells.begin(), cells.end(), owned.begin());
|
||||
auto independent = region.prepare_restored(coordinate, 1, owned);
|
||||
require(independent.has_value());
|
||||
const auto index = *voxel_index(split_voxel(position).local);
|
||||
owned[index] = static_cast<MaterialId>(200);
|
||||
error(region.prepare_restored(coordinate, 1, owned), VoxelError::InvalidMaterial);
|
||||
require(independent->chunk()->cells()[index] == cells[index], "import retained caller's mutable cells");
|
||||
owned[index] = cells[index];
|
||||
const auto outside_index = (index + 1234) % voxel_chunk_cells;
|
||||
owned[outside_index] = MaterialId::Stone;
|
||||
error(region.prepare_restored(coordinate, 1, owned), VoxelError::InvalidCoordinate);
|
||||
error(region.prepare_restored(coordinate, 0, cells), VoxelError::InvalidRevision);
|
||||
error(region.prepare_restored(coordinate, 1, cells.first(100)), VoxelError::InvalidSource);
|
||||
}
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::availability_and_snapshot_lifetimes() {
|
||||
VoxelRegion region(descriptor());
|
||||
const auto absent = region.sample({0, 0, 20});
|
||||
require(absent.availability == VoxelAvailability::Unavailable);
|
||||
const auto outside = region.sample({64, 0, 20});
|
||||
require(outside.availability == VoxelAvailability::Outside);
|
||||
auto held = region;
|
||||
const std::array coordinates{ChunkCoordinate{0, 0, 0}};
|
||||
activate(region, coordinates);
|
||||
require(!region.matches(absent.stamp) && held.matches(absent.stamp));
|
||||
const auto loaded = region.sample({0, 0, 20});
|
||||
require(loaded.availability == VoxelAvailability::Loaded && loaded.material == MaterialId::Air);
|
||||
require(held.sample({0, 0, 20}).availability == VoxelAvailability::Unavailable);
|
||||
auto owned_directory = region.directory();
|
||||
auto retained = region;
|
||||
const std::array changes{change(region, {0, 0, 20})};
|
||||
require(region.edit(changes).has_value());
|
||||
require(retained.matches(loaded.stamp) && !region.matches(loaded.stamp));
|
||||
require(owned_directory->front().chunk->cells()[20 * 1024] == MaterialId::Air);
|
||||
auto other_stamp = loaded.stamp; ++other_stamp.region; require(!retained.matches(other_stamp));
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::atomic_multichunk_edit_reuses_unchanged_pages() {
|
||||
VoxelRegion region(descriptor());
|
||||
const std::array coordinates{ChunkCoordinate{-1, 0, 0}, ChunkCoordinate{0, 0, 0}, ChunkCoordinate{1, 0, 0}};
|
||||
activate(region, coordinates);
|
||||
const auto held = region;
|
||||
const std::array changes{change(region, {0, 2, 20}), change(region, {-1, 2, 20}), change(region, {4, 4, 20})};
|
||||
const auto result = region.edit(changes);
|
||||
require(result.has_value() && result->changed_chunks.size() == 2 && result->changed_cells.size() == 3);
|
||||
require(result->changed_cells[0].position == VoxelPosition{-1, 2, 20} &&
|
||||
result->changed_cells[1].position == VoxelPosition{0, 2, 20});
|
||||
require(result->changed_chunks[0].coordinate == ChunkCoordinate{-1, 0, 0} &&
|
||||
result->changed_chunks[1].coordinate == ChunkCoordinate{0, 0, 0});
|
||||
for (const auto& change : changes) {
|
||||
require(region.sample(change.position).material == change.material);
|
||||
require(held.sample(change.position).material != change.material);
|
||||
require(region.sample(change.position).stamp.revision == 2);
|
||||
}
|
||||
require(region.directory()->back().chunk == held.directory()->back().chunk,
|
||||
"untouched geometry was copied");
|
||||
VoxelRegion other = held;
|
||||
auto reversed = changes; std::reverse(reversed.begin(), reversed.end());
|
||||
require(other.edit(reversed).has_value()); equivalent(region, other);
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::refused_batches_and_identical_writes_preserve_publication() {
|
||||
VoxelRegion region(descriptor());
|
||||
const std::array coordinates{ChunkCoordinate{-1, 0, 0}, ChunkCoordinate{0, 0, 0}};
|
||||
activate(region, coordinates);
|
||||
const auto held = region;
|
||||
auto changes = std::array{change(region, {-1, 1, 20}), change(region, {0, 1, 20})};
|
||||
++changes[1].expected_revision;
|
||||
error(region.edit(changes), VoxelError::Stale);
|
||||
--changes[1].expected_revision; changes[1].material = static_cast<MaterialId>(255);
|
||||
error(region.edit(changes), VoxelError::InvalidMaterial);
|
||||
changes[1] = changes[0]; error(region.edit(changes), VoxelError::Duplicate);
|
||||
changes[1] = {{32, 1, 20}, MaterialId::Stone, 1}; error(region.edit(changes), VoxelError::Unavailable);
|
||||
changes[1].position.x = 64; error(region.edit(changes), VoxelError::InvalidCoordinate);
|
||||
require(region.directory() == held.directory()); equivalent(region, held);
|
||||
require(region.edit({}).has_value() && region.directory() == held.directory());
|
||||
const auto current = region.sample({0, 1, 20});
|
||||
std::array identical{VoxelEdit{{0, 1, 20}, current.material, current.stamp.revision}};
|
||||
const auto result = region.edit(identical);
|
||||
require(result && result->changed_chunks.empty() && result->changed_cells.empty() && result->dirty_chunks.empty());
|
||||
require(region.directory() == held.directory());
|
||||
--identical[0].expected_revision; error(region.edit(identical), VoxelError::Stale);
|
||||
require(region.directory() == held.directory());
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::face_neighbors_and_unavailable_boundaries() {
|
||||
VoxelRegion region(descriptor({{-64, -64, -64}, {64, 64, 64}}));
|
||||
const std::array coordinates{ChunkCoordinate{-1, -1, -1}, ChunkCoordinate{0, -1, -1}};
|
||||
activate(region, coordinates);
|
||||
const auto neighbor = region.chunk_stamp({0, -1, -1});
|
||||
const auto absent = region.chunk_stamp({-1, 0, -1});
|
||||
const std::array changes{change(region, {-1, -1, -1})};
|
||||
const auto result = region.edit(changes);
|
||||
require(result && result->dirty_chunks.size() == 4);
|
||||
require(contains(result->dirty_chunks, {-1, -1, -1}) && contains(result->dirty_chunks, {0, -1, -1}) &&
|
||||
contains(result->dirty_chunks, {-1, 0, -1}) && contains(result->dirty_chunks, {-1, -1, 0}));
|
||||
require(!contains(result->dirty_chunks, {0, 0, -1}) && !contains(result->dirty_chunks, {0, 0, 0}));
|
||||
require(region.matches(neighbor) && region.matches(absent));
|
||||
const std::array interior{change(region, {-2, -2, -2})};
|
||||
const auto result2 = region.edit(interior);
|
||||
require(result2 && result2->dirty_chunks == std::vector<ChunkCoordinate>{{-1, -1, -1}});
|
||||
VoxelRegion edge(descriptor({{largest, 0, 0}, {std::int64_t{largest} + 1, 1, 1}}));
|
||||
const std::array last_chunk{split_voxel({largest, 0, 0}).chunk}; activate(edge, last_chunk);
|
||||
const std::array last_change{change(edge, {largest, 0, 0})};
|
||||
const auto last_result = edge.edit(last_change);
|
||||
require(last_result && last_result->dirty_chunks == std::vector<ChunkCoordinate>{last_chunk[0]});
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::activation_checks_source_duplicates_and_prior_publication() {
|
||||
VoxelRegion region(descriptor());
|
||||
auto candidate = generated(region, {});
|
||||
const auto empty = region.directory();
|
||||
const std::array duplicate{candidate, candidate}; error(region.activate(duplicate), VoxelError::Duplicate);
|
||||
require(region.directory() == empty);
|
||||
for (int field = 0; field < 3; ++field) {
|
||||
auto wrong = descriptor();
|
||||
if (field == 0) ++wrong.id;
|
||||
if (field == 1) ++wrong.seed;
|
||||
if (field == 2) --wrong.bounds.lower.x;
|
||||
VoxelRegion other(wrong);
|
||||
const std::array mixed{candidate, generated(other, {-1, 0, 0})};
|
||||
error(region.activate(mixed), VoxelError::InvalidSource);
|
||||
require(region.directory() == empty);
|
||||
}
|
||||
const std::array first{candidate}; require(region.activate(first).has_value());
|
||||
const auto held = region.directory();
|
||||
const std::array late{generated(region, {-1, 0, 0}), candidate};
|
||||
error(region.activate(late), VoxelError::Stale); require(region.directory() == held);
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::imported_revision_exhaustion_preserves_all_pages() {
|
||||
VoxelRegion region(descriptor());
|
||||
const auto source = generated(region, {});
|
||||
auto maximum = region.prepare_restored({}, exhausted, source.chunk()->cells());
|
||||
require(maximum.has_value());
|
||||
const std::array pages{generated(region, {-1, 0, 0}), *maximum};
|
||||
require(region.activate(pages).has_value());
|
||||
const auto held = region;
|
||||
const std::array changes{change(region, {-1, 1, 20}), change(region, {0, 1, 20})};
|
||||
error(region.edit(changes), VoxelError::RevisionExhausted);
|
||||
require(region.directory() == held.directory()); equivalent(region, held);
|
||||
const auto current = region.sample({0, 1, 20});
|
||||
const std::array identical{VoxelEdit{{0, 1, 20}, current.material, exhausted}};
|
||||
require(region.edit(identical).has_value() && region.directory() == held.directory());
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::page_edit_and_staging_budgets_are_atomic() {
|
||||
VoxelRegion source(descriptor());
|
||||
const std::array pages{generated(source, {}), generated(source, {-1, 0, 0})};
|
||||
VoxelLimits one; one.max_resident_chunks = 1;
|
||||
VoxelRegion bounded(descriptor(), one);
|
||||
const auto empty = bounded.directory();
|
||||
error(bounded.activate(pages), VoxelError::LimitExceeded); require(bounded.directory() == empty);
|
||||
require(bounded.activate(std::span(pages).first(1)).has_value());
|
||||
error(bounded.activate(std::span(pages).last(1)), VoxelError::LimitExceeded);
|
||||
VoxelLimits bytes; bytes.max_resident_bytes = sizeof(VoxelDirectory) + sizeof(VoxelChunkEntry) + sizeof(VoxelChunk) - 1;
|
||||
VoxelRegion small(descriptor(), bytes);
|
||||
error(small.activate(std::span(pages).first(1)), VoxelError::LimitExceeded);
|
||||
VoxelLimits transactions; transactions.max_transaction_bytes = sizeof(VoxelChunk) + 1024;
|
||||
VoxelRegion limited(descriptor(), transactions);
|
||||
error(limited.prepare_generated({}), VoxelError::LimitExceeded);
|
||||
require(limited.activate(std::span(pages).first(1)).has_value());
|
||||
const auto held = limited.directory();
|
||||
const std::array edits{change(limited, {1, 1, 20})};
|
||||
error(limited.edit(edits), VoxelError::LimitExceeded); require(limited.directory() == held);
|
||||
VoxelLimits edit_limit; edit_limit.max_edit_cells = 1;
|
||||
VoxelRegion two(descriptor(), edit_limit); require(two.activate(pages).has_value());
|
||||
const std::array too_many{change(two, {1, 1, 20}), change(two, {-1, 1, 20})};
|
||||
error(two.edit(too_many), VoxelError::LimitExceeded);
|
||||
require(two.resident_bytes() == sizeof(VoxelDirectory) + 2 * (sizeof(VoxelChunkEntry) + sizeof(VoxelChunk)));
|
||||
VoxelLimits hostile; hostile.max_resident_chunks = std::numeric_limits<std::size_t>::max();
|
||||
VoxelRegion sparse(descriptor(), hostile); require(sparse.directory()->empty());
|
||||
std::cout << "voxel payload: page=" << sizeof(VoxelChunk) << " directory entry=" << sizeof(VoxelChunkEntry)
|
||||
<< " active256=" << sizeof(VoxelDirectory) + 256 * (sizeof(VoxelChunkEntry) + sizeof(VoxelChunk)) << '\n';
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::doorway_crossing_two_chunks_opens_atomically() {
|
||||
require(voxel_blocks_passage(MaterialId::DoorClosed) && !voxel_blocks_passage(MaterialId::DoorOpen));
|
||||
require(!voxel_provides_support(MaterialId::DoorClosed) && !voxel_provides_support(MaterialId::DoorOpen));
|
||||
require(!voxel_blocks_passage(MaterialId::Air) && !voxel_provides_support(MaterialId::Air));
|
||||
for (auto material : {MaterialId::Soil, MaterialId::Stone}) {
|
||||
require(voxel_blocks_passage(material) && voxel_provides_support(material));
|
||||
}
|
||||
VoxelRegion region(descriptor({{0, 0, 0}, {32, 32, 64}}));
|
||||
const std::array coordinates{ChunkCoordinate{0, 0, 0}, ChunkCoordinate{0, 0, 1}};
|
||||
activate(region, coordinates);
|
||||
const std::array closed{VoxelEdit{{2, 2, 31}, MaterialId::DoorClosed, 1},
|
||||
VoxelEdit{{2, 2, 32}, MaterialId::DoorClosed, 1}};
|
||||
require(region.edit(closed).has_value());
|
||||
const auto held = region;
|
||||
std::array opened{VoxelEdit{{2, 2, 31}, MaterialId::DoorOpen, 2},
|
||||
VoxelEdit{{2, 2, 32}, MaterialId::DoorOpen, 1}};
|
||||
error(region.edit(opened), VoxelError::Stale);
|
||||
require(region.directory() == held.directory());
|
||||
opened[1].expected_revision = 2;
|
||||
const auto result = region.edit(opened);
|
||||
require(result && result->changed_chunks.size() == 2 && result->changed_cells.size() == 2);
|
||||
for (auto edit : opened) {
|
||||
require(region.sample(edit.position).material == MaterialId::DoorOpen);
|
||||
require(held.sample(edit.position).material == MaterialId::DoorClosed);
|
||||
}
|
||||
auto imported = region.prepare_restored(coordinates[0], 3, region.directory()->front().chunk->cells());
|
||||
require(imported.has_value());
|
||||
}
|
||||
|
||||
Test VoxelRegionTests::full_resident_directory_copies_one_changed_page() {
|
||||
using Clock = std::chrono::steady_clock;
|
||||
VoxelRegion region(descriptor({{-256, -256, 0}, {256, 256, 32}}));
|
||||
std::vector<ChunkCoordinate> coordinates;
|
||||
for (int x = -8; x < 8; ++x) for (int y = -8; y < 8; ++y) coordinates.push_back({x, y, 0});
|
||||
const auto preparation_started = Clock::now();
|
||||
activate(region, coordinates);
|
||||
const auto preparation_done = Clock::now();
|
||||
const auto held = region;
|
||||
require(held.directory() == region.directory() && held.directory()->size() == 256);
|
||||
const std::array edits{change(region, {1, 1, 20})};
|
||||
const auto edit_started = Clock::now();
|
||||
const auto result = region.edit(edits);
|
||||
const auto edit_done = Clock::now();
|
||||
require(result && result->changed_chunks.size() == 1);
|
||||
std::size_t shared = 0;
|
||||
for (std::size_t i = 0; i < region.directory()->size(); ++i) {
|
||||
if ((*held.directory())[i].chunk == (*region.directory())[i].chunk) ++shared;
|
||||
}
|
||||
require(shared == 255 && region.directory() != held.directory());
|
||||
require(held.sample(edits[0].position).material != region.sample(edits[0].position).material);
|
||||
std::cout << "full256 pages: prepare+activate_us="
|
||||
<< std::chrono::duration_cast<std::chrono::microseconds>(preparation_done - preparation_started).count()
|
||||
<< " edit_us=" << std::chrono::duration_cast<std::chrono::microseconds>(edit_done - edit_started).count()
|
||||
<< " shared_pages=" << shared << " resident_payload=" << region.resident_bytes() << '\n';
|
||||
}
|
||||
} // namespace
|
||||
Reference in new issue
Block a user