From 69bbf364a9510d2a497890deb6789f6e153efac6 Mon Sep 17 00:00:00 2001 From: dingo Date: Sat, 26 Sep 2026 10:06:22 -0400 Subject: [PATCH] Define M5.1 local voxel contract and expand M5-M9 gates --- AGENTS.md | 3 + CMakeLists.txt | 12 ++ README.md | 2 + docs/ROADMAP.md | 212 +++++++++++++++++++++++- docs/STATUS.md | 31 +++- docs/adr/0042-local-voxel-contract.md | 70 ++++++++ docs/adr/README.md | 2 + docs/architecture/OPEN_QUESTIONS.md | 2 +- docs/architecture/WORLD_ARCHITECTURE.md | 11 ++ docs/engineering/VALIDATION.md | 27 +++ docs/world/LOCAL_VOXEL_CONTRACT.md | 83 ++++++++++ include/evo/world/coordinates.hpp | 84 ++++++++++ src/world/coordinates.cpp | 101 +++++++++++ tests/world_coordinates_tests.cpp | 150 +++++++++++++++++ 14 files changed, 778 insertions(+), 12 deletions(-) create mode 100644 docs/adr/0042-local-voxel-contract.md create mode 100644 docs/world/LOCAL_VOXEL_CONTRACT.md create mode 100644 include/evo/world/coordinates.hpp create mode 100644 src/world/coordinates.cpp create mode 100644 tests/world_coordinates_tests.cpp diff --git a/AGENTS.md b/AGENTS.md index 820793b..cc0920f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,3 +22,6 @@ test pass; explain the simulation-version change and compatibility implications. Never deploy, reset or prune World0 from routine development. Never commit secrets. Do not claim checks passed unless they actually ran; record environmental limits in docs/engineering/VALIDATION.md. Preserve uncommitted work by others. + +After each completed and validated gate segment, commit its scoped changes and push +to the configured Git remote. Preserve unrelated untracked work; never stage secrets. diff --git a/CMakeLists.txt b/CMakeLists.txt index 0c6916a..9132102 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -34,6 +34,12 @@ target_include_directories(evo_simulation PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/in target_compile_features(evo_simulation PUBLIC cxx_std_23) evo_owned_target(evo_simulation) +add_library(evo_world STATIC src/world/coordinates.cpp) +add_library(evo::world ALIAS evo_world) +target_include_directories(evo_world PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_compile_features(evo_world PUBLIC cxx_std_23) +evo_owned_target(evo_world) + add_library(evo_accounting STATIC src/accounting/ledger.cpp) add_library(evo::accounting ALIAS evo_accounting) target_include_directories(evo_accounting PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") @@ -65,6 +71,12 @@ evo_owned_target(evo-sim) include(CTest) if(BUILD_TESTING) + add_executable(evo-world-coordinate-tests tests/world_coordinates_tests.cpp) + target_link_libraries(evo-world-coordinate-tests PRIVATE evo::world) + evo_owned_target(evo-world-coordinate-tests) + add_test(NAME world-coordinate-contracts COMMAND evo-world-coordinate-tests) + set_tests_properties(world-coordinate-contracts PROPERTIES TIMEOUT 60) + add_executable(evo-feeding-tests tests/feeding_tests.cpp) target_link_libraries(evo-feeding-tests PRIVATE evo::processes) evo_owned_target(evo-feeding-tests) diff --git a/README.md b/README.md index c4ff7ec..6369c62 100644 --- a/README.md +++ b/README.md @@ -129,3 +129,5 @@ The project license has not been selected. Do not infer an open-source license from a public dependency's license. M4.6 reproduction, measurements and limits: [aggregate budget report](docs/engineering/AGGREGATE_BUDGET.md). + +M5.1 local voxel/address API and scope: [local voxel contract](docs/world/LOCAL_VOXEL_CONTRACT.md). diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index feffb20..2d1b48b 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -188,25 +188,219 @@ stays open. | 4.5 Validate resolution equivalence | tests/ecosystem, benchmarks | 4.4 | 100 individuals → aggregate → 10,000 ticks → representatives | Conservation exactly; ecological distributions within documented tolerance | Claiming identical trajectories at different resolution | | 4.6 Budget and review aggregate model | docs/adr, simulation metrics | 4.5 | CPU/memory and error bounds justify tier policy | Active/aggregate benchmark and ecological sensitivity report | Premature world-scale claims | +## M5-M9 delivery gates + +Status: **planned**, not implemented or deployed. These tasks expand the founding +milestones without adopting new libraries, biological rules or production budgets. +Module paths below are proposed boundaries; create them only when their task starts. +Every row is an independently reviewable increment with buildable tests. Split a +row further if its contract cannot be reviewed separately from its implementation. + +M4.6 did not qualify an automatic tier policy. M5-M9 may use bounded active organisms +and explicit test cohorts; they may not silently enable the failed aggregate model +for live ecology. Reproduction cost semantics from ADR-0031/0032 remain a separate +biology decision before claiming a biologically credible persistent ecosystem. + +```mermaid +flowchart LR + M5[M5 sparse local world] --> M6[M6 conserved environment] + M6 --> M7[M7 durable region] + M7 --> M8D[M8 dev and stage recovery] + M8D --> M8W[M8 guarded World0 launch] + M7 --> M9[M9 custom 2D client] + M8D --> M9 + M9 --> M10[M10 realtime multiplayer] + F[M4.6 fidelity follow-up] -. required before live aggregate selection .-> M10 +``` + +The dotted dependency applies to using aggregate simulation, not to all M10 work. +M9 local graphics experiments can begin after the M6 read-view contract; its server +integration gate requires M7 and M8 dev/stage evidence, not premature World0 launch. +No runtime service is added solely to match a diagram. Existing Gitea, Harbor and +Argo setup is reused; image publication, Argo sync and successful workload execution +are separate evidence. + +### Shared gate evidence + +Each milestone closes with its ADR statuses, public contracts, reproducible commands, +version changes, test results and remaining limits recorded in STATUS and VALIDATION. +Tests run under NDEBUG; applicable Linux/Windows builds, format, tidy and sanitizer +jobs must pass. Timing thresholds require a declared host and workload. A gate is +not passed by an empty test, an image build, or a successful Kubernetes rollout alone. +Changes to persisted rules/formats require compatibility and migration decisions. + +## M5 - Basic voxel world + +**Goal:** a small, sparse, editable, headless 3D environmental volume, roughly the +founding 100x100x100 test scale or a documented chunk equivalent. It must support +deep/cavity edits without a surface-only assumption. Planet-scale geometry, spherical +indexing, LOD solvers, meshing and a renderer remain outside this gate. + +**Entry:** M4.6 report reviewed; WORLD_ARCHITECTURE and proposed ADR-0019 read. Scope +and layout must be accepted in a new scoped ADR before implementing storage. + +| ID / objective | Files/modules | Dependencies | Completion criteria | Tests / evidence | Risk | +|---|---|---|---|---|---| +| 5.1 Specify local world contract | docs/architecture/WORLD_ARCHITECTURE.md, docs/adr, include/evo/world | M4.6 | Define signed chunk addresses, voxel dimensions, local +Z-up frame, units, bounds and material/geometry representation; distinguish chunk, region and ecological cell | Address examples and independent round-trip oracle; rejected overflow cases | Accidentally choosing final planet topology | +| 5.2 Compare and select compact chunk layout | experiments/world, tests/benchmarks, ADR-0019 follow-up | 5.1 | Compare uniform/palette baseline and optional varying pages on uniform, mixed and excavated fixtures; pin initial chunk size and allocation limits from measurements | Resident/peak bytes including indexes, edit cost and encoded size; record rejected alternative | Compression overhead or dense hidden allocation | +| 5.3 Generate deterministic abiotic base | src/world/generation, include/evo/world, tests/world | 5.1-5.2 | Seed + address + generator/material versions yields identical chunks; adjacent chunks agree; generation creates no life | Frozen small fixtures, query-order independence, negative coordinates, boundary seams | Seeding depends on generation order | +| 5.4 Own sparse active chunks | src/world/chunks, tests/world | 5.2-5.3 | Absent chunks regenerate; bounded loading/eviction; immutable views carry revisions; dirty data cannot be silently evicted | Far-apart addresses, all-uniform worlds, memory cap/backpressure, stale view tests | Memory grows with address extent rather than touched data | +| 5.5 Apply transactional terrain edits | src/world/edits, schemas/world-edits, tests/world | 5.4 | Bounded edit commands with ID, request digest and expected revision; define multi-chunk atomic scope; account displaced volume/material into explicit destinations | Duplicate ID same/different payload, insufficient destination capacity, tunnel crossing seam, all-or-nothing rejection | Edits delete matter or partially publish | +| 5.6 Encode snapshots and edit journals | src/world/codec, schemas, tests/fuzz, apps/evo-tools | 5.3-5.5 | Canonical bounded format records address, base/generator/material versions, revision and covered edit sequence; restore base plus edits or compacted state | Round trip, malformed/truncated/oversized bytes, checksum/version errors, replay equality | Reinterpreting old chunks under new generator | +| 5.7 Compact and restore local state | src/world/journal, tools/world, tests/integration | 5.6 | Snapshot plus remaining journal reproduces uncompacted state; local-file publication has an explicit recovery contract; old source remains until verified replacement | Interrupted write/publish, corrupt candidate, missing sequence, disk-full injection | Treating uploaded/written bytes as committed state | +| 5.8 Close bounded world proof | docs/engineering, tests/benchmarks/world, apps/evo-tools | 5.1-5.7 | Reproduce create -> deep edit -> compact -> restart -> same hash and inventory; report memory/generation/edit/restore costs | Sparse/uniform/heavily modified workloads; unchanged-chunk regeneration; cross-platform golden checks | Small-volume result marketed as planet capacity | + +**Exit:** headless sparse chunk proof is buildable and restorable with deterministic +base/version retention and no unexplained material loss. M5 local files are not the +M7 production durability path. Any simplified volume-to-matter mapping is explicitly +versioned; M6 must reconcile it rather than invent a second inventory. + +M5.1 is implemented under [ADR-0042](adr/0042-local-voxel-contract.md): see +[the local contract](world/LOCAL_VOXEL_CONTRACT.md) for exact units, address limits, +negative seam examples and rejection rules. It does not allocate chunk storage. +Next is 5.2: benchmark compact representations and candidate edge lengths. + +**Decisions still open:** final spherical layout, region dimensions, adaptive LOD, +field quantization beyond the initial experiment, hydrology and surface extraction. +No Marching Cubes/Surface Nets/Dual Contouring selection is implied. + +## M6 - Environmental resources + +**Goal:** organisms and a small voxel environment exchange finite resources through +conserved accounting. Start with light/energy, water inventory with derived moisture, +one or two named nutrients and organic matter. Full chemistry, atmospheric circulation, +CFD, roots/canopies, erosion and 3D creature physics are later work. + +**Entry:** M5 local world gate and ENERGY_MODEL reviewed. Resolve how microscopic 2D +habitat area and effective depth map to environmental volume before connecting stores. + +| ID / objective | Files/modules | Dependencies | Completion criteria | Tests / evidence | Risk | +|---|---|---|---|---|---| +| 6.1 Ratify resource and coupling units | docs/biology/ENERGY_MODEL.md, docs/world, docs/adr, include/evo/world | M5 | Name extensive inventories, derived concentrations/moisture, energy source/sink terms, rounding residuals and valid ranges; specify 2D-to-3D volume mapping | Dimensional examples, closed/open system equations and invalid conversions | Area or concentration silently creates mass | +| 6.2 Store optional environmental fields | src/world/fields, schemas/world-fields | 6.1, 5.2, 5.6 | Material defaults plus sparse water/nutrient/organic pages; material ID alone grants no extractable supply; snapshot/version fields | Uniform vs varying footprint, finite exhaustion, round trip, old-version rejection | Dozens of floats per voxel or duplicated baseline resources | +| 6.3 Publish read-only environment views | include/evo/world/environment, src/world/resources | 6.2 | Footprint query returns values with units, resolution, tick and chunk revisions; missing data is explicit, not zero/unlimited | Seams, unavailable chunks, stale revisions, deterministic query order | Stale reads authorize consumption | +| 6.4 Commit environmental transfers | src/world/transfers, src/accounting adapters | 6.1-6.3 | Plan against immutable view; single-owner commit atomically validates organism and environment debits/credits; command IDs and changed-payload rejection | Two organisms contend for last nutrient, duplicate transfer, rollback and source/destination ownership | Resource spendable in both voxel and organism store | +| 6.5 Couple one producer and consumer fixture | src/processes adapters, tests/ecosystem | 6.4, M2-M3 contracts | Defined source flux funds capture; growth consumes water/nutrients; feeding transfers existing biomass; no implicit maintenance or reproduction rule changes | Source-off/starvation, nutrient limitation, temperature/resource boundaries, seeded replay | Fixture constants become game rules | +| 6.6 Return dead biomass to environment | src/processes/decomposition, src/world/transfers | 6.5 | Terminal organisms cannot act; bounded decay returns exact matter and accounted energy; residuals survive ticks | Death during pending consumption, duplicate decay, partial decay and nutrient-fed regrowth | Corpse disappears or decomposition runs twice | +| 6.7 Schedule local environment intervals | src/simulation scheduling adapters, src/world/resources | 6.4-6.6 | Explicit fixed intervals and phase order; read/write revisions prevent double integration; bounded catch-up; no implicit cross-region exchange | Interval split/merge where mathematically valid, pause/resume, maximum backlog, stale boundary refusal | Different update rates manufacture resources | +| 6.8 Validate integrated environmental slice | tests/ecosystem, tests/integration, docs/engineering | 6.2-6.7 | Environment -> producer -> consumer -> death -> nutrients -> growth, with integrated snapshot/restore and explicit version bundle | Multi-seed long runs, independent per-channel conservation including reservoirs/residuals, restore/replay hashes and cost report | Conservation passes while ecology collapses | + +**Exit:** one bounded microscopic habitat uses environmental inventories without +cross-scale literal physics or resource duplication. Read views are suitable for a +later client, but no rendering is required. Ecological results and failure regimes +are reported separately from arithmetic. Unsupported distributed transfers remain +rejected rather than simulated with untracked remote credits. + +## M7 - Persistent region server + +**Goal:** a disposable authoritative headless process can recover a bounded region +without losing acknowledged irreversible decisions. PostgreSQL is the preferred +authority; object payloads sit behind a storage adapter. The library does not acquire +SQL, network, Steam or Kubernetes dependencies. + +**Entry:** M6 integrated state is serializable; inventory actual state still missing +from snapshots, including lineage archive, genomes, RNG, residuals, pending commands +and versions. No existing particle or genome codec is assumed to cover a full region. +Follow PERSISTENCE_ARCHITECTURE and ADRs 0013/0016; the table adopts no client library. + +| ID / objective | Files/modules | Dependencies | Completion criteria | Tests / evidence | Risk | +|---|---|---|---|---|---| +| 7.1 Define region durability contract | docs/adr, schemas/region, include/evo/persistence | M6 | Specify region identity, state closure, simulation/commit watermarks, batch limits, irreversible ACK semantics and recovery format; choose replay or explicit full checkpoint batches | State inventory audit and crash-point matrix; exact replay requirements identified | Semantic events omit movement/randomness needed for recovery | +| 7.2 Adopt storage dependencies and migrations | src/persistence/database, migrations, dependency manifests | 7.1, ADR-0013 | Evaluate/pin PostgreSQL client and server pair; parameterized SQL, typed adapter errors, I/O ownership and bounded connection/deadline rules; only needed tables | Real PostgreSQL clean migration, supported upgrade path, rollback-on-error and permission checks | Dependency exception/transaction behavior leaks into simulation | +| 7.3 Implement fenced region ownership | src/server/world_director, src/persistence/leases | 7.2 | Director suggests assignment; DB serializes holder/epoch/expiry; commits lock/check lease and predecessor; worker role cannot bypass guard | Two contenders, expired renewal, paused stale writer, partition and database-time tests | Lease field exists but writes bypass its fence | +| 7.4 Encode and publish committed checkpoints | src/persistence/snapshots, object adapter, schemas/region | 7.1-7.3 | Coherent state includes complete version/RNG/history references; immutable payload verified before fenced manifest publication; unreferenced uploads are orphans | Missing/corrupt objects, upload/manifest failure, size caps, retained generator/binary restore | Snapshot mixes speculative and committed state | +| 7.5 Commit replay batches and permanent outcomes | src/persistence/events, src/server/region_host | 7.3-7.4 | Contiguous replay/checkpoint chain, canonical command digests, idempotent decisions and transactional outbox; batch DB writes; irreversible outcomes final only after durable confirmation | Commit-before-ACK disconnect, changed retry payload, gap/reorder, partial batch and duplicate births/deaths | Ambiguous commit treated as rollback | +| 7.6 Host bounded authoritative ticks | apps/evo-server, src/server/region_host | 7.1, 7.5 | One simulation owner with bounded I/O queues; simulated vs committed tick exposed; pause region at pending irreversible outcome; drain/shutdown and fail-closed readiness | Store outage, queue saturation, renewal failure, SIGTERM/forced kill, tick-debt measurement | Dependent actions use uncommitted reproduction/death | +| 7.7 Recover and verify before readiness | src/persistence/recovery, tests/integration | 7.4-7.6 | Load verified committed checkpoint, replay complete tail, verify hash/inventories/history, acquire valid current authority before serving | Kill at every publication/ACK boundary; corrupt/missing tail quarantines region; no empty fallback world | Silent world reset or resumed stale owner | +| 7.8 Add operations endpoints and dev image | apps/evo-server, core telemetry adapters, deploy/docker | 7.6-7.7 | Separate liveness/readiness; metrics for debt, commit lag, lease safety, checkpoint age and queue bounds; non-root image with no embedded secrets | Real process probes, metric-label bounds, unavailable DB readiness, image smoke test | Healthy process mistaken for valid authority | +| 7.9 Clone, migrate and qualify durability | tools/world-clone, migrations, tests/recovery, docs/engineering | 7.7-7.8 | Consistent clone into isolated world identity; explicit rule/format rejection/migration; durable-history retention; measured recovery and batching latency | Clone cannot publish into source; baseline vs restored trajectory; migration failure and old-writer fencing | Clone shares production credentials or rules change on restore | + +**Exit:** force-kill a real worker and recover through real storage with identical +committed state, retained ancestry and unique durable authority. Zero lost acknowledged +decisions under worker loss is required; the proposed 60-second recovery target is +measured under a declared fixture, not a universal promise. Database failure withholds +final outcomes and pauses before bounded pending/lease budgets expire. + +Cross-region seamless handoff, distributed population transfer and public realtime +multiplayer are not M7 acceptance claims. M7 lays their IDs/epochs/ownership contracts. +A local recovery proof does not establish host-loss durability; that is the M8 launch gate. + +## M8 - Kubernetes dev/stage recovery and guarded World0 + +**Goal:** run the M7 server through the existing GitOps pipeline, then qualify durable +World0 operation. Separate **M8-dev/stage passed** from **M8-World0 launch passed**. +World0 is persistent state, never a disposable smoke-test namespace. + +**Entry:** M7 recovery evidence and deployable digest. Reuse existing Gitea/Harbor/Argo +configuration; inspect the actual cluster before selecting storage or replica counts. +OPERATIONS and INFRASTRUCTURE_ARCHITECTURE govern protection and recovery semantics. + +| ID / objective | Files/modules | Dependencies | Completion criteria | Tests / evidence | Risk | +|---|---|---|---|---|---| +| 8.1 Inventory host and establish budgets | docs/infrastructure/inventory, deploy environment values | M7 image; read-only cluster access | Record R730xd CPU/RAM/storage, CNI/CSI, reclaim policies, failure domains, DNS/TLS and available capacity; reserve OS/stores/observability/recovery headroom | Measured disk latency/capacity and workload tick/resource profile | Treating 128GB as simulation-only memory | +| 8.2 Isolate environments and secrets | deploy/kubernetes overlays, deploy/argocd | 8.1 | Dev/stage/world0 identities, accounts, quotas, secret references and deny-by-default flows; no secrets in Git; World0 pruning/deletion protections designed | RBAC negative tests, cross-environment denial, cleanup rejects World0; parent-app deletion protection | One permissive app or credential can destroy all worlds | +| 8.3 Provision durable stores in dev/stage | deploy storage manifests, migrations jobs, docs/runbooks | 8.1-8.2, 7.2 | Adopt supported PostgreSQL and maintained object-store deployment with pinned versions; verify PV retention and backup destination | Pod restart, missing volume refusal, object semantics/digests, credentials rotation, full disk | Local PV binds failover to lost node | +| 8.4 Deploy director and region host | deploy/kubernetes, deploy/argocd, .gitea/workflows | 8.3, 7.8 | Immutable image digest, measured resources, probes, security context and drain budget; actual Argo sync/workload evidence | Region ready only after lease/recovery; graceful rollout and forced worker deletion | Successful rollout hides failed region recovery | +| 8.5 Add observability and bounded background delivery | deploy monitoring, dashboards, optional bus ADR | 8.4 | Tick/lease/commit/storage/backup alerts and bounded logs; evaluate DB outbox before optional JetStream; no mandatory Redis/Kafka | Alert injection, backlog/retry/idempotency tests if bus adopted, telemetry cardinality/cost report | Broker redelivery changes authority or logs fill disk | +| 8.6 Exercise recovery under faults | deploy/workflows, tests/operations, runbooks | 8.4-8.5 | Dev/stage pod-kill restores committed world automatically; stale owner cannot resume; unavailable state never initializes fresh | Repeated pod kill, stale process, DB/object outage, partition, disk full; record RTO and zero lost ACKs | Happy-path pod restart mistaken for disaster recovery | +| 8.7 Verify off-host backup and clone restore | tools/backup, deploy/workflows, docs/infrastructure | 8.3, 7.9 | Coordinated manifest covers DB/WAL, objects, versions, binaries and in-flight state; restore on independent storage; retention/GC respects clone/backup pins | Rebuild isolated world from backup, corruption and missing-object failure, credential/key recovery | Backup exists but cannot reconstruct causal state | +| 8.8 Qualify World0 acknowledgment and promotion | docs/adr, deploy/world0 protections, operations runbook | 8.6-8.7 | Ratify measured RPO/RTO and host-loss causal durability before irreversible ACK; independent durable chain or keep launch blocked; explicit promotion of reviewed digest/state | Host-loss restore preserves deaths, offspring, inventory and ancestry; fence old environment; promotion audit | Old backup resurrects dead organisms or duplicates resources | +| 8.9 Prove upgrade and growth operations | deploy/workflows, node scheduling values, docs/engineering | 8.6-8.8 | Clone/migrate/accelerate/compare before world-wide rules change; label/affinity plan works on one node and admits added compute nodes | Dev/stage version-barrier rehearsal, failed migration recovery, additional-node scheduling where hardware exists | Mixed physical laws or assuming added CPU makes storage portable | + +**Dev/stage exit:** a pinned M7 workload is observed running; pod termination yields +automatic fenced recovery with measured costs and tested alerts. **World0 launch exit:** +all independent recovery/acknowledgment, data-protection and explicit promotion gates +pass. If no independent durable failure domain exists, dev/stage can proceed while +World0 launch stays blocked; changing RPO silently is not a workaround. Do fault and +prune drills in isolated clones, never by deleting World0's namespace or data. + +Target recovery objectives in OPERATIONS remain proposals until measured and +accepted. No multi-node HA claim is made for the single physical host. Optional +JetStream is adopted only for a demonstrated delivery workload, not as lease authority. + +## M9 - Custom 2D engineering client + +**Goal:** a native desktop cellular viewer/controller with input, camera, renderer, +readable organism/environment views and a real development-server connection. +It is an engineering client, not the M11 playable game or the M13 3D engine. + +**Entry:** M6 view contracts; M7 durable authority for connection work and M8-dev/stage +for deployment evidence. No Unreal/Unity, browser delivery, Steam dependency, 3D +terrain meshing or procedural creature animation is required. + +| ID / objective | Files/modules | Dependencies | Completion criteria | Tests / evidence | Risk | +|---|---|---|---|---|---| +| 9.1 Select scoped client dependencies | docs/adr, dependency manifests, CMake | M6 views, constitution | Evaluate SDL3 and Vulkan/thin alternatives for native 2D support, tooling, portability, maintenance/license/size; pin adopted subset; audio may be explicitly deferred | Minimal window/input/render probes on supported targets, reproducible acquisition and license records | Building a general renderer before validating cellular views | +| 9.2 Establish platform and render boundary | apps/evo-client, src/client/platform, src/render | 9.1 | Window/event loop, resize/DPI/focus handling, orderly resource ownership; renderer consumes immutable views; headless targets build without client dependencies | Open/close/recreate, minimized window, device/init failure, headless build with client disabled | GPU/window types leak into biological APIs | +| 9.3 Add camera and input intentions | src/client/input, src/client/camera | 9.2, M6 coordinate contract | Pan/zoom and world-screen mapping; bounded intentions carry sequence/tick; UI focus prevents accidental world input | DPI/resize/zoom round trips, focus loss, key release, invalid ranges | Pixels become authority coordinates or stuck movement | +| 9.4 Render microscopic environment | src/render/environment, src/client/views | 9.2-9.3, 6.3 | Resource fields and boundaries render from revision-tagged views; missing/stale data has explicit presentation; no unbounded geometry/texture growth | Synthetic known fields, camera seams, stale update and frame/resource profile | Rendering changes resource simulation or hides missing data | +| 9.5 Render organisms and debug views | src/render/organism, src/client/ui | 9.4, M3 phenotype contracts | Visual parameters derive from available biology; players/NPCs use identical biological rendering; optional ImGui stays engineering UI | Same phenotype renders identically across controller types; death/removal, dense scenes, no player/NPC/level labels | Debug ownership labels become gameplay UI | +| 9.6 Define a narrow secure dev-session protocol | docs/networking, schemas/view, src/network adapters | 7.8, 9.3, ADR-0017 | Versioned bounded view/intent envelope, session identity, epoch and commit watermark; choose maintained transport/crypto for this scope; test identity is explicitly dev-only | Codec fuzz/bounds, unsupported versions, auth/replay/rate rejection, no native-struct trust | A temporary unauthenticated protocol escapes into production | +| 9.7 Connect to one authoritative dev region | src/client/session, src/server/session adapter | 9.6, M8-dev/stage | Real desktop-to-server connection, snapshot display and minimal admitted intent; reconnect requests fresh baseline; final outcomes reflect durable server ACK | Disconnect/reconnect, stale epoch, server pod restart, rejected intention and duplicate session tests | Client state or reconnect becomes authority | +| 9.8 Validate presentation and package the client | tools/client packaging, tests/client, docs/engineering | 9.1-9.7 | Reproducible native artifact, bounded snapshot/render queues, frame/memory report and documented manual visual checks | Install/run on supported dev platforms; long session, resolution/DPI matrix, headless regression suite | Declaring FUN or multiplayer scalability from a viewer | + +**Exit:** a packaged native client opens, renders an authoritative cellular development +scene, submits a bounded test intention and recovers its view after the server restarts. +The prototype session respects server authority and ownership epochs. M10 owns the +full real-time datagram/reliability selection, prediction, reconciliation, interpolation, +interest management and 20+ client acceptance. M9 may use a scoped secure reliable +channel if its ADR documents the limits and preserves transport-neutral semantics. +No renderer is needed for server tests; no client may decide energy, mutation, +reproduction or death. Steam and final player UI remain later product work. + ## Later gates | Milestone | Deliverable and acceptance gate | |---|---| -| M5 Basic voxel world | Sparse small-volume generation + modifications + restore; deterministic base and bounded delta tests; mesher remains an experiment | -| M6 Environmental resources | Light/moisture/limited nutrients connected through conserved transfers; no full chemistry simulation | -| M7 Persistent region | Unique fenced authority, durable outcomes, snapshots/replay, health/metrics, process-kill recovery; migrations before real data | -| M8 Kubernetes World0 | Inventory actual host, provision dev/stage/world0 with guarded promotion and backups; delete worker pod and restore automatically; restore on independent storage verified | -| M9 Custom 2D client | ADRs for SDL3, renderer and audio; usable window/input/camera, biological presentation, no NPC labels | | M10 Realtime multiplayer | Authenticated intentions, reliable outcomes, prediction/reconciliation/interpolation and interest; 20+ bot clients then measured scaling/fault tests | -| M11 Cellular gameplay | Movement, feeding, predation, mutation, reproduction, descendants, total restart; playtest FUN and repeated-life variety | +| M11 Cellular gameplay | Movement, feeding, predation, mutation selection, reproduction, descendants, total restart; playtest FUN and repeated-life variety | | M12 Persistent ecology | Days-long unattended worlds, genealogy, extinction evidence, player absence and diverse strategies; analyze collapse/runaway lineages | | M13 3D R&D | Isolated smooth meshing, body graph, procedural skin/physics/locomotion comparisons with measured exit criteria | -| M14 Multicellular transition | Ratified biological transition and first cell→multicellular→3D slice with conserved ecological coupling | +| M14 Multicellular transition | Ratified biological transition and first cell-to-multicellular-to-3D slice with conserved ecological coupling | No date or production capacity is promised without staffing and benchmark data. Every release records simulation/world/network versions; biological upgrades use -production snapshot → clone → migrate → accelerated comparison → approval. - +production snapshot -> clone -> migrate -> accelerated comparison -> approval. M4.6 completed as measurement tooling and a policy review on 2026-09-26; see [aggregate budget report](engineering/AGGREGATE_BUDGET.md). No automatic tier policy diff --git a/docs/STATUS.md b/docs/STATUS.md index d5cda9a..dfe6678 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -7,7 +7,7 @@ persistent simulation server. The founding vision remains unchanged. ## Completed implementation - Vision, architectural pillars, risks, open-question register, architecture - diagrams, biological contracts, engineering constitution and 41 ADRs. + diagrams, biological contracts, engineering constitution and 42 ADRs. Proposed/deferred choices remain distinct from accepted proof decisions. - M0–M4 task breakdowns with dependencies, acceptance evidence and risks, plus M5–M14 gates in [ROADMAP.md](ROADMAP.md). @@ -61,7 +61,7 @@ for the bounded proof; the general production ECS remains a later measured choic | Priority | Work | Completion evidence | |---|---|---| -| 1 | M5 small sparse voxel prototype | Deterministic generation, modification, snapshot and restore; select scoped storage contract first | +| 1 | M5.2 compare compact chunk layouts | Benchmark uniform/palette and optional varying pages across the explicit edge candidates; select storage in a scoped ADR | | Research | Improve aggregate fidelity and measure Linux/target-host costs | M4.6 found no qualifying width; see the aggregate budget report | | 2 | Revisit the ADR-0031/0032 reproduction cost model | Reproduction is affordable only at the genome schema's floor; decide whether that is intended before M4 builds cohorts on it | | Delivery gate | Add/update the dev workload when a deployable increment needs it; Argo is ready | Observe Job/pod completion separately from image publication; no World0 changes | @@ -519,3 +519,30 @@ widths passes the proposed fidelity gate across supplies 240/300/360; automatic selection remains disabled. The next implementation milestone is M5's sparse voxel prototype; aggregate-model improvement and Linux/target-host measurement remain prerequisites for a production tier policy. See VALIDATION.md for checks actually run. + + +## M5-M9 planning expansion - 2026-09-26 + +[ROADMAP.md](ROADMAP.md) now breaks M5-M9 into 42 reviewable tasks, each with +module boundaries, dependencies, completion criteria, tests and risks. These are +planned gates, not implementation or deployment claims. M8 dev/stage recovery is +separate from World0 launch; M9 client integration can use dev/stage without +premature World0 promotion. M4.6's failed fidelity gate remains explicit. +That expansion identified 5.1 as the next task; it is now implemented as recorded below. No library, service, cluster or dependency changed in this update. + + +## M5.1 - bounded local voxel contract (2026-09-26) + +Implemented dependency-free `evo::world` coordinate and cell-sample utilities, +[ADR-0042](adr/0042-local-voxel-contract.md), and +[LOCAL_VOXEL_CONTRACT.md](world/LOCAL_VOXEL_CONTRACT.md). Signed floor mapping handles +negative chunk seams; all public operations reject invalid bounds before arithmetic. +The experiment uses a 1m cell pitch and explicit edge candidates 8/16/32/64; it +selects no storage layout, renderer, spherical topology or production world extent. +Logical fill describes volume fraction, not surface shape or consumable inventory. + +Tests independently enumerate chunk intervals, exhaust 299,520 local ordinals, check +metric/domain corners and hostile signed/unsigned extrema, and validate fill/material +consistency. Existing simulation goldens/formats are unchanged. No world data or +service is deployed. Next: M5.2's measured layout/edge comparison; actual chunk +allocation and generator work follow its decision. See VALIDATION.md for checks. diff --git a/docs/adr/0042-local-voxel-contract.md b/docs/adr/0042-local-voxel-contract.md new file mode 100644 index 0000000..2609801 --- /dev/null +++ b/docs/adr/0042-local-voxel-contract.md @@ -0,0 +1,70 @@ +# ADR-0042: Bounded local voxel addresses and logical cells + +## Status +Accepted for M5.1 only. No chunk storage, generator, persistence, mesher, spherical +planet mapping or world-size choice is adopted. ADR-0019 remains proposed for those +choices. Existing particle coordinates and snapshot formats are unchanged. + +## Context +M5.2 must compare layouts against a stable logical domain. C++ integer division +truncates toward zero, which assigns negative cells to the wrong chunk unless the +mapping explicitly uses floor division. Unbounded signed arithmetic also risks +undefined behavior before an invalid address can be rejected. + +## Decision +Use a right-handed local Cartesian frame: +Z up and X cross Y = Z. Signed voxel +coordinates identify lower corners of half-open cells. All axes are in +[-1,048,576, 1,048,576); one cell spans 1,000 millimetres for this experiment. The +address envelope is an arithmetic guard, not allocated space or a planet extent. +The initial storage experiment should touch roughly 100 cells per axis. + +Chunk edge is explicit, with candidates 8, 16, 32 and 64 cells. No default or +preferred candidate is selected before M5.2 measures them. All divide the domain +exactly. Chunk coordinates are floor(voxel/edge), local offsets are nonnegative +remainders. Join validates edge, chunk and local bounds before multiplication. +Logical ordinal order is X-fastest, then Y, then Z. It is an enumeration convention, +not a mandated physical layout. Mapping functions allocate nothing, perform no I/O, +and use checked integer bounds with typed recoverable errors. + +A logical cell has a 16-bit material key and unsigned fill numerator over 65,535. +Material key zero means void and must have zero fill; a nonzero key requires positive +fill. The containing material table is versioned later; this layer validates only +structural consistency, not material existence. Fill denotes occupied volume fraction, +not a signed distance, density, chemical inventory, collision shape or mesh sample. +Sub-cell placement is unknown. A change in fill does not itself authorize matter +creation/destruction; edits must supply material accounting in M5.5/M6. + +The coordinate contract is local version 1. A future world key must include world +and frame identity and all layout/generator/material versions. Changing edge or +resolution is an explicit repartition/migration, never reinterpretation of stored +chunk keys. Region ownership and ecological cell boundaries are separate mappings. + +## Alternatives Considered +Truncating division breaks negative seams. Unsigned-only positions hide origin +crossings. Unbounded 64-bit addresses invite accidental overflow and imply unsupported +scope. Fixing edge 32 now would pre-empt M5.2's comparison. Signed distance fields +would bias future meshers; material-only blocks cannot express partial occupied +volume. Full chemistry or a generic dimensional algebra is outside this increment. + +## Benefits +Negative boundaries and exact round trips are testable independently of storage. +Extreme input is rejected before arithmetic. Logical occupancy does not select a +renderer or a planetary topology; sparse layouts can share the same fixtures. + +## Costs +Explicit edge arguments and validation cost a few integer operations. Full signed +input types carry values outside the valid domain. The bounded domain, candidate +edges and 1m pitch are experiments and need version review before extension. + +## Risks +Fill alone cannot reconstruct smooth geometry or conserve constituent mass. Material +keys without their future table cannot be interpreted. Domain size must not be +mistaken for supported memory or production scale. Raw logical structs are not a +wire format and may not be serialized by copying native bytes. + +## Consequences +Expose a dependency-free evo::world target. Test independent negative-floor oracles, +axis independence, signed extrema, bounds, all local ordinal positions, metric +corners, invalid edges and cell consistency in Release and sanitizers. No new +third-party dependency or existing simulation golden changes. M5.2 selects actual +storage and chunk dimensions through measured alternatives. diff --git a/docs/adr/README.md b/docs/adr/README.md index 7bd7f02..5dde9c6 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -41,3 +41,5 @@ benchmarked. Primary sources were reviewed during the initial September 2026 design. No unadopted candidate is a link dependency of the proof. - [ADR-0041: Aggregate cost and fidelity budget](0041-aggregate-budget.md) - M4.6 measurement only. + +- [ADR-0042: Local voxel contract](0042-local-voxel-contract.md) - accepted for M5.1; layout and planet mapping deferred. diff --git a/docs/architecture/OPEN_QUESTIONS.md b/docs/architecture/OPEN_QUESTIONS.md index 4bec02b..64c68ef 100644 --- a/docs/architecture/OPEN_QUESTIONS.md +++ b/docs/architecture/OPEN_QUESTIONS.md @@ -23,7 +23,7 @@ person. ADR indexes distinguish scoped proof choices from production proposals. | 15 | Multicellular transition | Physiological and ecological criteria unresolved | Design/biology; M14 | | 16 | Population abstraction | Conservative cohort ledger + distributions, ensemble validation | Ecology; M4 | | 17 | Region dimensions | Benchmark against interest, entities and migration overhead | Engine/platform; M7 | -| 18 | Planet coordinates | Hierarchical global address + local coordinates proposal | World; M5/M13 | +| 18 | Planet coordinates | M5.1 bounded local integer contract accepted (ADR-0042); global hierarchy remains proposed | World; M5/M13 | | 19 | Spherical voxels | Prototype cubed sphere versus alternatives; no fixed topology yet | World; M13 | | 20 | Voxel LOD | Sparse procedural base, aggregate fields, active chunks | World; M5/M13 | | 21 | Surface meshing | Marching Cubes / Surface Nets / Dual Contouring comparison | Render/world; M13 | diff --git a/docs/architecture/WORLD_ARCHITECTURE.md b/docs/architecture/WORLD_ARCHITECTURE.md index 5b8fe7a..4fdfbe2 100644 --- a/docs/architecture/WORLD_ARCHITECTURE.md +++ b/docs/architecture/WORLD_ARCHITECTURE.md @@ -103,3 +103,14 @@ duplicate edit idempotency; crash at every compaction boundary; oscillating LOD without resource gain; stale halo invalidation; stalled transfer escrow; corrupt objects/full disk rejection. No planet topology or smooth mesher is accepted until its comparison demonstrates precision, seam correctness and bounded cost. + + +## Implemented M5.1 boundary + +[ADR-0042](../adr/0042-local-voxel-contract.md) and the +[local voxel contract](../world/LOCAL_VOXEL_CONTRACT.md) implement pure signed +address mapping, logical ordinal enumeration, metric corners and cell-fill +validation in `evo::world`. The 1m pitch and bounded local domain are experiments; +8/16/32/64-cell chunk edges remain comparison candidates, not a selected layout. +No data allocation, terrain generation, material table, mass transfer, persistence, +meshing or planet mapping is implemented by this contract. M5.2 measures storage. diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index bac8d2e..19bfdb1 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -1398,3 +1398,30 @@ version changes. Existing contested-parent and round-trip controls remain active The final exception-handler-only adjustment was compiled in analysis; Release and ASan benchmark targets were then rebuilt and their resolution tests rerun. No performance or model algorithm changed after the archived timing run. + + +## M5.1 local voxel contract - 2026-09-26 + +Added ADR-0042, the local voxel contract and dependency-free `evo::world`. No +existing simulation golden, codec or runtime dependency changed. The earlier +uncommitted M5-M9 roadmap expansion is preserved in the working tree. + +Executed on Windows x64 / MSVC 19.44 with the repository helper: + +- `tools/windows-check.ps1 -Preset release -Action check`: configure/build, + warnings-as-errors and 40/40 CTest passed. +- `tools/windows-check.ps1 -Preset analysis -Action check`: clang-tidy 19 build + and 40/40 CTest passed. +- `tools/windows-check.ps1 -Preset asan -Action check`: AddressSanitizer build + and 40/40 CTest passed. Native Windows ASan is not UBSan coverage. +- `tools/windows-check.ps1 -Preset release -Action format`: passed. +- `git diff --check`: passed. + +New Release-active tests enumerate independent signed chunk intervals, all 299,520 +logical cell ordinals across edges 8/16/32/64, envelope corners, each-axis invalid +bounds including INT64_MIN/MAX and UINT32_MAX, metric coordinates and all valid +positive fill numerators. Typed rejection is checked before reading expected values. +No allocation/terrain-generation/performance claim is made for the address envelope. + +Linux GCC/Clang CI and UBSan have not been run for this increment. No container, +Argo or World0 deployment occurred. M5.2 storage benchmarks remain the next task. diff --git a/docs/world/LOCAL_VOXEL_CONTRACT.md b/docs/world/LOCAL_VOXEL_CONTRACT.md new file mode 100644 index 0000000..28b88fe --- /dev/null +++ b/docs/world/LOCAL_VOXEL_CONTRACT.md @@ -0,0 +1,83 @@ +# Local voxel contract v1 (M5.1) + +This is the scoped experiment in [ADR-0042](../adr/0042-local-voxel-contract.md). +Public API: `include/evo/world/coordinates.hpp`. It implements pure address mapping +and logical cell validation, not a world container or a persistent file format. + +## Frames and units + +Right-handed Cartesian frame, +Z up, X cross Y = Z. `VoxelAddress` contains signed +cell indices, not metres. `ChunkAddress` contains signed chunk indices. +`LocalCell` contains unsigned cell offsets within a chunk. `MetricCorner` contains +named signed millimetres. No implicit conversion to the old periodic 2D particle +coordinates exists. The 2D habitat/effective-depth mapping waits for M6.1. + +Per-axis voxel range is [-1,048,576, 1,048,576). Cell v owns the metric interval +[v*1000, (v+1)*1000) mm. The positive outer face exists geometrically but is not +another addressable cell. There is no wraparound or clamping. Negative Z is ordinary +volume, so the contract is not a surface heightfield. No origin shift is implicit. + +## Mapping and failure contract + +Callers explicitly pass edge N in {8,16,32,64}. M5.2 will compare those candidates; +there is no default chunk size. Valid chunk axes are [-1,048,576/N, 1,048,576/N). +Offsets satisfy 0 <= local < N. Each chunk covers exactly N cubed disjoint cells. + +``` +voxel --split(edge)--> {chunk, local} --join(edge)--> same voxel +local --ordinal(edge)--> x + N*(y + N*z) --local_from_ordinal(edge)--> same local +voxel --lower_corner_mm()--> signed metric corner +``` + +For edge 16, on any axis: + +| Voxel | Chunk | Local | +|---:|---:|---:| +| -17 | -2 | 15 | +| -16 | -1 | 0 | +| -1 | -1 | 15 | +| 0 | 0 | 0 | +| 15 | 0 | 15 | +| 16 | 1 | 0 | + +All functions return `std::expected` and leave arguments unchanged. Invalid edge +is reported before address validation; join checks chunk before local coordinates. +Metric conversion validates voxel bounds before multiplying. Accepted ordinal range +is [0,N cubed). Max N cubed is 262,144; all intermediate arithmetic is bounded. +Inputs at INT64_MIN/MAX and UINT32_MAX must fail safely, not overflow. + +| Error | Meaning | +|---|---| +| invalid_edge | Candidate edge not supported | +| voxel_out_of_range | Any signed voxel axis outside the local envelope | +| chunk_out_of_range | Any signed chunk axis outside the edge-specific envelope | +| local_out_of_range | Any local offset >= edge | +| ordinal_out_of_range | Ordinal >= edge cubed | +| invalid_cell | Fill >65,535 or void/material-fill mismatch | + +## Logical cell and identity boundaries + +`CellSample::create(MaterialId, fill)` produces a validated value. Material zero +and fill zero denote void. Nonzero material requires positive fill. Fill/65,535 is +an exact rational fraction of the 1m-cubed cell; integer volume/mass conversion must +carry remainders under a later accounting contract. No geometry shape, material +density, light, moisture, nutrients or energy are inferred from this value. + +An unknown nonzero material key is structurally valid here; M5.3's versioned table +must resolve it or reject it. Native sizeof/alignment is not an encoded layout. +Palette compression, uniform storage and varying pages belong to M5.2. Smooth +meshing needs additional geometry information and a separate comparison/ADR. + +A chunk is storage addressing, a region is simulation authority, and an ecological +cell is a resource/model domain. They are not interchangeable IDs. M5.1 functions +operate in one caller-selected frame; no function compares coordinates from different +worlds or frames. Persisting/exchanging keys requires those identities and versions +in the enclosing schema. No coordinate or material key allocates resident data. + +## Acceptance and next step + +Tests must prove floor mapping against an independently constructed interval oracle, +not merely split(join(x)); exhaust every ordinal for every candidate edge; test all +axes, seams, envelope corners and invalid extremes. M5.1 is complete when those +contracts build and pass. M5.2 next compares compact chunk layouts and sizes; it must +not infer a preferred storage representation from these C++ value types. diff --git a/include/evo/world/coordinates.hpp b/include/evo/world/coordinates.hpp new file mode 100644 index 0000000..fff28f7 --- /dev/null +++ b/include/evo/world/coordinates.hpp @@ -0,0 +1,84 @@ +#pragma once + +#include +#include +#include + +namespace evo::world { +inline constexpr std::uint32_t coordinate_contract_version = 1; +inline constexpr std::int64_t voxel_limit = 1'048'576; // [-limit, limit), every axis +inline constexpr std::int64_t cell_pitch_mm = 1'000; +inline constexpr std::uint32_t fill_scale = 65'535; + +// Values are logical addresses, never native serialization records. Each API +// validates raw input; constructing these aggregates does not validate them. +struct VoxelAddress { + std::int64_t x{}, y{}, z{}; + auto operator<=>(const VoxelAddress&) const = default; +}; +struct ChunkAddress { + std::int64_t x{}, y{}, z{}; + auto operator<=>(const ChunkAddress&) const = default; +}; +struct LocalCell { + std::uint32_t x{}, y{}, z{}; + auto operator<=>(const LocalCell&) const = default; +}; +struct ChunkLocation { + ChunkAddress chunk; + LocalCell local; + auto operator<=>(const ChunkLocation&) const = default; +}; +struct SignedMillimetres { + std::int64_t value{}; + auto operator<=>(const SignedMillimetres&) const = default; +}; +struct MetricCorner { + SignedMillimetres x, y, z; + auto operator<=>(const MetricCorner&) const = default; +}; +struct MaterialId { + std::uint16_t value{}; // zero is void; table membership is checked elsewhere + auto operator<=>(const MaterialId&) const = default; +}; +enum class WorldError : std::uint8_t { + invalid_edge, + voxel_out_of_range, + chunk_out_of_range, + local_out_of_range, + ordinal_out_of_range, + invalid_cell +}; + +// Explicit edge candidate in {8,16,32,64}; no storage size has been adopted. +[[nodiscard]] std::expected split(VoxelAddress voxel, + std::uint32_t edge) noexcept; +[[nodiscard]] std::expected join(ChunkLocation location, + std::uint32_t edge) noexcept; +// Canonical logical enumeration, X fastest. Does not prescribe memory layout. +[[nodiscard]] std::expected ordinal(LocalCell local, + std::uint32_t edge) noexcept; +[[nodiscard]] std::expected local_from_ordinal(std::uint32_t index, + std::uint32_t edge) noexcept; +[[nodiscard]] std::expected lower_corner_mm(VoxelAddress voxel) noexcept; + +// Occupied volume fraction only; not an SDF, density or biological inventory. +// Trivial value copies/moves preserve validity. No material database dependency. +class CellSample { + public: + [[nodiscard]] static std::expected create(MaterialId material, + std::uint32_t fill) noexcept; + [[nodiscard]] MaterialId material() const noexcept { + return material_; + } + [[nodiscard]] std::uint16_t fill() const noexcept { + return fill_; + } + auto operator<=>(const CellSample&) const = default; + + private: + CellSample(MaterialId material, std::uint16_t fill) : material_{material}, fill_{fill} {} + MaterialId material_; + std::uint16_t fill_; +}; +} // namespace evo::world diff --git a/src/world/coordinates.cpp b/src/world/coordinates.cpp new file mode 100644 index 0000000..d2dfad1 --- /dev/null +++ b/src/world/coordinates.cpp @@ -0,0 +1,101 @@ +#include "evo/world/coordinates.hpp" + +namespace evo::world { +namespace { +bool valid_edge(std::uint32_t edge) noexcept { + return edge == 8 || edge == 16 || edge == 32 || edge == 64; +} +bool inside(std::int64_t value, std::int64_t limit) noexcept { + return value >= -limit && value < limit; +} +bool valid_voxel(VoxelAddress voxel) noexcept { + return inside(voxel.x, voxel_limit) && inside(voxel.y, voxel_limit) && + inside(voxel.z, voxel_limit); +} +bool valid_local(LocalCell local, std::uint32_t edge) noexcept { + return local.x < edge && local.y < edge && local.z < edge; +} +struct Axis { + std::int64_t chunk; + std::uint32_t local; +}; +Axis split_axis(std::int64_t voxel, std::int64_t edge) noexcept { + auto chunk = voxel / edge; + auto local = voxel % edge; + if (local < 0) { + --chunk; + local += edge; + } + return {chunk, static_cast(local)}; +} +} // namespace + +std::expected split(VoxelAddress voxel, std::uint32_t edge) noexcept { + if (!valid_edge(edge)) { + return std::unexpected{WorldError::invalid_edge}; + } + if (!valid_voxel(voxel)) { + return std::unexpected{WorldError::voxel_out_of_range}; + } + const auto x = split_axis(voxel.x, edge); + const auto y = split_axis(voxel.y, edge); + const auto z = split_axis(voxel.z, edge); + return ChunkLocation{{x.chunk, y.chunk, z.chunk}, {x.local, y.local, z.local}}; +} + +std::expected join(ChunkLocation location, std::uint32_t edge) noexcept { + if (!valid_edge(edge)) { + return std::unexpected{WorldError::invalid_edge}; + } + const auto limit = voxel_limit / edge; + const auto chunk = location.chunk; + if (!inside(chunk.x, limit) || !inside(chunk.y, limit) || !inside(chunk.z, limit)) { + return std::unexpected{WorldError::chunk_out_of_range}; + } + const auto local = location.local; + if (!valid_local(local, edge)) { + return std::unexpected{WorldError::local_out_of_range}; + } + // Both operands bounded above; multiplication cannot overflow or escape the + // voxel envelope. Domain divisibility means no partial outer chunks exist. + return VoxelAddress{chunk.x * edge + local.x, chunk.y * edge + local.y, + chunk.z * edge + local.z}; +} + +std::expected ordinal(LocalCell local, std::uint32_t edge) noexcept { + if (!valid_edge(edge)) { + return std::unexpected{WorldError::invalid_edge}; + } + if (!valid_local(local, edge)) { + return std::unexpected{WorldError::local_out_of_range}; + } + return local.x + edge * (local.y + edge * local.z); +} + +std::expected local_from_ordinal(std::uint32_t index, + std::uint32_t edge) noexcept { + if (!valid_edge(edge)) { + return std::unexpected{WorldError::invalid_edge}; + } + if (index >= edge * edge * edge) { + return std::unexpected{WorldError::ordinal_out_of_range}; + } + return LocalCell{index % edge, (index / edge) % edge, index / (edge * edge)}; +} + +std::expected lower_corner_mm(VoxelAddress voxel) noexcept { + if (!valid_voxel(voxel)) { + return std::unexpected{WorldError::voxel_out_of_range}; + } + return MetricCorner{ + {voxel.x * cell_pitch_mm}, {voxel.y * cell_pitch_mm}, {voxel.z * cell_pitch_mm}}; +} + +std::expected CellSample::create(MaterialId material, + std::uint32_t fill) noexcept { + if (fill > fill_scale || ((material.value == 0) != (fill == 0))) { + return std::unexpected{WorldError::invalid_cell}; + } + return CellSample{material, static_cast(fill)}; +} +} // namespace evo::world diff --git a/tests/world_coordinates_tests.cpp b/tests/world_coordinates_tests.cpp new file mode 100644 index 0000000..89a3a05 --- /dev/null +++ b/tests/world_coordinates_tests.cpp @@ -0,0 +1,150 @@ +#include "evo/world/coordinates.hpp" + +#include +#include +#include +#include +#include +#include + +namespace { +using namespace evo::world; +void check(bool condition, std::source_location at = std::source_location::current()) { + if (!condition) { + throw std::runtime_error("world coordinate line " + std::to_string(at.line())); + } +} +#define CHECK(...) check(static_cast(__VA_ARGS__)) +template bool refused(const std::expected& result, WorldError error) { + return !result && result.error() == error; +} +constexpr std::array edges{8, 16, 32, 64}; + +void independent_interval_oracle() { + // Enumerate known half-open chunk intervals rather than deriving an expected + // quotient using the same division as the implementation. Pair different + // signed axes so a swapped/reused coordinate is observable. + for (const auto edge : edges) { + for (std::int64_t chunk = -20; chunk <= 20; ++chunk) { + for (std::uint32_t local = 0; local < edge; ++local) { + const ChunkLocation expected{{chunk, -chunk, chunk + 3}, + {local, edge - 1 - local, (local + 1) % edge}}; + const VoxelAddress voxel{chunk * edge + local, -chunk * edge + (edge - 1 - local), + (chunk + 3) * edge + ((local + 1) % edge)}; + const auto actual = split(voxel, edge); + CHECK(actual && *actual == expected); + const auto rebuilt = join(expected, edge); + CHECK(rebuilt && *rebuilt == voxel); + } + } + } + const auto seam = split({-17, -16, -1}, 16); + CHECK(seam && *seam == ChunkLocation{{-2, -1, -1}, {15, 0, 15}}); +} + +void every_ordinal_has_one_local_cell() { + for (const auto edge : edges) { + std::uint32_t counter = 0; + for (std::uint32_t z = 0; z < edge; ++z) { + for (std::uint32_t y = 0; y < edge; ++y) { + for (std::uint32_t x = 0; x < edge; ++x) { + const LocalCell expected{x, y, z}; + const auto index = ordinal(expected, edge); + CHECK(index && *index == counter); + const auto decoded = local_from_ordinal(counter, edge); + CHECK(decoded && *decoded == expected); + ++counter; + } + } + } + CHECK(refused(local_from_ordinal(counter, edge), WorldError::ordinal_out_of_range)); + CHECK(refused(local_from_ordinal(std::numeric_limits::max(), edge), + WorldError::ordinal_out_of_range)); + } +} + +void envelope_corners_and_metrics() { + constexpr std::array ends{-voxel_limit, voxel_limit - 1}; + for (const auto edge : edges) { + for (const auto x : ends) { + for (const auto y : ends) { + for (const auto z : ends) { + const VoxelAddress voxel{x, y, z}; + const auto at = split(voxel, edge); + CHECK(at); + const auto restored = join(*at, edge); + CHECK(restored && *restored == voxel); + const auto mm = lower_corner_mm(voxel); + CHECK(mm && mm->x.value == x * 1000 && mm->y.value == y * 1000 && + mm->z.value == z * 1000); + } + } + } + } + const auto metric = lower_corner_mm({-1, 2, -3}); + CHECK(metric && *metric == MetricCorner{{-1000}, {2000}, {-3000}}); +} + +void invalid_values_fail_before_arithmetic() { + constexpr auto maximum = std::numeric_limits::max(); + constexpr auto minimum = std::numeric_limits::min(); + constexpr auto unsigned_maximum = std::numeric_limits::max(); + for (const auto edge : {0U, 1U, 7U, 9U, 15U, 63U, 65U, unsigned_maximum}) { + CHECK(refused(split({minimum, maximum, 0}, edge), WorldError::invalid_edge)); + CHECK(refused(join({{minimum, maximum, 0}, {}}, edge), WorldError::invalid_edge)); + CHECK(refused(ordinal({}, edge), WorldError::invalid_edge)); + CHECK(refused(local_from_ordinal(0, edge), WorldError::invalid_edge)); + } + for (const auto edge : edges) { + for (const auto bad : {minimum, maximum, -voxel_limit - 1, voxel_limit}) { + for (const auto voxel : + {VoxelAddress{bad, 0, 0}, VoxelAddress{0, bad, 0}, VoxelAddress{0, 0, bad}}) { + CHECK(refused(split(voxel, edge), WorldError::voxel_out_of_range)); + CHECK(refused(lower_corner_mm(voxel), WorldError::voxel_out_of_range)); + } + } + const auto limit = voxel_limit / edge; + for (const auto bad : {minimum, maximum, -limit - 1, limit}) { + for (const auto chunk : + {ChunkAddress{bad, 0, 0}, ChunkAddress{0, bad, 0}, ChunkAddress{0, 0, bad}}) { + CHECK(refused(join({chunk, {}}, edge), WorldError::chunk_out_of_range)); + } + } + for (const auto bad : {edge, unsigned_maximum}) { + for (const auto local : + {LocalCell{bad, 0, 0}, LocalCell{0, bad, 0}, LocalCell{0, 0, bad}}) { + CHECK(refused(join({{}, local}, edge), WorldError::local_out_of_range)); + CHECK(refused(ordinal(local, edge), WorldError::local_out_of_range)); + } + } + } +} + +void logical_fill_is_not_a_material_database() { + const auto empty = CellSample::create({0}, 0); + CHECK(empty && empty->material() == MaterialId{0} && empty->fill() == 0); + CHECK(refused(CellSample::create({1}, 0), WorldError::invalid_cell)); + for (std::uint32_t fill = 1; fill <= fill_scale; ++fill) { + CHECK(refused(CellSample::create({0}, fill), WorldError::invalid_cell)); + const auto sample = CellSample::create({65535}, fill); + CHECK(sample && sample->fill() == fill && sample->material() == MaterialId{65535}); + } + CHECK(refused(CellSample::create({1}, fill_scale + 1), WorldError::invalid_cell)); + CHECK(refused(CellSample::create({1}, std::numeric_limits::max()), + WorldError::invalid_cell)); +} +} // namespace +int main() try { + independent_interval_oracle(); + every_ordinal_has_one_local_cell(); + envelope_corners_and_metrics(); + invalid_values_fail_before_arithmetic(); + logical_fill_is_not_a_material_database(); + std::puts("PASS bounded world coordinates, negative seams, ordinals and cell samples"); + return 0; +} catch (const std::exception& error) { + std::fprintf(stderr, "%s\n", error.what()); + return 1; +} catch (...) { + return 1; +}