Author SHA1 Message Date
Fr0zkaandClaude Opus 5.5 b5ed321b9e wip(L16, side branch): disk terrain cache design + headless Linux prototype
Exact lossless zlib tile records (keyed on world/season/recipe/plan/evaluator/options/tile),
pristine cache plus ordered edits, server never trusts client caches, corruption/stale rejection,
atomic writes, 2 GB cap. Loaded tiles match regenerated hashes (L1 view, 24 m crossing).
NOT for assembler/world yet: the shared StreamBenchmarkPipeline.h includes Linux-only headers
(unistd/fcntl/zlib), which would break the Windows viewer build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CSFYgsdW8ejZSyiMf4qRSX
2026-10-20 04:19:56 +02:00
102 changed files with 1870 additions and 8005 deletions

No files matched your search

+5 -148
View File
@@ -73,7 +73,7 @@ is the only density path; a degenerate (zero-height) strate has none and is open
| Maze | `FMazeGenerationParams` | `BuildMazeStack` | origin-directed spanning-tree corridors on a 3D lattice, with capped loop edges and a thread-local per-cell capsule cache |
| SurfaceWorld | `FSurfaceGenerationParams` | `BuildSurfaceStack` | heightfield terrain: domain-warped continents+ridged mtns+detail, a low-freq **relief map** (`M`) that scales mountains/elevation for plains↔highland variety, **F20 heightfield terrain ops** (`Surface|Ops` — all default off ⇒ byte-identical): **Cliff** (slope-gated steepening — where the analytic structural slope > `CliffSlopeThreshold`, push the height away from the local mean by `CliffSharpness` ⇒ gentle slopes become sheer walls/canyon faces that hug real steep ground, gentle areas untouched; 4 structural resamples only when enabled), **Terrace** (relief-gated plateau quantize + `TerraceHardness` soft-round↔crisp-mesa), **LayerLines** (sedimentary sine shelves, slope-expressed) — pure per-column height remaps in the single oracle `ComputeSurfaceTerrainZ` (`SampleSurfaceStructuralZ` = pre-op raw height, re-sampled at an XY offset for Cliff's slope), biome-selected + border-blended for free via each biome's `SurfaceParams` + the height output-lerp; plus **phase-2 Overhang** (the first VOLUMETRIC op — real jutting shelves like a cliff lip): in `FOverhangShelfMod`, for AIR voxels in the window `(TerrainZ, TerrainZ+OverhangHeight]` above a steep slope, the heightfield is re-sampled UPHILL (toward the cliff) by a reach that GROWS with height and unioned in. Low in the window the shift is ~0 (borrows nearby low rock ⇒ stays air over the void); high up it reaches the far cliff (solid) ⇒ a shelf attached to the cliff, tapering out over the void with air underneath. Per-column `OverhangAmp`(=strength·slope-gate) + unit uphill dir `(DirX,DirY)` are resolved once in `ComputeSurfaceColumn` — the gradient sampled at the REACH scale (`OverhangReach`) so a point out over the void can "see" the cliff to know which way is uphill — and cached on `FSurfaceColumn`. It's genuine 3D (per-voxel structural re-eval), so it's gated hard to steep overhang columns; the union only ADDS rock (never removes), capped at `TerrainZ+OverhangHeight`, so `ClassifyTile` forces Mixed only in `(TerrainZ, TerrainZ+OverhangMargin]` (upward-only; margin = max `OverhangHeight`) — a shelf never holes a trivially-skipped tile, and only the thin cliff-edge band of air tiles is woken (NOT far-field like phase-3 spikes/holes). Overhang undersides classify as ground rock by the F17 rule (down-facing but below `TerrainZ`). Known v1 limit: applies at all LODs (Step-agnostic) — may alias far; gate to fine tiles later. Beaches at water line, high sky-cap ceiling. The cap is shapeable terrain in its own right (`ComputeSurfaceCeiling`, `Surface|Sky` params: `CeilingUndulation` broad inverted hills/valleys, `CeilingRidgeStrength` hanging ridgelines, `CeilingRoughness`+freq fine bumps, `CeilingWarp*`) — defaults (strengths 0, freq 0.04) = old flat-ish cap. (`Surface|Macro` params = the cheap precursor to biomes; `ReliefStrength=0` ⇒ old uniform terrain.) **Sky-cap vs ground is a PER-TRIANGLE surface class (F17), not a per-tile verdict**: the mesher classifies each unique vertex on the **worker** — only down-facing verts (`N.Z<-0.1`) pay a memoized `GetSurfaceHeightAt` column query; nearer `CeilSurf` ⇒ sky-cap, nearer `TerrainZ` ⇒ terrain overhang stays ground (a future SurfaceWorld cave roof — down-facing but below `TerrainZ` — also lands ground by the same rule; non-surface strates always ground). Triangles take the majority class of their 3 verts and are packed as **two contiguous index runs** (ground then cap, `FVoxelMeshData::NumCeilingTriangles`; skirts inherit their source triangle's run) → RMC **polygroups 0/1** → one **section per non-empty group** (`ApplyMeshToTile`, material slot = group index): slot 0 = strate `OverrideMaterial`/default (min-corner chunk), slot 1 = `CeilingMaterial` resolved at the tile's **TOP chunk** (mid as gap fallback, then min; fallback: ground material) — a coarse tile is 2^level chunks tall, so its min corner can sit in a lower strate/gap while the cap belongs to the strate above (this was the "far cap = ground material" residue), so the shadowless overhead rock is tinted separately instead of reading flat/bright. Shadow is **per section** via `FRealtimeMeshSectionConfig::bCastsShadow` (NOT the component `SetCastShadow` — RMC's proxy ignores the component flag; this is also why level≥2 far tiles only stopped casting once the section flag was wired): ground casts at level≤1, the cap section never casts, so the rock ceiling never shadows the terrain below it. History: v1 was a game-thread centre height-oracle (misclassified coarse far tiles → terrain material on the cap underside); v2 a whole-tile worker normal VOTE — which painted **mixed coarse tiles** (one far tile spanning terrain AND cap) entirely with the winner's material, and put sky material under terrain overhangs. The per-triangle class fixes both and is the identity channel caves/F8 will reuse. |
| VerticalShafts | `FVerticalShaftParams` | `BuildVerticalShaftStack` | full-height shafts + horizontal connectors + partial ledges |
| FloatingIslands | `FFloatingIslandParams` | `BuildFloatingIslandStack` | asymmetric islands: flat land top + underside tapering to a point, lobed (domain-warped) outline, beneath the shared ceiling at its configured strate upper boundary |
| FloatingIslands | `FFloatingIslandParams` | `BuildFloatingIslandStack` | asymmetric islands: flat land top + underside tapering to a point, lobed (domain-warped) outline, in an open void |
| Underwater | `FStrateGenerationParams` + water | (reuses `BuildTunnelNetworkStack`) | tunnel rock + high water table |
All stacks share the convention: internal **positive=solid**, and `AppendStructuralPost` ends every
@@ -1431,9 +1431,8 @@ density roots, including a 100 cm datum-offset negative control. See
evaluators keep their recorded cap behavior. The clip joins the exact near density root at the owning
boundary without changing LOD0–3 density hashes. Future families with planar roofs must declare their
cap height and bounds through the family plan/provider contract; the shared tile generator consumes
that declaration. FloatingIslands uses the same resolved strate-boundary data flow: its upper seal
follows its plan's chunk range and the shared boundary-seal primitive, while SurfaceWorld keeps its
existing heightfield cap.
that declaration. FloatingIslands declares no planar roof, so open sky above a surface island is the
expected view.
For each requested far SurfaceWorld XY column at LOD4–8, desired-tile selection adds cap-height
bands only when they do not overlap an existing or already accepted 3D clipmap tile. The original
@@ -1472,9 +1471,8 @@ neighborhood have installed collision (or are explicitly collision-not-required)
now** — the active view has ground, horizon and the family-appropriate ceiling, with no exposed
coverage hole or unexpected sky; (3) **refined soon** — each target LOD resolves within its stated
time or travel distance after entering range. While moving, report the largest frame/time gap in
enclosure and maximum distance that unresolved work trails the pawn. FloatingIslands is enclosed by a
planar roof at the upper boundary of its configured strate range; a taller strate places that roof
farther above its islands.
enclosure and maximum distance that unresolved work trails the pawn. FloatingIslands has open sky by
design, so its enclosure check excludes a planar roof.
The shared `AVoxelWorld::UpdateChunksAroundPosition` scheduler serves both the Core snapshot path and
Core-off legacy path. It admits the collision-critical 3×3 ring first. The measured S5 order remains
@@ -1842,147 +1840,6 @@ fill and check page tiles against the evaluator they actually sample. This is th
the Unreal adapter and its asynchronous MPSC/Epoch flow are unchanged. See
[`Standalone/Research/WorldAssemblerM3/Linux13/REPORT.md`](Standalone/Research/WorldAssemblerM3/Linux13/REPORT.md).
### 8.37 Shared strate boundaries and FloatingIslands lower seal — World Assembler L18
`FStandaloneShapeWorld::GetResolvedStratumBounds` supplies one physical lower/upper-bound descriptor
to layer ranges, far-field sample protection, and far-shell continuity for every strate. SurfaceWorld
retains its exact `topChunkZ * 32` Core-voxel mapping and native heightfield cap. Native FloatingIslands
takes its resolved bounds from its plan, whose chunk range is converted through the serialized
owner/Core voxel ratio. Its version-3 field removes only the lower all-XY seal and calls the same
`VF_ApplyUpperBoundarySeal` primitive used by the shared two-sided `VF_ApplyBoundarySeal` for its upper
boundary. The ceiling therefore sits at that strate's own upper boundary, with the common
`boundarySealSubvoxels` thickness; there is no FloatingIslands-specific height. The recipe range is
un-inset to match the Unreal adapter. Versions 1 and 2 retain their serialized two-sided seals.
SurfaceWorld's field and output hashes remain unchanged. See
[`Standalone/Research/WorldAssemblerM3/Linux18/REPORT.md`](Standalone/Research/WorldAssemblerM3/Linux18/REPORT.md).
### 8.38 Closed shared boundary ceilings and LOD sampling audit — World Assembler L19
`AppendStratumBoundaryCeilings` fills a candidate cell when the authoritative field is solid just
inside that strate's configured upper boundary. It does not require the raw field to cross back to
air above the boundary: the ceiling itself closes the strate even when the field continues solid
through that plane. This avoids isolated holes where a coarse lattice node has no zero crossing.
`FFarMeshColumnIndex::HasDownwardCellCoverage` still suppresses a fallback quad only after its
interior and perimeter probes all hit the existing downward face. The L19 `farHorizonVersion` is 4
for this shared boundary-cap change; hashes remain direct at LOD0–3 and salted at LOD4–8. No density
query, stratum position, scale, or asynchronous route changes. The strict LOD0–8 roof and paired-edge
audit and the matched before/after captures are in
[`Standalone/Research/WorldAssemblerM3/Linux19/REPORT.md`](Standalone/Research/WorldAssemblerM3/Linux19/REPORT.md).
### 8.39 Resolved layout snapshots and nominal strate bands — World Assembler L21 (historical)
`ResolvedLayoutSnapshotV1` is a separate Core-owned record built from the resolved manager slots and
the native SurfaceWorld/FloatingIslands plans. It has a canonical JSON representation, schema version,
and stable FNV-1a identity. Its physical intervals use half-open micrometre coordinates; recipe anchors
retain their serialized fixed-point units. The Unreal adapter exports it beside `world_assembly`, so the
layout digest never salts a recipe, manifest, density, or mesh hash. The standalone exporter follows
the same builder after plan resolution. It runs once per plan request and is not read from density or
tile-worker loops.
Each record separates the nominal ceiling, content, and bedrock bands. A strict layout requires that
sequence for every strate and requires bedrock(N) to touch the next strate's ceiling(N+1). The two
bands remain separately owned. Gradient and Interleaved interfaces may declare interpenetration only
inside their explicit transition zone; Hard has zero effective width. The manager's `TransitionBlendChunks`
is expressed in owner-chunk metres. Interleaved's existing two-chunk domain warp extends its possible
fingers beyond the blend width and is recorded separately. Compatibility validation reports current
gaps, overlaps, ambiguities, inactive/missing bands, and unhonoured transitions while accepting them;
strict validation rejects them. Core dispatches per-strate recipe fields without applying that
parameter blend, even though the legacy manager helper implements it. Both band types default diggable,
with protection represented explicitly.
Compatibility facts from L21: native SurfaceWorld plan/query bounds use 32 Core voxels (8 m) per
dispatch chunk, while FloatingIslands converts the 32-voxel owner chunk through its 12.5/25 cm scale
(16 Core voxels, 4 m). In the prototype where the top slot is FloatingIslands, this leaves a nominal
60 m interval between the FI bottom (−60 m) and SurfaceWorld top (−120 m); the Core selectors fall
through to the compiled analytic FloatingIslands fallback there. Core does not apply the manager's
parameter blend at either recipe boundary. The FI v3 upper seal remains a ceiling inside its current
content range, and its missing lower bedrock is recorded without changing evaluation. See
[`Standalone/Research/WorldAssemblerM3/Linux21/REPORT.md`](Standalone/Research/WorldAssemblerM3/Linux21/REPORT.md).
### 8.40 Fixed-metre strate layout units and shared boundary volumes — World Assembler L22
`StrateLayoutChunkSizeMeters` is one world-level setting, defaulting to **8 m**, independent of the
legacy 32-voxel chunk and Core's 32³ storage tile. The director resolves the setting once to physical
micrometres and Core subvoxels; every generator plan and dispatch reads that snapshot. At a 25 cm Core
voxel, an 8 m layout chunk is 32 Core voxels (8192 1/256-voxel units); at 20 cm it is 40 Core voxels
(10240 units). The Core tile remains 32³ voxels and is not a layout chunk.
The owner's FI/SW intervals are contiguous: FloatingIslands occupies [−120,+8) m and SurfaceWorld
occupies [−632,−120) m. Each strate is ceiling → content → bedrock. Both solid, diggable boundary
bands use its generator's existing `BoundarySealThickness` and `BaseDensity`; `InterStrateGapChunks`
controls only spacing, and `EdgeSealThickness` remains horizontal. No new thickness parameter or hidden
band height was added. The shared composition layer emits both volumes for every generator and the
shared mesh path closes their visible ceiling and floor faces.
The snapshot is schema V2 and is consumed by bounds planning, native and legacy dispatch, solid-band
composition, and validation. Strict validation accepts the real owner layouts, and the boundary probe
audit agrees at all 27 sampled endpoints in both recipe modes. The owner authored Gradient transition
is recorded as an explicit Hard fallback with zero interpenetration; Gradient and Interleaved mixing
remain unimplemented and must not be inferred from the declared blend width. Seven validator negative
controls continue to reject malformed bands.
Evidence and owner caveats are in
[`Standalone/Research/WorldAssemblerM3/Linux22/REPORT.md`](Standalone/Research/WorldAssemblerM3/Linux22/REPORT.md).
### 8.41 Director-resolved inter-strate passages and walkable landings — World Assembler L23
Core passage geometry is derived after the director has resolved physical strate bands and native
route anchors. `PlanResolvedLayoutPassagesV1` joins every adjacent resolved pair. Its placement hash
uses `(seed, upper strate, lower strate, connection, salt)`; `PassageConfig.DistanceMax` is the
outer radius around world `(0,0)` (24 m for the owner's first interface), while `DistanceMin` is
the inner radius used when a mouth has no route anchor. A route-bound mouth reuses the upper
strate's departure or lower strate's arrival anchor, after checking it lies within `DistanceMax`.
The legacy `UVoxelStrateManager::GeneratePassages` and its owner-voxel control points remain the
legacy generator path; Core does not import the exported legacy `passages` array. The season
manifest carries recipes and plans, and the adapter rebuilds the resolved layout and its passages
from the current manager slots and route anchors each time it attaches the Core world.
`ApplyResolvedStrateComposition` composes the current generator field, applies the resolved ceiling
and bedrock bands, then unions the passage carve and floor support. Only the hashed capsule path
opens a band; the support strip stays below the player capsule. The lower mouth index splits the
monotone descent from the short route-bound landing tail, whose height may vary with the route.
Both route and passage audits sample the 0.34 m by 1.76 m capsule, support probes, and grade; the
negative control compiles the same world without passage carving and must detect a blocked capsule.
The L23 shared-field change is `WorldAssemblyEvaluatorVersion=9`. It does not change the L22 bands
or any generator's field away from a passage. The L23 report includes exact-query/hash comparisons,
the blocked control, captures, and the Windows adapter checklist. §8.10's cache, proof, streaming,
and async rules remain unchanged.
[`Standalone/Research/WorldAssemblerM3/Linux23/REPORT.md`](Standalone/Research/WorldAssemblerM3/Linux23/REPORT.md)
records the audit and captures.
### 8.42 Per-strate natural passages and the FloatingIslands anchor helix — World Assembler L24
`FStratePassageConfig.Style` now drives the shared Core planner for every generator. The default is
`Worm`; Straight, Spiral and Cascading remain selectable per upper strate. Passage radius, reach,
distance and style stay in the resolved-layout input, so equal seeds and route anchors produce equal
paths on every peer. The passage carver adds bounded, deterministic wall relief (`0.24 m` before the
gravity-facing attenuation) while its support tread follows the same route profile below the capsule.
FloatingIslands' owner config selects Spiral. A seed-derived anchor island near `(0,0)` is joined to
bedrock by a 6 m radius rock root. The 3 m helix descends from the island mouth to the `-119.5 m`
bedrock top inside that root, leaving at least the authored clearance around its 1.5 m bore, then
widens into the Worm route toward the SurfaceWorld arrival. The selected anchor is ordinal 2; the
other island ordinals and their placement hashes are unchanged. FloatingIslands recipe geometry is
version 5 and the shared passage evaluator is version 10; the resolved-layout snapshot stays V3.
The passage naturalness audit rejects a horizontal run above 8 m (segments flatter than 0.5 degrees)
or wall relief below 0.20 m peak-to-peak across at least 8 valid samples. The smooth-wall control
has zero relief and fails; the anchored Spiral has 0 m flat run and 0.793 m measured relief. Strict
layout controls, route binding, capsule clearance, support, grade, and the no-carve negative control
remain required. Passage-centered interval proofs remain unknown/fallback rather than falsely
certified. At the lower mouth, the shared layer now relies on native terrain plus the passage tread;
it does not stamp additional flat route-anchor shelves over the cave opening. The L24 report records
compiler/worker parity, unchanged SurfaceWorld hashes away from the route, captures and the Windows
adapter checklist.
The Linux offscreen capture tool accepts `--headlamp=on` to aim brighter readable shading from the
camera for interior views and `--clip-plane=NX,NY,NZ,D` to discard the plane's negative half-space for
cutaway views. Both affect captures only, not generated geometry.
[`Standalone/Research/WorldAssemblerM3/Linux24/REPORT.md`](Standalone/Research/WorldAssemblerM3/Linux24/REPORT.md)
records the evidence and owner-facing caveats.
## 9. Multiplayer model (listen-server first, dedicated-friendly)
> **Status: transport is DESIGN ONLY — nothing is networked in-tree yet** (no `Replicated`/`HasAuthority`/RPCs; a
+3 -6
View File
@@ -26,12 +26,9 @@ try to run anything.
- **Density sign: negative = solid, positive = air** (MC convention at the mesher).
`FVoxelModification::Strength` negative = carve. *The #1 source of confusion.*
- **Density functions take VOXEL coords, not cm.** The legacy plugin field uses 12.5 cm voxels;
the opt-in Core field uses 25 cm voxels and its own 32³-voxel storage tile. The legacy 32³ chunk
spans 4 m at 12.5 cm. Strate placement uses the separate world-level `StrateLayoutChunkSizeMeters`
setting (8 m by default), resolved once and shared by every generator. At 25 cm that layout unit is
32 Core voxels; at 20 cm it is 40. Never infer the layout unit from `CHUNK_SIZE` or the Core tile.
Conversions live in `VoxelTypes.h`, the director, and the Core bridge; do not mix scales in queries,
anchors, edits, or surface lookups.
the opt-in Core field uses 25 cm voxels and its own tile keys. One legacy 32³ chunk is 4 m.
Conversions live in `VoxelTypes.h` and the Core bridge; do not mix scales in queries, anchors, edits,
or surface lookups.
- **Determinism:** all randomness = hash of (coord, seed, strateIndex). No RNG state — same seed ⇒
same world. Player edits (diff layer) are the only non-deterministic overlay.
- **Core world invariants:** Core density keeps the same sign (negative solid, positive air), but Core
+9 -53
View File
@@ -29,9 +29,7 @@ A **density-field voxel terrain** plugin for Unreal Engine, built around undergr
### Core terminology
| Term | Meaning |
|------|---------|
| Legacy chunk | 32×32×32 voxels (`CHUNK_SIZE`). At the legacy 12.5 cm voxel size it spans 4 m; it is not the strate-layout unit or the Core tile. |
| Strate-layout chunk | World-level `StrateLayoutChunkSizeMeters`, default 8 m, shared by all generators and independent of voxel size. The director resolves it once and Core reads the resolved snapshot. At 25 cm it is 32 Core voxels; at 20 cm it is 40 Core voxels. |
| Core tile | Internal 32×32×32 Core voxel tile. Its metre size follows the Core voxel size and stays separate from the configurable layout chunk. |
| Chunk | 32×32×32 voxels (`CHUNK_SIZE`). Voxel = 12.5 cm (`VOXEL_SIZE`), so a chunk is 4 m. |
| Density | Scalar field. `< 0` solid, `> 0` air, `0` = surface (`IsoLevel`). |
| Strate | Vertical layer of the world, stacked downward. Has its own generator + params. |
| Generator type | Archetype per strate: `TunnelNetwork`, `FlatPlain`, `CrystalChamber`, `Maze`, `SurfaceWorld`, `VerticalShafts`, `FloatingIslands`, `Underwater`. See §8. |
@@ -80,12 +78,10 @@ what generator type, and is there a passage/elevator SDF near here?"
Paths relative to `Source/VoxelForge/`. `Public/` = headers, `Private/` = impl.
### 3.0 Human-scale generation contract (2026-10-01)
`VOXEL_SIZE` is **12.5 cm** for the legacy generator. Its 32³-voxel chunks span **4 m**. The
world-level strate-layout unit is a separate setting with an **8 m default**; a 16-chunk strate is
therefore **128 m**, and a 64-chunk strate is **512 m**. Core still stores work in 32³-voxel tiles;
at 25 cm those tiles happen to span 8 m, but they are not the layout unit. The gameplay capsule remains
**0.34 m radius / 1.76 m tall** (**2.72 / 14.08 legacy voxels**). Research-field dimensions are authored
in metres and converted at runtime. The live
`VOXEL_SIZE` is **12.5 cm**; 32³ voxels make each chunk **4 m**. The gameplay capsule remains
**0.34 m radius / 1.76 m tall** (**2.72 / 14.08 voxels**). The default strate envelope is
**16 chunks / 512 voxels / 64 m**; serialized owner strate assets that still say 8 chunks must be
changed to 16. Research-field dimensions are authored in metres and converted at runtime. The live
strate generator continues to read voxel-valued parameters from its assets, so those authored
dimensions become half as large in metres unless their asset values are doubled.
@@ -167,14 +163,13 @@ remains `0`, and lateral regions remain gated off.
| `../../Standalone/Core/src/CoreNamespacePreamble.h` | First include of every Core TU. Forces FP contraction off per compiler (Clang/MSVC/GCC pragmas; unknown compiler = `#error`) and defines `vfcore::fp_contract::selfTest`, which `World::compile` runs before building: a fused multiply-add (e.g. Clang `-ffp-contract=fast`) refuses world generation. The world depends on contraction (Linux2/Linux3 reports), so never remove either. |
| `../../VoxelForgeCore/Private/ModuleEntry/` | Unreal module entry and an isolated `CoreMinimal.h` shim for the actual engine header. |
| `../../Standalone/Core/include/VoxelForgeCore/VoxelForgeCore.h` | Standard-library-only public Core API. `VOXELFORGECORE_API` exports the API from the Unreal module and is empty for standalone builds. |
| `../../Standalone/Core/include/VoxelForgeCore/VoxelForgeCore.h` / `../../Standalone/Core/src/ResolvedLayoutInternal.h` | `ResolvedLayoutSnapshotV3`: physical layout-chunk width, versioned micrometre intervals, owned ceiling/content/bedrock bands, transition and dispatch provenance, recipe anchors, director-planned passages, canonical JSON/FNV identity, compatibility/strict validators, and negative-control audit. Built once from the director-resolved plan and consumed by bounds planning, Core dispatch, composition, and validation. §8.40–8.41. |
| `../../Standalone/Core/src/FloatingIslandsInternal.h` | Canonical standalone/Core floating-island planner, geometry-versioned field, manifest serializer, influence bounds, capsule-route checks, and thickness audit. |
| `Tools/VoxelForgeTest.ps1` | The single guarded test entry point. `-Scenario canonical|owner|probe|perf|tests|surface-fall|crossing|gate-stress|visual-edit|visual-lod|visual-gap-walk|visual-gap-inject|dig-motion|parity|horizon|horizon-render|determinism|region-eval|step2d|step2e|step2f|step2f-capture|step3-scale|step3-game`, optional `-Build`, `-Assets owner|default`, `-Cvars`, absolute `-Out`, `-Label`, `-HorizonLevel`, `-HorizonRenderDistanceChunks`, `-Step2fProfile=0..7`, `-Step2fCaptureView=inside|wall-closeup`, `-ParityExportSize=32|64|128`, `-ParityExportTile=x,y,z`, `-SharedDDC`, `-SampleDensityStacks`, `-StackSampleIntervalUs`, and `-RegionHashProbe -RegionWorkers N -RegionReferenceHash HASH`; stages the host/assets, isolates user/DDC/config state, serializes one Unreal launch at a time, enforces the 8 GiB/30-minute guards, waits for 6 GiB free RAM before launches, and emits compact `result.json`/`summary.txt` plus full logs. Parity can render its game leg with `-EnableRender` and compares the selected export region against the exact streamed tile hashes. `visual-gap-walk` records camera-frustum surface-point coverage at 6000 cm/s; `visual-gap-inject` proves an early component hide is detected; `dig-motion` logs per-frame vertical velocity, gate, support readiness, and movement mode. `-Cvars @{ 'voxel.TestGapAuditLegacyHandoff'=1 }` replays the old visibility handoff for A/B audit baselines. Horizon traces report desired/loaded tiles, resident stream geometry, worker seconds, steady wall time, and peak private memory; `horizon-render` captures the owner view; `step2f-capture` selects one of eight parameter sets, finds a positive-density camera point and aims at a sampled rock wall for an inside or wall-closeup view, then saves it under `Saved/Research/step2f/captures` (pass the persistent render DDC with `-SharedDDC`); `determinism` compares per-tile hashes across the default CRT path and `-voxel.CrtFma3=0`; `region-eval` compares the live path with the default-off editor chunk program on the 259³ lattice and five-seed probe set; `step2d` retains the earlier independent field; `step2e` retains its earlier benchmark; `step2f` compares frozen step 2e and the coherent field for all eight profiles on the same 259³ ring, applies geometry gates, and checks sound bounds, seams, and 1-vs-6-worker hashes. `-RegionHashProbe -RegionWorkers N -RegionReferenceHash HASH` checks a full-ring hash at another partition count. `-SampleDensityStacks` captures profiles, and `-StackSampleIntervalUs` sets the sampling interval.
| Step-3 scale and game validation | `step3-scale` measures the same 519³ and 259³ six-worker lattices at 12.5 cm. The cached medians are 7.347496 s and 1.169567 s respectively; determinism and brick sound-proof audits pass. `step3-game` routes in-game generation through the brick evaluator and records tile timings, spawn fill, moving frames, and profile-switch rebuilds. The visible D3D12 run measured tile generation p50/p95/max 3.326/31.045/169.867 ms, full-detail L0 fill 12.369 s for 2,765 tiles, and moving-frame p50/p95/p99/max 4.856/8.922/13.090/80.575 ms. Switching profiles rebuilt 5,815 loaded tiles. Both high-resolution screenshot requests were logged, but the harness found only one fresh PNG and it is a blank pale viewport; no lit comparison capture is accepted. Raw output: `Saved/TestHarness/step3_game_visible_final`; scale output: `Saved/Research/step3/scale/step3_scale_cacheperf_v1`. |
| `Public/VoxelForgeModule.h` / `Private/VoxelForgeModule.cpp` | `FVoxelForgeModule` boilerplate (Startup/Shutdown just log). |
| `Source/VoxelForgeEditor/VoxelForgeEditor.Build.cs` / `Private/VoxelForgeExploreCommandlet.*` | Editor/commandlet-only `-run=VoxelForgeExplore`; schema-v1 owner-asset export check and BuildHost Core actor tests. `-coreworldassembly=PATH` supplies a reviewed manifest transiently to `-coreworldtest=1`; it does not save a data asset. `FStandaloneCoreAdapterScheduler` runs Core work at 1/8/16 workers; `VerifyStandaloneCoreAdapter` checks hashes and walkability. Existing bounded render/`VF_` walk/OBJ orchestration and research options remain editor/commandlet-only and are not linked by Game/Shipping. |
| `Source/VoxelForge/Public/VoxelSettings.h` / `Private/VoxelSettings.cpp` | `UVoxelSettings` owns optional canonical world-assembly JSON and its Core digest. The editor file picker plus `ImportWorldAssemblyManifestJson` imports the reviewed manifest into the cooked settings asset and validates the recipe seed against the effective settings seed. |
| `Source/VoxelForge/Private/VoxelForgeCoreAdapter.cpp` | Validates the optional manifest against each resolved `SurfaceWorld` slot (unique strate index and exact top/bottom chunks), then exports canonical `resolved_layout` separately from `world_assembly` and its hash. The layout digest does not alter recipe hashes. Invalid plans fail Core initialization. |
| `Source/VoxelForge/Private/VoxelForgeCoreAdapter.cpp` | Validates the optional manifest against each resolved `SurfaceWorld` slot (unique strate index and exact top/bottom chunks), then places canonical `world_assembly` JSON and its hash in the Core snapshot. Invalid plans fail Core initialization. |
| `Source/VoxelForgeEditor/Private/VoxelForgeRegionEvalExperiment.*` | Six-worker lattice drivers for step 2c through step 2f. The original path still compares live `GetDensityAt` with the editor chunk program. Research modes assign contiguous batches dynamically so surface-heavy work balances across workers; steps 2e and 2f use 4³ proof bricks and stage each evaluated brick before copying contiguous X rows, while step 2d retains 8³. Each skip requires a macro Lipschitz bound plus the complete final-detail supremum; uncertain bricks retain every 12.5 cm detail sample. Timings split classification, point evaluation, and uniform fill; step 2f compares all profiles and hashes workers 1 and 6. |
| `Public/VoxelRedefinedDensityField.h` / `Private/VoxelRedefinedDensityField.cpp` | Two default-off `WITH_EDITOR` research fields, selected by `voxel.ResearchRedefinedDensityField` (step 2d) and `voxel.ResearchParameterizedCave` (steps 2e/2f). Step 2f retains a metre-scaled 2e baseline for its rejection audit. New profiles use strongly jittered, individually rotated elliptical rooms capped against nearest neighbors and curved cubic-Bezier passages with deterministic centerline and width variation along each edge. Room heights and feature rolls vary by cell; ledges, occasional pillars, stalactites/stalagmites, basin floors, and bounded hanging masses remain features. Point and brick detail sampling share independently rotated 96/48/24-sample bands and a smooth ridge response, preserving 12/6/3 m wavelengths at 12.5 cm per sample. The parameterized mesher evaluates the exact field through prepared 4³ bricks and the same sound skip proof in commandlet and editor-game meshing. In-editor and in-game profile changes invalidate and rebuild all loaded tiles. In an editor game with this field enabled, sealed-solid, out-of-layout, and outer-classifier verdicts are declined without changing their console switches. |
| `Private/Tests/VoxelForgeParameterizedGenerationTest.cpp` | Separate three-seed functional sweep for the step 2f parameterized field; passage landing air/floor brackets and arrival-to-exit walking routes are checked without changing the live-world tests. |
@@ -186,7 +181,7 @@ remains `0`, and lateral regions remain gated off.
| Symbol | Line | Notes |
|--------|------|-------|
| `CHUNK_SIZE` (32) | 211 | Chunk dimensions. 64³ would cut draw calls but makes streaming too bursty; fps is fixed render-side instead. |
| `VOXEL_SIZE` (12.5f cm) | 213 | Legacy generator scale; `CHUNK_SIZE` 32 spans 4 m here. Keep separate from the 8 m default layout chunk and 32³ Core tile. |
| `VOXEL_SIZE` (12.5f cm) | 213 | World scale; one 32³ chunk is 4 m. |
| `EVoxelFace` enum | 266 | 6 cube faces. |
| `WorldToChunkCoord` | 287 | World cm → chunk coord (handles negatives via floor). |
| `VoxelMath::IsFiniteFast` / `IsFinite` | 24 / 45 | Exact IEEE bit test (`voxel.FastIsFinite` A/B switch). |
@@ -213,16 +208,14 @@ all eight archetypes; there is no other path. See [Docs/archive/OPSTACK-PLAN.md]
| `FVoxelBoxHypotheses` + `FVoxelBoxSdfInterval` + `VF_ForceHypotheses` / `VF_FoldEffect` / `VF_FoldOp` | The fold that turns a stack into an `EVoxelTileClass`, carrying the SDF interval between independent writers and consumers. Unknown is biased toward `Mixed`; the mapping and soundness rule are written out in the header. |
### 3.2c Structural primitives — `Public/VoxelDensityPrimitives.h`
`VF_ApplyOriginSpine` · `VF_ApplyBoundarySeal` · `VF_ApplyUpperBoundarySeal` · `VF_ApplyPassageCarving` · `VF_ApplyXYEdgeSeal` —
`VF_ApplyOriginSpine` · `VF_ApplyBoundarySeal` · `VF_ApplyPassageCarving` · `VF_ApplyXYEdgeSeal` —
the four world invariants every archetype appends, with landing/floor geometry joined by the
manager passage post, **moved here 2026-07-27** so the generator and
the operator stack share ONE copy. The XY helper is a radial smooth ramp in actor-space and is a
true no-op when `WorldRadiusVoxels == 0`; `VF_XYEdgeSealForcedMarginOverBox` is the shared sound
proof for `ClassifyBox` and T1.d's global shell skip. `VoxelGenerator.cpp` keeps same-named
`static FORCEINLINE` forwarders for `ApplyBoundarySeal` and `ApplyOriginSpine`; the passage and
edge helpers are called directly. `VF_ApplyUpperBoundarySealValue` contains the common upper-band
math used by both one-sided and two-sided seals. **Convention: INTERNAL (positive = solid);
`VF_ApplyXYEdgeSealMC` is the output wrapper.**
edge helpers are called directly. **Convention: INTERNAL (positive = solid); `VF_ApplyXYEdgeSealMC` is the output wrapper.**
### 3.2d Operator stack — `Public/VoxelDensityOpStack.h` + `Private/VoxelDensityOpStack.cpp`
⚠️ **This IS the game's generation path.** `GetDensityAt` builds the stack in its per-chunk refetch
@@ -1144,43 +1137,6 @@ Implementation and evidence: [`Standalone/Research/WorldAssemblerM3/Linux9/REPOR
The base manifest field is authoritative for tile generation and exact queries. See ARCHITECTURE
§8.36 and [`Standalone/Research/WorldAssemblerM3/Linux13/REPORT.md`](Standalone/Research/WorldAssemblerM3/Linux13/REPORT.md).
### 3.23 Shared strate boundaries and FloatingIslands seal — World Assembler M3 Linux18
| Symbol | Canonical file | Role |
|---|---|---|
| `FStandaloneShapeWorld::FResolvedStratumBounds`, `MakeResolvedStratumBounds`, `GetResolvedStratumBounds` | `Standalone/Core/src/ShapeWorldInternal.h` | Resolves each strate's physical lower/upper range and seal width for layer ranges, far-field sample protection, and far-shell continuity. Native FloatingIslands uses its plan's owner/Core ratio; SurfaceWorld retains its `32` Core voxels per slot chunk. |
| `VF_ApplyUpperBoundarySeal` / `VF_ApplyUpperBoundarySealValue` | `Standalone/Source/VoxelForge/Public/VoxelDensityPrimitives.h` and `Source/VoxelForge/Public/VoxelDensityPrimitives.h` | Shared one-sided top seal used by version-3 native FloatingIslands; the two-sided seal reuses the same upper-band math. |
Geometry version 3 removes the FI lower all-XY seal while retaining its ceiling through the shared
upper-bound path. Versions 1 and 2 retain their serialized two-sided behavior. See ARCHITECTURE §8.37
and [`Standalone/Research/WorldAssemblerM3/Linux18/REPORT.md`](Standalone/Research/WorldAssemblerM3/Linux18/REPORT.md).
### 3.24 Resolved inter-strate passages — World Assembler M3 L23
| Symbol | Canonical file | Role |
|---|---|---|
| `PlanResolvedLayoutPassagesV1`, `ResolvedLayoutPassageV1::lowerMouthControlIndex` | `Standalone/Core/src/ResolvedLayoutInternal.h`, public record in `VoxelForgeCore.h` | Plans deterministic fixed-metre passages from adjacent director-resolved strata, binds route departure/arrival mouths, and records the derived split between the monotone descent and route-bound landing tail. |
| `FStandaloneShapeWorld::ApplyResolvedStrateComposition`, `ApplyResolvedStratePassageCarves` | `Standalone/Core/src/ShapeWorldInternal.h` | Applies boundary bands first, then opens the passage capsule and supported floor along the passage for every native generator. |
| `--audit-resolved-layout-passages` | `Standalone/Source/StreamBenchmarkPipeline.h` | Samples passage capsules, floor support, mouth ownership/radius, in-strate route bindings, and a blocked-passage negative control. |
The evaluator version is 9. See ARCHITECTURE §8.41 and
[`Standalone/Research/WorldAssemblerM3/Linux23/REPORT.md`](Standalone/Research/WorldAssemblerM3/Linux23/REPORT.md).
### 3.25 Per-strate natural passages and FloatingIslands anchor helix — World Assembler L24
| Symbol | Canonical file | Role |
|---|---|---|
| `FStratePassageConfig::Style`, `EVoxelPassageStyle` | `Source/VoxelForge/Public/VoxelStrateTypes.h` | Selects Straight, Worm, Spiral or Cascading per upper strate; Worm is the default. |
| `PlanResolvedLayoutPassagesV1` | `Standalone/Core/src/ResolvedLayoutInternal.h` | Applies the selected style in the shared planner; a configured FI Spiral follows the anchor root into the bedrock and smoothly transitions into the inter-strate route. |
| Anchor root recipe fields and `EvaluateIslandSDF` | `Standalone/Core/src/FloatingIslandsInternal.h` | Add the seed-stable ordinal-2 island/root without changing other island placements; geometry version 5. |
| `ApplyResolvedStratePassageCarves` | `Standalone/Core/src/ShapeWorldInternal.h` | Applies deterministic rough wall relief and the supported route profile to all native generator fields. |
| `--audit-resolved-layout-passages` naturalness checks | `Standalone/Source/StreamBenchmarkPipeline.h` | Checks 8 m maximum flat run, 0.20 m minimum wall relief, capsule/support/grade, mouths, routes and the blocked-passage control. |
| `--headlamp=on`, `--clip-plane=NX,NY,NZ,D` | `Standalone/Source/LinuxOffscreenCapture.cpp` | Adds camera-directed light or discards the plane's negative half-space for offscreen cutaways; neither affects Core output. |
The shared evaluator is version 10, the FI recipe geometry is version 5, and resolved-layout schema
V3 is unchanged. See ARCHITECTURE §8.42 and
[`Standalone/Research/WorldAssemblerM3/Linux24/REPORT.md`](Standalone/Research/WorldAssemblerM3/Linux24/REPORT.md).
## 4. The density pipeline (most-edited hot path)
### 4.1 `GetDensityWithParams` (TunnelNetwork) — VoxelGenerator.cpp:3749
@@ -32,38 +32,6 @@ namespace
using FCoreJsonWriter = TJsonWriter<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>;
constexpr double OwnerVoxelSizeCm = VOXEL_SIZE;
float StrateBoundarySealThickness(const UVoxelStrateDefinition& Definition)
{
switch(Definition.GeneratorType)
{
case ECaveGeneratorType::SurfaceWorld:return Definition.SurfaceParams.BoundarySealThickness;
case ECaveGeneratorType::FloatingIslands:return Definition.FloatingIslandParams.BoundarySealThickness;
case ECaveGeneratorType::Maze:return Definition.MazeParams.BoundarySealThickness;
case ECaveGeneratorType::VerticalShafts:return Definition.VerticalShaftParams.BoundarySealThickness;
case ECaveGeneratorType::TunnelNetwork:
case ECaveGeneratorType::FlatPlain:
case ECaveGeneratorType::CrystalChamber:
case ECaveGeneratorType::Underwater:return Definition.GenerationParams.BoundarySealThickness;
}
return Definition.GenerationParams.BoundarySealThickness;
}
float StrateBoundarySolidDensity(const UVoxelStrateDefinition& Definition)
{
switch(Definition.GeneratorType)
{
case ECaveGeneratorType::SurfaceWorld:return Definition.SurfaceParams.BaseDensity;
case ECaveGeneratorType::FloatingIslands:return Definition.FloatingIslandParams.BaseDensity;
case ECaveGeneratorType::Maze:return Definition.MazeParams.BaseDensity;
case ECaveGeneratorType::VerticalShafts:return Definition.VerticalShaftParams.BaseDensity;
case ECaveGeneratorType::TunnelNetwork:
case ECaveGeneratorType::FlatPlain:
case ECaveGeneratorType::CrystalChamber:
case ECaveGeneratorType::Underwater:return Definition.GenerationParams.BaseDensity;
}
return Definition.GenerationParams.BaseDensity;
}
std::int64_t WorldAssemblyFixed(double Voxels)
{
return static_cast<std::int64_t>(std::llround(
@@ -319,10 +287,8 @@ bool BuildSurfaceStratumPlan(const UVoxelStrateManager* StrateManager,
const FSurfaceGenerationParams Surface = StrateManager->GetSurfaceParamsForChunk(Chunk);
const FBiomeContext BiomeContext = StrateManager->GetBiomeContextForChunk(Chunk);
const UVoxelStrateDefinition* Definition = Slot.Definition;
const double LayoutChunkVoxels = static_cast<double>(Recipe.layoutChunkWidthSubvoxels)
/ WorldAssemblySubvoxelsPerVoxel;
const double BottomVoxel = static_cast<double>(Slot.BottomChunkZ) * LayoutChunkVoxels;
const double HeightVoxels = static_cast<double>(Slot.TopChunkZ - Slot.BottomChunkZ + 1) * LayoutChunkVoxels;
const double BottomVoxel = static_cast<double>(Slot.BottomChunkZ) * CHUNK_SIZE;
const double HeightVoxels = static_cast<double>(Slot.TopChunkZ - Slot.BottomChunkZ + 1) * CHUNK_SIZE;
const FBiomeMapParams& Map = BiomeContext.Map;
Recipe.seed = static_cast<std::uint32_t>(StrateManager->GetWorldSeed());
Recipe.biomeCellSizeSubvoxels = WorldAssemblyFixed(Map.CellSize);
@@ -456,7 +422,7 @@ bool BuildSurfaceStratumPlan(const UVoxelStrateManager* StrateManager,
Shelf.minimumSubvoxels = {WorldAssemblyFixed(MinX), WorldAssemblyFixed(MinY),
std::max(WorldAssemblyFixed(BottomVoxel), LowestGround - WorldAssemblyFixed(4.0))};
Shelf.maximumSubvoxels = {WorldAssemblyFixed(MaxX), WorldAssemblyFixed(MaxY),
std::min(WorldAssemblyFixed((Slot.TopChunkZ + 1) * LayoutChunkVoxels),
std::min(WorldAssemblyFixed((Slot.TopChunkZ + 1) * CHUNK_SIZE),
HighestGround + WorldAssemblyFixed(ShelfHeight + 4.0))};
Shelf.parametersSubvoxels = {WorldAssemblyFixed(DirX), WorldAssemblyFixed(DirY),
WorldAssemblyFixed(ShelfHeight), WorldAssemblyFixed(Reach)};
@@ -474,19 +440,17 @@ bool BuildSurfaceStratumPlan(const UVoxelStrateManager* StrateManager,
bool BuildFloatingIslandStratumPlan(const UVoxelStrateManager* StrateManager,
const FStrateSlot& Slot, VoxelForgeCore::WorldAssemblyManifest& Manifest,
double CoreVoxelSizeCm, std::int64_t LayoutChunkWidthSubvoxels, FString& OutError)
double CoreVoxelSizeCm, FString& OutError)
{
using namespace VoxelForgeCore;
const FIntVector Chunk(0, 0, Slot.TopChunkZ);
const FFloatingIslandParams Params = StrateManager->GetFloatingIslandParamsForChunk(Chunk);
const FStratePassageConfig& Passage = Slot.Definition->PassageConfig;
WorldAssemblyFloatingIslandPlanV1 IslandPlan;
IslandPlan.strateIndex = Slot.StrateIndex;
IslandPlan.topChunkZ = Slot.TopChunkZ;
IslandPlan.bottomChunkZ = Slot.BottomChunkZ;
auto& Recipe = IslandPlan.manifest.recipe;
Recipe.geometryVersion = 5;
Recipe.layoutChunkWidthSubvoxels = LayoutChunkWidthSubvoxels;
Recipe.geometryVersion = 2;
Recipe.seed = static_cast<std::uint32_t>(StrateManager->GetWorldSeed());
Recipe.ownerVoxelSizeMicrons = static_cast<std::uint32_t>(std::llround(OwnerVoxelSizeCm * 10000.0));
Recipe.coreVoxelSizeMicrons = static_cast<std::uint32_t>(std::llround(CoreVoxelSizeCm * 10000.0));
@@ -499,10 +463,12 @@ bool BuildFloatingIslandStratumPlan(const UVoxelStrateManager* StrateManager,
}
Recipe.ownerToCoreScaleNumerator = Recipe.ownerVoxelSizeMicrons / ScaleGcd;
Recipe.ownerToCoreScaleDenominator = Recipe.coreVoxelSizeMicrons / ScaleGcd;
Recipe.layoutMinimumZSubvoxels = static_cast<std::int64_t>(Slot.BottomChunkZ)
* LayoutChunkWidthSubvoxels;
Recipe.layoutMaximumZSubvoxels = static_cast<std::int64_t>(Slot.TopChunkZ + 1)
* LayoutChunkWidthSubvoxels;
const double CoreVoxelsPerOwnerChunk = static_cast<double>(CHUNK_SIZE)
* Recipe.ownerToCoreScaleNumerator / Recipe.ownerToCoreScaleDenominator;
Recipe.layoutMinimumZSubvoxels = WorldAssemblyFixed(
static_cast<double>(Slot.BottomChunkZ) * CoreVoxelsPerOwnerChunk);
Recipe.layoutMaximumZSubvoxels = WorldAssemblyFixed(
static_cast<double>(Slot.TopChunkZ + 1) * CoreVoxelsPerOwnerChunk);
Recipe.layoutCenterTopZSubvoxels = (Recipe.layoutMinimumZSubvoxels
+ Recipe.layoutMaximumZSubvoxels) / 2;
Recipe.islandDensityQ16 = WorldAssemblyQ16(FMath::Clamp(Params.IslandDensity, 0.0f, 1.0f));
@@ -517,28 +483,6 @@ bool BuildFloatingIslandStratumPlan(const UVoxelStrateManager* StrateManager,
Recipe.roughnessSubvoxels = WorldAssemblyFixed(Params.SurfaceRoughness * OwnerToCoreScale);
Recipe.blendRadiusSubvoxels = WorldAssemblyFixed(Params.SDFBlendRadius * OwnerToCoreScale);
Recipe.boundarySealSubvoxels = WorldAssemblyFixed(Params.BoundarySealThickness * OwnerToCoreScale);
const auto OwnerVoxelsToCoreQ=[&](double Value)
{
return static_cast<std::int64_t>(std::llround(Value*Recipe.ownerVoxelSizeMicrons
*WorldAssemblySubvoxelsPerVoxel/Recipe.coreVoxelSizeMicrons));
};
Recipe.anchorIslandOrdinal=Recipe.primaryIslandCount-1;
Recipe.anchorPlacementRadiusSubvoxels=OwnerVoxelsToCoreQ(Passage.DistanceMax);
const std::int64_t spiralRadius=OwnerVoxelsToCoreQ(Passage.SpiralRadius);
// Reserve at least a 1.5 m mid-bore through the anchor root.
constexpr double AnchorPassageMinimumBoreOwnerVoxels=12.0;
const std::int64_t mouthBore=std::max(OwnerVoxelsToCoreQ(Passage.MouthRadius),
OwnerVoxelsToCoreQ(12.0));
const std::int64_t bore=std::max(OwnerVoxelsToCoreQ(Passage.MidRadius),
OwnerVoxelsToCoreQ(AnchorPassageMinimumBoreOwnerVoxels));
const std::int64_t wallReserve=OwnerVoxelsToCoreQ(12.0);
Recipe.anchorMouthOffsetSubvoxels=spiralRadius+mouthBore+OwnerVoxelsToCoreQ(4.0);
const std::int64_t excursion=std::max(OwnerVoxelsToCoreQ(Passage.Wander),spiralRadius);
Recipe.anchorRootRadiusSubvoxels=excursion+bore+wallReserve;
Recipe.anchorIslandMinimumRadiusSubvoxels=std::max(Recipe.minimumRadiusSubvoxels,
Recipe.anchorMouthOffsetSubvoxels+mouthBore+OwnerVoxelsToCoreQ(4.0));
Recipe.anchorRootBottomZSubvoxels=Recipe.layoutMinimumZSubvoxels
+Recipe.boundarySealSubvoxels;
std::string PlanError;
const std::optional<FloatingIslandManifestV1> Planned = PlanFloatingIslandCluster(Recipe, PlanError);
if (!Planned)
@@ -814,12 +758,6 @@ bool AttachValidatedWorldAssembly(const UVoxelSettings* Settings,
const TSharedRef<FJsonObject>& Root,
FString& OutError)
{
const std::uint32_t LayoutChunkSizeMicrometres=StrateManager->GetStrateLayoutChunkSizeMicrometres();
const std::uint32_t CoreVoxelMicrometres=static_cast<std::uint32_t>(std::llround(CoreVoxelSizeCm*10000.0));
const std::int64_t LayoutChunkWidthSubvoxels=static_cast<std::int64_t>(std::llround(
static_cast<double>(LayoutChunkSizeMicrometres)*VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel
/std::max<std::uint32_t>(1,CoreVoxelMicrometres)));
StrateManager->SetHardTransitionFallbackForAssembly(true);
FString ManifestJson;
FString ManifestHash;
if (!Settings->GetWorldAssemblyManifestJson(ManifestJson, ManifestHash, OutError))
@@ -845,7 +783,6 @@ bool AttachValidatedWorldAssembly(const UVoxelSettings* Settings,
{
VoxelForgeCore::WorldAssemblyManifest Generated;
Generated.recipe.seed = static_cast<std::uint32_t>(StrateManager->GetWorldSeed());
Generated.recipe.layoutChunkWidthSubvoxels=LayoutChunkWidthSubvoxels;
int32 SurfaceSlotCount = 0;
int32 IslandSlotCount = 0;
for (const FStrateSlot& Slot : StrateManager->GetLayout())
@@ -878,7 +815,6 @@ bool AttachValidatedWorldAssembly(const UVoxelSettings* Settings,
{
VoxelForgeCore::WorldAssemblyRecipeV1 SlotRecipe;
SlotRecipe.seed = static_cast<std::uint32_t>(StrateManager->GetWorldSeed());
SlotRecipe.layoutChunkWidthSubvoxels=LayoutChunkWidthSubvoxels;
VoxelForgeCore::WorldAssemblyStratumPlanV1 Stratum;
if (!BuildSurfaceStratumPlan(StrateManager, Slot,
SlotRecipe, Stratum, OutError))
@@ -893,7 +829,7 @@ bool AttachValidatedWorldAssembly(const UVoxelSettings* Settings,
else if (Type == ECaveGeneratorType::FloatingIslands)
{
if (!BuildFloatingIslandStratumPlan(StrateManager, Slot, Generated,
CoreVoxelSizeCm, LayoutChunkWidthSubvoxels, OutError))
CoreVoxelSizeCm, OutError))
{
return false;
}
@@ -937,11 +873,7 @@ bool AttachValidatedWorldAssembly(const UVoxelSettings* Settings,
OutError = TEXT("floating-island override uses a different Core voxel size; regenerate the plan.");
return false;
}
if(Island.manifest.recipe.layoutChunkWidthSubvoxels!=LayoutChunkWidthSubvoxels)
{OutError=TEXT("floating-island override uses a different strate-layout chunk width; regenerate the plan.");return false;}
}
if(Manifest->recipe.layoutChunkWidthSubvoxels!=LayoutChunkWidthSubvoxels)
{OutError=TEXT("world assembly manifest uses a different strate-layout chunk width; regenerate the plan.");return false;}
int32 SurfaceSlotCount = 0;
int32 FloatingIslandSlotCount = 0;
@@ -1012,247 +944,6 @@ bool AttachValidatedWorldAssembly(const UVoxelSettings* Settings,
MatchedStrateIndices.Add(Plan.strateIndex);
}
// Keep the inspectable physical-layout export separate from the manifest identity: it is
// assembled from the same resolved slots/plans, but adding it must not salt evaluation hashes.
VoxelForgeCore::ResolvedLayoutSnapshotV3 Layout;
Layout.worldIdentity = std::string("owner-world/seed/")
+ std::to_string(StrateManager->GetWorldSeed());
Layout.ownerVoxelSizeMicrometres = static_cast<std::uint32_t>(std::llround(OwnerVoxelSizeCm * 10000.0));
Layout.coreVoxelSizeMicrometres = ExpectedCoreVoxelMicrons;
Layout.strateLayoutChunkSizeMicrometres=LayoutChunkSizeMicrometres;
Layout.strateLayoutChunkWidthSubvoxels=LayoutChunkWidthSubvoxels;
const auto generatorName = [](ECaveGeneratorType Type) -> const char*
{
switch (Type)
{
case ECaveGeneratorType::TunnelNetwork: return "TunnelNetwork";
case ECaveGeneratorType::FlatPlain: return "FlatPlain";
case ECaveGeneratorType::CrystalChamber: return "CrystalChamber";
case ECaveGeneratorType::Maze: return "Maze";
case ECaveGeneratorType::SurfaceWorld: return "SurfaceWorld";
case ECaveGeneratorType::VerticalShafts: return "VerticalShafts";
case ECaveGeneratorType::FloatingIslands: return "FloatingIslands";
case ECaveGeneratorType::Underwater: return "Underwater";
}
return "Unknown";
};
const auto transitionName = [](EVoxelStrateTransition Type) -> const char*
{
switch (Type)
{
case EVoxelStrateTransition::Gradient: return "Gradient";
case EVoxelStrateTransition::Hard: return "Hard";
case EVoxelStrateTransition::Interleaved: return "Interleaved";
}
return "Unknown";
};
const std::int64_t OwnerVoxelMicrons = Layout.ownerVoxelSizeMicrometres;
const auto FixedToMicrons = [ExpectedCoreVoxelMicrons](std::int64_t Fixed)
{
return static_cast<std::int64_t>(std::llround(static_cast<double>(Fixed)
* ExpectedCoreVoxelMicrons / VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel));
};
std::vector<VoxelForgeCore::ResolvedLayoutPassageConfigV1> PassageConfigs;
for (const FStrateSlot& Slot : StrateManager->GetLayout())
{
if (Slot.Definition == nullptr) continue;
const FStratePassageConfig& AuthoredPassage = Slot.Definition->PassageConfig;
const auto OwnerVoxelsToCoreQ = [OwnerVoxelMicrons, ExpectedCoreVoxelMicrons](double Value)
{
return static_cast<std::int64_t>(std::llround(Value * OwnerVoxelMicrons
* VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel / ExpectedCoreVoxelMicrons));
};
VoxelForgeCore::ResolvedLayoutPassageConfigV1 PassageConfig;
PassageConfig.upperStrateIndex = Slot.StrateIndex;
PassageConfig.connections = AuthoredPassage.Connections;
PassageConfig.style = static_cast<std::uint32_t>(AuthoredPassage.Style);
PassageConfig.mouthRadiusSubvoxels = std::max(OwnerVoxelsToCoreQ(AuthoredPassage.MouthRadius),
OwnerVoxelsToCoreQ(12.0));
PassageConfig.midRadiusSubvoxels = std::max(OwnerVoxelsToCoreQ(AuthoredPassage.MidRadius),
OwnerVoxelsToCoreQ(12.0));
PassageConfig.reachMinimumSubvoxels = OwnerVoxelsToCoreQ(AuthoredPassage.ReachMin);
PassageConfig.reachMaximumSubvoxels = OwnerVoxelsToCoreQ(AuthoredPassage.ReachMax);
PassageConfig.distanceMinimumSubvoxels = OwnerVoxelsToCoreQ(AuthoredPassage.DistanceMin);
PassageConfig.distanceMaximumSubvoxels = OwnerVoxelsToCoreQ(AuthoredPassage.DistanceMax);
PassageConfig.wanderSubvoxels = OwnerVoxelsToCoreQ(AuthoredPassage.Wander);
PassageConfig.segments = static_cast<std::uint32_t>(FMath::Clamp(AuthoredPassage.Segments,1,48));
PassageConfig.verticalWobbleSubvoxels = OwnerVoxelsToCoreQ(AuthoredPassage.VerticalWobble);
PassageConfig.spiralRadiusSubvoxels = OwnerVoxelsToCoreQ(AuthoredPassage.SpiralRadius);
PassageConfig.spiralTurnsQ16 = static_cast<std::int64_t>(std::llround(
static_cast<double>(AuthoredPassage.SpiralTurns)*65536.0));
PassageConfig.cascadeSteps = static_cast<std::uint32_t>(FMath::Clamp(AuthoredPassage.CascadeSteps,1,16));
PassageConfig.cascadeLedgeSubvoxels = OwnerVoxelsToCoreQ(AuthoredPassage.CascadeLedge);
PassageConfigs.push_back(PassageConfig);
const ECaveGeneratorType Type = StrateManager->GetGeneratorTypeForChunk(
FIntVector(0, 0, Slot.TopChunkZ));
VoxelForgeCore::ResolvedLayoutStratumV2 Item;
Item.strateIndex = Slot.StrateIndex;
Item.generatorKind = generatorName(Type);
Item.stableId = Layout.worldIdentity + "/strate/" + std::to_string(Slot.StrateIndex)
+ "/generator/" + generatorName(Type);
Item.recipeId = Type == ECaveGeneratorType::SurfaceWorld ? "SurfaceWorld.Heightfield2D"
: Type == ECaveGeneratorType::FloatingIslands ? "FloatingIslands.ClusterField"
: std::string("legacy.") + generatorName(Type);
Item.recipeVersion = Type == ECaveGeneratorType::SurfaceWorld ? Manifest->recipe.schemaVersion : 0;
Item.voxelSizeMicrometres = ExpectedCoreVoxelMicrons;
Item.interiorBottomMicrometres = static_cast<std::int64_t>(Slot.BottomChunkZ)
* LayoutChunkSizeMicrometres;
Item.interiorTopMicrometres = static_cast<std::int64_t>(Slot.TopChunkZ + 1)
* LayoutChunkSizeMicrometres;
Item.managerChunkWidthMicrometres = LayoutChunkSizeMicrometres;
Item.dispatchChunkWidthMicrometres = LayoutChunkSizeMicrometres;
Item.transitionMode = transitionName(Slot.Definition->TransitionType);
Item.transitionBlendChunks = Slot.Definition->TransitionBlendChunks;
Item.transitionWidthMicrometres = static_cast<std::int64_t>(Item.transitionBlendChunks)
* Item.managerChunkWidthMicrometres;
Item.transitionWarpAmplitudeMicrometres = Item.transitionMode == "Interleaved"
? 2 * Item.managerChunkWidthMicrometres : 0;
Item.transitionInterpenetrationMicrometres = 0;
Item.transitionHonouredInCore = Slot.Definition->TransitionType == EVoxelStrateTransition::Hard;
Item.transitionFallsBackToHard = Slot.Definition->TransitionType != EVoxelStrateTransition::Hard;
Item.transitionDispatchPath = Item.transitionFallsBackToHard
? "declared Gradient/Interleaved recorded; Core uses an explicit Hard transition fallback with zero interpenetration"
: "declared Hard transition is applied at this interface";
Item.managerLookup = "UVoxelStrateManager::GetGeneratorTypeForChunk; transition is controlled by upper strate";
if (Type == ECaveGeneratorType::SurfaceWorld)
{
Item.boundDispatchPath = "BuildSurfaceStratumPlan uses resolved layout chunk width from ResolvedLayoutSnapshotV3";
Item.queryDispatchPath = "NativeSurfaceDensityAt selects floor(CoreZ / resolved layout chunk width) from ResolvedLayoutSnapshotV3";
const auto Plan = std::find_if(Manifest->plan.strates.begin(), Manifest->plan.strates.end(),
[&Slot](const auto& Entry) { return Entry.strateIndex == Slot.StrateIndex; });
if (Plan != Manifest->plan.strates.end())
{
for (const auto& Profile : Manifest->recipe.biomes)
if (Profile.hasCapProfile)
{
VoxelForgeCore::ResolvedLayoutAnchorV2 Anchor;
Anchor.kind = "cap_profile";
Anchor.stableId = "biome/" + std::to_string(Profile.stableId);
Anchor.units = "1/256 Core voxel";
Anchor.values = { Profile.capHeightSubvoxels, Profile.capUndulationSubvoxels,
Profile.capWavelengthSubvoxels, Profile.capDetailAmplitudeSubvoxels,
Profile.capRidgeAmplitudeSubvoxels };
Item.anchors.push_back(std::move(Anchor));
}
for (std::size_t RouteIndex = 0; RouteIndex < Plan->route.size(); ++RouteIndex)
{
const auto& Point = Plan->route[RouteIndex];
VoxelForgeCore::ResolvedLayoutAnchorV2 Anchor;
Anchor.kind = "route_point"; Anchor.stableId = "route/" + std::to_string(RouteIndex);
Anchor.units = "1/256 Core voxel";
Anchor.values = { Point.positionSubvoxels[0], Point.positionSubvoxels[1],
Point.positionSubvoxels[2], Point.radiusSubvoxels };
Item.anchors.push_back(std::move(Anchor));
}
}
}
else if (Type == ECaveGeneratorType::FloatingIslands)
{
Item.boundDispatchPath = "BuildFloatingIslandStratumPlan uses resolved layout chunk width from ResolvedLayoutSnapshotV3";
Item.queryDispatchPath = "NativeFloatingIslandDensityAt selects floor(CoreZ / resolved layout chunk width) from ResolvedLayoutSnapshotV3";
const auto Plan = std::find_if(Manifest->floatingIslands.begin(), Manifest->floatingIslands.end(),
[&Slot](const auto& Entry) { return Entry.strateIndex == Slot.StrateIndex; });
std::int64_t SealMicrometres = 0;
if (Plan != Manifest->floatingIslands.end())
{
Item.interiorBottomMicrometres = FixedToMicrons(Plan->manifest.recipe.layoutMinimumZSubvoxels);
Item.interiorTopMicrometres = FixedToMicrons(Plan->manifest.recipe.layoutMaximumZSubvoxels);
Item.recipeVersion = Plan->manifest.recipe.geometryVersion;
for (std::size_t IslandIndex = 0; IslandIndex < Plan->manifest.plan.islands.size(); ++IslandIndex)
{
const auto& Island = Plan->manifest.plan.islands[IslandIndex];
VoxelForgeCore::ResolvedLayoutAnchorV2 Anchor;
Anchor.kind = "island_anchor"; Anchor.stableId = "island/" + std::to_string(IslandIndex);
Anchor.units = "1/256 Core voxel";
Anchor.values = { Island.centerSubvoxels[0], Island.centerSubvoxels[1],
Island.centerSubvoxels[2], Island.radiusSubvoxels, Island.topHalfSubvoxels };
Item.anchors.push_back(std::move(Anchor));
if(IslandIndex==Plan->manifest.recipe.anchorIslandOrdinal
&&Plan->manifest.recipe.geometryVersion>=5)
{
VoxelForgeCore::ResolvedLayoutAnchorV2 PassageAnchor;
PassageAnchor.kind="passage_anchor";
PassageAnchor.stableId="passage-anchor/island/"+std::to_string(IslandIndex);
PassageAnchor.units="1/256 Core voxel";
PassageAnchor.values={Island.centerSubvoxels[0],Island.centerSubvoxels[1],
Plan->manifest.recipe.anchorRootRadiusSubvoxels,
Plan->manifest.recipe.anchorMouthOffsetSubvoxels,
Plan->manifest.recipe.anchorPlacementRadiusSubvoxels,
Plan->manifest.recipe.anchorRootBottomZSubvoxels,
Island.radiusSubvoxels};
Item.anchors.push_back(std::move(PassageAnchor));
}
}
for (std::size_t RouteIndex = 0; RouteIndex < Plan->manifest.plan.route.size(); ++RouteIndex)
{
const auto& Point = Plan->manifest.plan.route[RouteIndex];
VoxelForgeCore::ResolvedLayoutAnchorV2 Anchor;
Anchor.kind = "route_point"; Anchor.stableId = "route/" + std::to_string(RouteIndex);
Anchor.units = "1/256 Core voxel";
Anchor.values = { Point.positionSubvoxels[0], Point.positionSubvoxels[1],
Point.positionSubvoxels[2], Point.radiusSubvoxels };
Item.anchors.push_back(std::move(Anchor));
}
}
}
else
{
Item.boundDispatchPath = "resolved manager slot scaled by ResolvedLayoutSnapshotV3 chunk width";
Item.queryDispatchPath = "legacy Core route selects manager chunk by floor(CoreZ / resolved layout chunk width)";
}
const std::int64_t SealMicrometres=static_cast<std::int64_t>(std::llround(
std::max(0.0f,StrateBoundarySealThickness(*Slot.Definition))*OwnerVoxelMicrons));
if(SealMicrometres<=0)
{OutError=FString::Printf(TEXT("Strate %d has no positive BoundarySealThickness for shared ceiling and bedrock bands."),Slot.StrateIndex);return false;}
const std::int64_t SolidDensityQ16=std::max<std::int64_t>(1,WorldAssemblyQ16(
std::max(0.05f,StrateBoundarySolidDensity(*Slot.Definition))));
Item.ceiling={"ceiling",Item.interiorTopMicrometres-SealMicrometres,
Item.interiorTopMicrometres,true,true,false,"solid ceiling from strate BoundarySealThickness; breakable by default",
"interior-facing lower surface","shared resolved-layout density band",SolidDensityQ16};
Item.bedrock={"bedrock",Item.interiorBottomMicrometres,
Item.interiorBottomMicrometres+SealMicrometres,true,true,false,
"solid bedrock floor from strate BoundarySealThickness; breakable by default",
"interior-facing upper surface","shared resolved-layout density band",SolidDensityQ16};
Item.content = { "content", Item.interiorBottomMicrometres,
Item.interiorTopMicrometres, true, true, false, "resolved generator interior",
"none", "none" };
Item.content.bottomMicrometres+=SealMicrometres;
Item.content.topMicrometres-=SealMicrometres;
Layout.strates.push_back(std::move(Item));
}
std::string PassagePlanError;
if (!VoxelForgeCore::PlanResolvedLayoutPassagesV1(Layout,
StrateManager->GetWorldSeed(), PassageConfigs, PassagePlanError))
{
OutError = FString::Printf(TEXT("Resolved inter-strate passage planning failed: %s"),
UTF8_TO_TCHAR(PassagePlanError.c_str()));
return false;
}
std::string LayoutError;
if (!Layout.finalize(LayoutError))
{
OutError = FString::Printf(TEXT("Core resolved-layout export failed: %s"), UTF8_TO_TCHAR(LayoutError.c_str()));
return false;
}
const std::string LayoutJson = Layout.ToJson();
Root->SetStringField(TEXT("resolved_layout_json"),UTF8_TO_TCHAR(LayoutJson.c_str()));
const auto SurfaceSpawnPlan=std::find_if(Manifest->plan.strates.begin(),Manifest->plan.strates.end(),
[](const auto& Plan){return !Plan.route.empty();});
if(SurfaceSpawnPlan!=Manifest->plan.strates.end())
{
const auto& Spawn=SurfaceSpawnPlan->route.front();
TSharedRef<FJsonObject> ViewerStart=MakeShared<FJsonObject>();
ViewerStart->SetBoolField(TEXT("found_open_space"),true);
ViewerStart->SetNumberField(TEXT("x"),static_cast<double>(Spawn.positionSubvoxels[0])
/VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel);
ViewerStart->SetNumberField(TEXT("y"),static_cast<double>(Spawn.positionSubvoxels[1])
/VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel);
ViewerStart->SetNumberField(TEXT("z"),static_cast<double>(Spawn.positionSubvoxels[2])
/VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel);
Root->SetObjectField(TEXT("viewer_start"),ViewerStart);
}
const std::string CanonicalJson = Manifest->ToJson();
if (CanonicalJson.empty())
{
@@ -1322,8 +1013,6 @@ bool VoxelForgeCoreAdapter::SerializeResolvedWorld(
// Override only the temporary schema copy. Clipmap tuning on the owner's asset is preserved.
SettingsValue->AsObject()->SetNumberField(TEXT("ClipRadius"), CoreClipRadius);
SettingsValue->AsObject()->SetNumberField(TEXT("MaxClipLevel"), CoreMaxClipLevel);
SettingsValue->AsObject()->SetNumberField(TEXT("StrateLayoutChunkSizeMeters"),
Settings->StrateLayoutChunkSizeMeters);
TSharedRef<FJsonObject> Root = MakeShared<FJsonObject>();
Root->SetNumberField(TEXT("schema_version"), 1);
@@ -1343,8 +1032,6 @@ bool VoxelForgeCoreAdapter::SerializeResolvedWorld(
Root->SetNumberField(TEXT("edge_seal_thickness"), Settings->EdgeSealThickness);
Root->SetNumberField(TEXT("total_strates"), StrateManager->GetNumStrates());
Root->SetNumberField(TEXT("inter_strate_gap_chunks"), Settings->InterStrateGapChunks);
Root->SetNumberField(TEXT("strate_layout_chunk_size_um"),
std::llround(Settings->StrateLayoutChunkSizeMeters*1000000.0));
Root->SetNumberField(TEXT("clip_radius"), CoreClipRadius);
Root->SetNumberField(TEXT("max_clip_level"), CoreMaxClipLevel);
Root->SetNumberField(TEXT("full_res_clip_levels"), Settings->FullResClipLevels);
@@ -1412,15 +1099,12 @@ bool VoxelForgeCoreAdapter::SerializeResolvedWorld(
return false;
}
Root->SetArrayField(TEXT("density_samples"), {});
if(!Root->HasField(TEXT("viewer_start")))
{
TSharedRef<FJsonObject> ViewerStart = MakeShared<FJsonObject>();
ViewerStart->SetBoolField(TEXT("found_open_space"), false);
ViewerStart->SetNumberField(TEXT("x"), 0.0);
ViewerStart->SetNumberField(TEXT("y"), 0.0);
ViewerStart->SetNumberField(TEXT("z"), 0.0);
Root->SetObjectField(TEXT("viewer_start"), ViewerStart);
}
TSharedRef<FJsonObject> ViewerStart = MakeShared<FJsonObject>();
ViewerStart->SetBoolField(TEXT("found_open_space"), false);
ViewerStart->SetNumberField(TEXT("x"), 0.0);
ViewerStart->SetNumberField(TEXT("y"), 0.0);
ViewerStart->SetNumberField(TEXT("z"), 0.0);
Root->SetObjectField(TEXT("viewer_start"), ViewerStart);
FString WriterBuffer;
TSharedRef<FCoreJsonWriter> Writer = TJsonWriterFactory<TCHAR,
@@ -321,7 +321,7 @@ namespace
const FVector ChunkCenter(
(ChunkCoord.X + 0.5f) * (float)CHUNK_SIZE,
(ChunkCoord.Y + 0.5f) * (float)CHUNK_SIZE,
(ChunkCoord.Z + 0.5f) * Manager->GetStrateLayoutChunkWidthVoxels());
(ChunkCoord.Z + 0.5f) * (float)CHUNK_SIZE);
const float ChunkRadius = (float)CHUNK_SIZE * 0.8660254f + 3.0f;
const TArray<FVoxelPassage>& Passages = Manager->GetPassages();
Cache.FloorProjections.SetNum(Passages.Num());
@@ -1103,7 +1103,7 @@ static bool VF_FindWalkableTunnelAir(
const FIntVector ChunkCoord(
FMath::FloorToInt(Position.X / (float)CHUNK_SIZE),
FMath::FloorToInt(Position.Y / (float)CHUNK_SIZE),
FMath::FloorToInt(Position.Z / Manager->GetStrateLayoutChunkWidthVoxels()));
FMath::FloorToInt(Position.Z / (float)CHUNK_SIZE));
const TArray<int32>& Nearby = VF_GetNearbyPassages(Manager, ChunkCoord);
const TArray<FVoxelPassage>& Passages = Manager->GetPassages();
const FVoxelPassage* PassageData = Passages.GetData();
@@ -1138,7 +1138,7 @@ static bool VF_IsAnyPassageFloorAt(
const FIntVector ChunkCoord(
FMath::FloorToInt(Position.X / (float)CHUNK_SIZE),
FMath::FloorToInt(Position.Y / (float)CHUNK_SIZE),
FMath::FloorToInt(Position.Z / Manager->GetStrateLayoutChunkWidthVoxels()));
FMath::FloorToInt(Position.Z / (float)CHUNK_SIZE));
const TArray<int32>& Nearby = VF_GetNearbyPassages(Manager, ChunkCoord);
const TArray<FVoxelPassage>& Passages = Manager->GetPassages();
const FVoxelPassage* PassageData = Passages.GetData();
@@ -1169,17 +1169,6 @@ bool UVoxelStrateManager::Initialize(UVoxelSettings* Settings, int32 WorldSeed)
UE_LOG(LogTemp, Error, TEXT("[StrateManager] No settings provided!"));
return false;
}
if (!FMath::IsFinite(Settings->StrateLayoutChunkSizeMeters)
|| Settings->StrateLayoutChunkSizeMeters < 0.25f
|| Settings->StrateLayoutChunkSizeMeters > 64.0f)
{
UE_LOG(LogTemp, Error, TEXT("[StrateManager] StrateLayoutChunkSizeMeters must be in [0.25, 64] m."));
return false;
}
StrateLayoutChunkSizeMicrometres = static_cast<uint32>(std::llround(
static_cast<double>(Settings->StrateLayoutChunkSizeMeters) * 1000000.0));
StrateLayoutChunkWidthVoxels = static_cast<float>(
static_cast<double>(StrateLayoutChunkSizeMicrometres) / (10000.0 * VOXEL_SIZE));
FVoxelSeasonManifest SeasonManifest;
bool bUseSeason = false;
@@ -1353,11 +1342,10 @@ bool UVoxelStrateManager::Initialize(UVoxelSettings* Settings, int32 WorldSeed)
Slot.Definition->FloatingIslandParams = SeasonStrate.Params.FloatingIslandParams;
Slot.HeightInChunks = SeasonStrate.HeightInChunks;
const int32 LayoutChunkVoxels=FMath::RoundToInt(StrateLayoutChunkWidthVoxels);
Slot.TopChunkZ = SeasonStrate.TopWorldZ / LayoutChunkVoxels - 1;
Slot.BottomChunkZ = SeasonStrate.BottomWorldZ / LayoutChunkVoxels;
if (SeasonStrate.TopWorldZ % LayoutChunkVoxels != 0
|| SeasonStrate.BottomWorldZ % LayoutChunkVoxels != 0
Slot.TopChunkZ = SeasonStrate.TopWorldZ / CHUNK_SIZE - 1;
Slot.BottomChunkZ = SeasonStrate.BottomWorldZ / CHUNK_SIZE;
if (SeasonStrate.TopWorldZ % CHUNK_SIZE != 0
|| SeasonStrate.BottomWorldZ % CHUNK_SIZE != 0
|| Slot.TopChunkZ != CurrentTopZ
|| Slot.BottomChunkZ != CurrentTopZ - (Slot.HeightInChunks - 1))
{
@@ -1537,8 +1525,8 @@ bool UVoxelStrateManager::SetComposerOverrideForStrate(
}
VF_SetComposerRuntimeBounds(
Override->Params,
(float)(TargetSlot->TopChunkZ + 1) * StrateLayoutChunkWidthVoxels,
(float)TargetSlot->BottomChunkZ * StrateLayoutChunkWidthVoxels);
(float)(TargetSlot->TopChunkZ + 1) * CHUNK_SIZE,
(float)TargetSlot->BottomChunkZ * CHUNK_SIZE);
Override->bUseRecipe = bUseRecipe;
if (Recipe != nullptr)
{
@@ -1557,8 +1545,8 @@ bool UVoxelStrateManager::SetComposerOverrideForStrate(
Override->bUseRegions = true;
Override->Regions = *InRegions;
VF_RekeyStrateRegionManifest(Override->Regions, CandidateSeed, StrateIndex);
Override->Regions.StrateTopWorldZ = (float)(TargetSlot->TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
Override->Regions.StrateBottomWorldZ = (float)TargetSlot->BottomChunkZ * StrateLayoutChunkWidthVoxels;
Override->Regions.StrateTopWorldZ = (float)(TargetSlot->TopChunkZ + 1) * CHUNK_SIZE;
Override->Regions.StrateBottomWorldZ = (float)TargetSlot->BottomChunkZ * CHUNK_SIZE;
VF_SetStrateArchetypeRuntimeBounds(Override->Params,
Override->Regions.StrateTopWorldZ,
Override->Regions.StrateBottomWorldZ);
@@ -1808,11 +1796,11 @@ void UVoxelStrateManager::GeneratePassages()
const FStratePassageConfig& Cfg = UpperDef->PassageConfig;
// Upper strate floor and lower strate ceiling (differ when there's a bedrock gap).
const float UpperTopZ = (float)(Upper.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
const float UpperBottomZ = (float)(Upper.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
const float LowerTopZ = (float)(Lower.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
const float UpperMax = (float)Upper.HeightInChunks * StrateLayoutChunkWidthVoxels * 0.9f;
const float LowerMax = (float)Lower.HeightInChunks * StrateLayoutChunkWidthVoxels * 0.9f;
const float UpperTopZ = (float)(Upper.TopChunkZ + 1) * CHUNK_SIZE;
const float UpperBottomZ = (float)(Upper.BottomChunkZ) * CHUNK_SIZE;
const float LowerTopZ = (float)(Lower.TopChunkZ + 1) * CHUNK_SIZE;
const float UpperMax = (float)Upper.HeightInChunks * CHUNK_SIZE * 0.9f;
const float LowerMax = (float)Lower.HeightInChunks * CHUNK_SIZE * 0.9f;
const float DistLo = FMath::Min(Cfg.DistanceMin, Cfg.DistanceMax);
const float DistHi = FMath::Max(Cfg.DistanceMin, Cfg.DistanceMax);
@@ -1942,7 +1930,7 @@ void UVoxelStrateManager::GeneratePassages()
LowerDef->FloatingIslandParams,
LowerQuerySeed,
LowerTopZ,
(float)(Lower.BottomChunkZ) * StrateLayoutChunkWidthVoxels,
(float)(Lower.BottomChunkZ) * CHUNK_SIZE,
PX,
PY,
MaxLateralSnap,
@@ -2002,7 +1990,7 @@ void UVoxelStrateManager::GeneratePassages()
if (bAimedLowerAtPlayerFitPoint)
{
const float LowerSealThickness = BoundarySealThicknessFor(*LowerDef);
const float LowerBottomZ = (float)(Lower.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
const float LowerBottomZ = (float)(Lower.BottomChunkZ) * CHUNK_SIZE;
const float InnerBottomZ = LowerBottomZ + LowerSealThickness;
const float InnerTopZ = LowerTopZ - LowerSealThickness;
if (VoxelMath::IsFinite(SuggestedLowerPoint.X)
@@ -2170,7 +2158,7 @@ void UVoxelStrateManager::GeneratePassages()
Cfg.MouthRadius,
LowerDoorDirection,
LowerTopZ,
(float)(Lower.BottomChunkZ) * StrateLayoutChunkWidthVoxels,
(float)(Lower.BottomChunkZ) * CHUNK_SIZE,
LowerDef ? BoundarySealThicknessFor(*LowerDef) : 0.0f,
bAimedLowerAtPlayerFitPoint);
Passage.UpperPoint = Passage.UpperLanding.StandingPoint;
@@ -2595,8 +2583,8 @@ void UVoxelStrateManager::GeneratePassages()
if (bOpenSurfaceEntry && OriginSpineRadius > 0.0f && StrateLayout.Num() > 0)
{
const FStrateSlot& Top = StrateLayout[0];
const float TopZ = (float)(Top.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
const float BottomZ = (float)Top.BottomChunkZ * StrateLayoutChunkWidthVoxels;
const float TopZ = (float)(Top.TopChunkZ + 1) * CHUNK_SIZE;
const float BottomZ = (float)Top.BottomChunkZ * CHUNK_SIZE;
const float TopSeal = Top.Definition
? BoundarySealThicknessFor(*Top.Definition) : 0.0f;
const VoxelPassageGeometry::FOriginLandingGeometry OriginLanding =
@@ -2619,7 +2607,7 @@ void UVoxelStrateManager::GeneratePassages()
// the top seal into the finite landing room; lower strate seals remain untouched.
Entry.Radius = FMath::Max(OriginSpineRadius,
VoxelPassageGeometry::MetersToVoxels(0.25f));
Entry.UpperPoint = FVector(0.0f, 0.0f, TopZ + StrateLayoutChunkWidthVoxels);
Entry.UpperPoint = FVector(0.0f, 0.0f, TopZ + CHUNK_SIZE);
// The capsule's lower tangent meets the room ceiling; it never bores through the
// room's floor or creates an origin column in strate 0.
Entry.LowerPoint = FVector(
@@ -2683,7 +2671,7 @@ float UVoxelStrateManager::EvaluateModifierSDF(float WorldX, float WorldY, float
const FIntVector ChunkCoord(
FMath::FloorToInt(WorldX / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldY / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldZ / StrateLayoutChunkWidthVoxels));
FMath::FloorToInt(WorldZ / (float)CHUNK_SIZE));
// The shortlist is rebuilt once for a (manager, version, chunk) and is shared by the tube,
// landing, and floor paths. No source-fit stencil or topology search is allowed below it.
@@ -2829,7 +2817,7 @@ void UVoxelStrateManager::ApplyPassageModifier(
const FIntVector ChunkCoord(
FMath::FloorToInt(WorldX / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldY / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldZ / StrateLayoutChunkWidthVoxels));
FMath::FloorToInt(WorldZ / (float)CHUNK_SIZE));
const TArray<int32>& Nearby = VF_GetNearbyPassages(this, ChunkCoord);
const FVoxelPassage* PassageData = Passages.GetData();
const FVector Position(WorldX, WorldY, WorldZ);
@@ -2922,7 +2910,7 @@ void UVoxelStrateManager::ApplyPassageLandingAir(
const FIntVector ChunkCoord(
FMath::FloorToInt(WorldX / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldY / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldZ / StrateLayoutChunkWidthVoxels));
FMath::FloorToInt(WorldZ / (float)CHUNK_SIZE));
const TArray<int32>& Nearby = VF_GetNearbyPassages(this, ChunkCoord);
if (Nearby.Num() == 0) return;
@@ -3033,7 +3021,7 @@ void UVoxelStrateManager::ApplyPassageLandingFloorMC(
const FIntVector ChunkCoord(
FMath::FloorToInt(WorldX / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldY / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldZ / StrateLayoutChunkWidthVoxels));
FMath::FloorToInt(WorldZ / (float)CHUNK_SIZE));
const TArray<int32>& Nearby = VF_GetNearbyPassages(this, ChunkCoord);
const FVoxelPassage* PassageData = Passages.GetData();
const FVector Position(WorldX, WorldY, WorldZ);
@@ -3129,7 +3117,7 @@ void UVoxelStrateManager::ApplyPassageStructuralPostsMC(
const FIntVector ChunkCoord(
FMath::FloorToInt(WorldX / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldY / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldZ / StrateLayoutChunkWidthVoxels));
FMath::FloorToInt(WorldZ / (float)CHUNK_SIZE));
const TArray<int32>& Nearby = VF_GetNearbyPassages(this, ChunkCoord);
if (Nearby.Num() == 0) return;
@@ -3256,7 +3244,7 @@ void UVoxelStrateManager::ApplyPassageNativeFloorMC(
const FIntVector ChunkCoord(
FMath::FloorToInt(WorldX / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldY / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldZ / StrateLayoutChunkWidthVoxels));
FMath::FloorToInt(WorldZ / (float)CHUNK_SIZE));
const TArray<int32>& Nearby = VF_GetNearbyPassages(this, ChunkCoord);
if (Nearby.Num() == 0
|| VoxelPassageGeometry::VerticalShaftConnectorAirMarker())
@@ -3447,7 +3435,7 @@ void UVoxelStrateManager::ApplyPassageLandingRoomFloorMC(
const FIntVector ChunkCoord(
FMath::FloorToInt(WorldX / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldY / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldZ / StrateLayoutChunkWidthVoxels));
FMath::FloorToInt(WorldZ / (float)CHUNK_SIZE));
const TArray<int32>& Nearby = VF_GetNearbyPassages(this, ChunkCoord);
const FVoxelPassage* PassageData = Passages.GetData();
const FVector Position(WorldX, WorldY, WorldZ);
@@ -5921,8 +5909,8 @@ bool UVoxelStrateManager::AnyLandingFloorAtLattice(
for (const FStrateSlot& Slot : StrateLayout)
{
if (Slot.Definition == nullptr) continue;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * StrateLayoutChunkWidthVoxels;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * CHUNK_SIZE;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * CHUNK_SIZE;
const float Seal = VF_BoundarySealThicknessForDefinition(*Slot.Definition);
const VoxelPassageGeometry::FOriginLandingGeometry Geometry =
VoxelPassageGeometry::BuildOriginLandingGeometry(
@@ -5964,8 +5952,8 @@ bool UVoxelStrateManager::AnyOriginLandingNearBox(
for (const FStrateSlot& Slot : StrateLayout)
{
if (Slot.Definition == nullptr) continue;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * StrateLayoutChunkWidthVoxels;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * CHUNK_SIZE;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * CHUNK_SIZE;
if (VoxelPassageGeometry::OriginLandingRoomTouchesBox(
VoxelBox, TopZ, BottomZ,
VF_BoundarySealThicknessForDefinition(*Slot.Definition),
@@ -5985,8 +5973,8 @@ bool UVoxelStrateManager::AnyOriginLandingFloorNearBox(
for (const FStrateSlot& Slot : StrateLayout)
{
if (Slot.Definition == nullptr) continue;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * StrateLayoutChunkWidthVoxels;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * CHUNK_SIZE;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * CHUNK_SIZE;
if (VoxelPassageGeometry::OriginLandingFloorTouchesBox(
VoxelBox, TopZ, BottomZ,
VF_BoundarySealThicknessForDefinition(*Slot.Definition),
@@ -6010,8 +5998,8 @@ bool UVoxelStrateManager::AnyOriginLandingNearLattice(
for (const FStrateSlot& Slot : StrateLayout)
{
if (Slot.Definition == nullptr) continue;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * StrateLayoutChunkWidthVoxels;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * CHUNK_SIZE;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * CHUNK_SIZE;
const float Seal = VF_BoundarySealThicknessForDefinition(*Slot.Definition);
if (VoxelPassageGeometry::OriginLandingRoomTouchesLattice(
VoxelBox, LatticeOrigin, Step, TopZ, BottomZ, Seal, OriginSpineRadius,
@@ -6048,8 +6036,8 @@ bool UVoxelStrateManager::AnyOriginLandingAirNearLattice(
{
continue;
}
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * StrateLayoutChunkWidthVoxels;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * CHUNK_SIZE;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * CHUNK_SIZE;
const float Seal = VF_BoundarySealThicknessForDefinition(*Slot.Definition);
const VoxelPassageGeometry::FOriginLandingGeometry Geometry =
VoxelPassageGeometry::BuildOriginLandingGeometry(
@@ -6125,8 +6113,8 @@ bool UVoxelStrateManager::AnyOriginLandingFloorNearLattice(
for (const FStrateSlot& Slot : StrateLayout)
{
if (Slot.Definition == nullptr) continue;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * StrateLayoutChunkWidthVoxels;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * CHUNK_SIZE;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * CHUNK_SIZE;
const float Seal = VF_BoundarySealThicknessForDefinition(*Slot.Definition);
if (VoxelPassageGeometry::OriginLandingFloorTouchesLattice(
VoxelBox, LatticeOrigin, Step, TopZ, BottomZ, Seal, OriginSpineRadius))
@@ -6160,7 +6148,7 @@ int32 UVoxelStrateManager::FindSlotIndexForChunkZ(int32 ChunkZ) const
UVoxelStrateDefinition* UVoxelStrateManager::GetStrateAt(float WorldZ) const
{
// Convert world Z to chunk Z coordinate
int32 ChunkZ = FMath::FloorToInt((WorldZ / VOXEL_SIZE) / StrateLayoutChunkWidthVoxels);
int32 ChunkZ = FMath::FloorToInt((WorldZ / VOXEL_SIZE) / CHUNK_SIZE);
int32 SlotIdx = FindSlotIndexForChunkZ(ChunkZ);
if (SlotIdx >= 0)
{
@@ -6171,7 +6159,7 @@ UVoxelStrateDefinition* UVoxelStrateManager::GetStrateAt(float WorldZ) const
int32 UVoxelStrateManager::GetStrateIndex(float WorldZ) const
{
int32 ChunkZ = FMath::FloorToInt((WorldZ / VOXEL_SIZE) / StrateLayoutChunkWidthVoxels);
int32 ChunkZ = FMath::FloorToInt((WorldZ / VOXEL_SIZE) / CHUNK_SIZE);
int32 SlotIdx = FindSlotIndexForChunkZ(ChunkZ);
if (SlotIdx >= 0)
{
@@ -6330,9 +6318,9 @@ FSlabGenerationParams UVoxelStrateManager::GetSlabParamsForChunk(const FIntVecto
// Fill in the runtime Z bounds (voxel coordinates, same convention as
// FStrateGenerationParams::StrateTopWorldZ / StrateBottomWorldZ).
// TopChunkZ+1 because the top chunk's CEILING is at (TopChunkZ+1)*StrateLayoutChunkWidthVoxels.
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
Result.StrateBottomWorldZ = (float)(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
// TopChunkZ+1 because the top chunk's CEILING is at (TopChunkZ+1)*CHUNK_SIZE.
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
Result.StrateBottomWorldZ = (float)(Slot.BottomChunkZ) * CHUNK_SIZE;
return Result;
}
@@ -6365,8 +6353,8 @@ FMazeGenerationParams UVoxelStrateManager::GetMazeParamsForChunk(const FIntVecto
}
}
#endif
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * StrateLayoutChunkWidthVoxels;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * CHUNK_SIZE;
return Result;
}
@@ -6392,8 +6380,8 @@ FSurfaceGenerationParams UVoxelStrateManager::GetSurfaceParamsForChunk(const FIn
}
}
#endif
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * StrateLayoutChunkWidthVoxels;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * CHUNK_SIZE;
return Result;
}
@@ -6419,8 +6407,8 @@ FVerticalShaftParams UVoxelStrateManager::GetVerticalShaftParamsForChunk(const F
}
}
#endif
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * StrateLayoutChunkWidthVoxels;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * CHUNK_SIZE;
return Result;
}
@@ -6446,8 +6434,8 @@ FFloatingIslandParams UVoxelStrateManager::GetFloatingIslandParamsForChunk(const
}
}
#endif
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * StrateLayoutChunkWidthVoxels;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * CHUNK_SIZE;
return Result;
}
@@ -6481,14 +6469,14 @@ FBiomeContext UVoxelStrateManager::GetBiomeContextForChunk(const FIntVector& Chu
bool UVoxelStrateManager::GetStrateUnrealZRange(float WorldZ, float& OutTopZ, float& OutBottomZ) const
{
const int32 ChunkZ = FMath::FloorToInt((WorldZ / VOXEL_SIZE) / StrateLayoutChunkWidthVoxels);
const int32 ChunkZ = FMath::FloorToInt((WorldZ / VOXEL_SIZE) / CHUNK_SIZE);
const int32 SlotIdx = FindSlotIndexForChunkZ(ChunkZ);
if (SlotIdx < 0) return false;
const FStrateSlot& Slot = StrateLayout[SlotIdx];
// Voxel-space Z bounds → Unreal units. Ceiling = top chunk's upper edge.
OutTopZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels * VOXEL_SIZE;
OutBottomZ = (float)(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels * VOXEL_SIZE;
OutTopZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE * VOXEL_SIZE;
OutBottomZ = (float)(Slot.BottomChunkZ) * CHUNK_SIZE * VOXEL_SIZE;
return true;
}
@@ -6501,8 +6489,8 @@ FStrateDisturbanceParams UVoxelStrateManager::GetDisturbanceParamsForChunk(const
}
const FStrateSlot& Slot = StrateLayout[SlotIdx];
FStrateDisturbanceParams Result = Slot.Definition->Disturbances;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
Result.StrateBottomWorldZ = (float)(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
Result.StrateBottomWorldZ = (float)(Slot.BottomChunkZ) * CHUNK_SIZE;
return Result;
}
@@ -6534,8 +6522,8 @@ float UVoxelStrateManager::GetWaterLevelWorldZForChunk(const FIntVector& ChunkCo
}
if (Rel <= 0.0f) return -FLT_MAX;
const float BottomZ = (float)(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
const float TopZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
const float BottomZ = (float)(Slot.BottomChunkZ) * CHUNK_SIZE;
const float TopZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
return FMath::Lerp(BottomZ, TopZ, FMath::Clamp(Rel, 0.0f, 1.0f));
}
@@ -6579,8 +6567,8 @@ FStrateGenerationParams UVoxelStrateManager::GetGenerationParams(const FIntVecto
FindComposerOverride(Slot.StrateIndex))
{
FStrateGenerationParams Result = Override->Params.TunnelNetworkParams;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * StrateLayoutChunkWidthVoxels;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * CHUNK_SIZE;
// A candidate is a hard replacement of this slot. Do not blend its rolled vector with an
// authored neighbour at a boundary; this is also how the offline fixture measures it.
return ResolveFinalParams(Result);
@@ -6590,8 +6578,8 @@ FStrateGenerationParams UVoxelStrateManager::GetGenerationParams(const FIntVecto
if (SeasonStrates.IsValidIndex(SlotIdx))
{
FStrateGenerationParams Result = SeasonStrates[SlotIdx].Params.TunnelNetworkParams;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * StrateLayoutChunkWidthVoxels;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * CHUNK_SIZE;
// Season vectors are already final, measured slot records. Vertical structural posts own
// their boundary; blending them with another selected recipe would describe neither one.
return ResolveFinalParams(Result);
@@ -6608,17 +6596,8 @@ FStrateGenerationParams UVoxelStrateManager::GetGenerationParams(const FIntVecto
//
// TopChunkZ=0, CHUNK_SIZE=32: top of the strate = chunk 0's top edge = voxel Z=32
// BottomChunkZ=-3: bottom of the strate = chunk -3's bottom edge = voxel Z=-3*32 = -96
BaseParams.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
BaseParams.StrateBottomWorldZ = (float)(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
// Core currently dispatches one generator field per resolved strate. Gradient and
// interleaved metadata therefore use the explicitly declared Hard fallback for every
// legacy parameter lookup as well; mixing parameter vectors here would disagree with the
// shared ceiling/content/bedrock composition layer.
if (bHardTransitionFallbackForAssembly)
{
return ResolveFinalParams(BaseParams);
}
BaseParams.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
BaseParams.StrateBottomWorldZ = (float)(Slot.BottomChunkZ) * CHUNK_SIZE;
//=========================================================================
// BOUNDARY BLENDING (transition-type aware)
@@ -6691,8 +6670,8 @@ FStrateGenerationParams UVoxelStrateManager::GetGenerationParams(const FIntVecto
if (EffectiveBlend > 0 && DistFromBottom < EffectiveBlend)
{
FStrateGenerationParams BelowParams = BuildParamsFromDefinition(BelowSlot.Definition);
BelowParams.StrateTopWorldZ = (float)(BelowSlot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
BelowParams.StrateBottomWorldZ = (float)(BelowSlot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
BelowParams.StrateTopWorldZ = (float)(BelowSlot.TopChunkZ + 1) * CHUNK_SIZE;
BelowParams.StrateBottomWorldZ = (float)(BelowSlot.BottomChunkZ) * CHUNK_SIZE;
// Linear alpha: 0 at EffectiveBlend chunks away, 1 at the boundary
float Alpha = 1.0f - ((float)DistFromBottom / (float)EffectiveBlend);
@@ -6729,8 +6708,8 @@ FStrateGenerationParams UVoxelStrateManager::GetGenerationParams(const FIntVecto
if (DistFromBottom < CheckRange)
{
FStrateGenerationParams BelowParams = BuildParamsFromDefinition(BelowSlot.Definition);
BelowParams.StrateTopWorldZ = (float)(BelowSlot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
BelowParams.StrateBottomWorldZ = (float)(BelowSlot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
BelowParams.StrateTopWorldZ = (float)(BelowSlot.TopChunkZ + 1) * CHUNK_SIZE;
BelowParams.StrateBottomWorldZ = (float)(BelowSlot.BottomChunkZ) * CHUNK_SIZE;
// Sample 3D Perlin noise to warp the boundary position.
// XY frequency 0.15 gives medium-scale variation (~6-7 chunks per cycle).
@@ -6790,8 +6769,8 @@ FStrateGenerationParams UVoxelStrateManager::GetGenerationParams(const FIntVecto
if (EffectiveBlend > 0 && DistFromTop < EffectiveBlend)
{
FStrateGenerationParams AboveParams = BuildParamsFromDefinition(AboveSlot.Definition);
AboveParams.StrateTopWorldZ = (float)(AboveSlot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
AboveParams.StrateBottomWorldZ = (float)(AboveSlot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
AboveParams.StrateTopWorldZ = (float)(AboveSlot.TopChunkZ + 1) * CHUNK_SIZE;
AboveParams.StrateBottomWorldZ = (float)(AboveSlot.BottomChunkZ) * CHUNK_SIZE;
float Alpha = 1.0f - ((float)DistFromTop / (float)EffectiveBlend);
Alpha = FMath::Clamp(Alpha, 0.0f, 1.0f);
@@ -6812,8 +6791,8 @@ FStrateGenerationParams UVoxelStrateManager::GetGenerationParams(const FIntVecto
if (DistFromTop < CheckRange)
{
FStrateGenerationParams AboveParams = BuildParamsFromDefinition(AboveSlot.Definition);
AboveParams.StrateTopWorldZ = (float)(AboveSlot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
AboveParams.StrateBottomWorldZ = (float)(AboveSlot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
AboveParams.StrateTopWorldZ = (float)(AboveSlot.TopChunkZ + 1) * CHUNK_SIZE;
AboveParams.StrateBottomWorldZ = (float)(AboveSlot.BottomChunkZ) * CHUNK_SIZE;
// Same noise function but with a different seed offset to avoid
// symmetry between top and bottom boundaries of adjacent strates
@@ -41,27 +41,21 @@
// SealFactor > 0 et BaseDensity > 0, le résultat est solide GARANTI quelle qu'ait été l'entrée.
// C'est exactement ce qu'encode `IVoxelDensityOp::ClassifyBox` (voir VoxelDensityOp.h), et la
// raison pour laquelle cette méthode existe.
FORCEINLINE void VF_ApplyUpperBoundarySealValue(float& Density, float WorldZ,
float StrateTopZ, float Thickness, float BaseDensity)
{
const float DistTop = StrateTopZ - WorldZ;
if (DistTop >= 0.0f && DistTop < Thickness)
{
float SealFactor = 1.0f - (DistTop / Thickness);
SealFactor = SmoothStep01(SealFactor);
Density = FMath::Max(Density, SealFactor * BaseDensity);
}
}
FORCEINLINE void VF_ApplyBoundarySeal(float& Density, float WorldZ,
float StrateTopZ, float StrateBottomZ,
float Thickness, float BaseDensity)
{
if (VoxelDensityAblation::IsBoundarySealOff() || Thickness <= 0.0f) return;
const float DistTop = StrateTopZ - WorldZ; // + si on est sous le plafond
const float DistBot = WorldZ - StrateBottomZ; // + si on est au-dessus du sol
VF_ApplyUpperBoundarySealValue(Density, WorldZ, StrateTopZ, Thickness, BaseDensity);
if (DistTop >= 0.0f && DistTop < Thickness)
{
float SealFactor = 1.0f - (DistTop / Thickness);
SealFactor = SmoothStep01(SealFactor);
Density = FMath::Max(Density, SealFactor * BaseDensity);
}
if (DistBot >= 0.0f && DistBot < Thickness)
{
float SealFactor = 1.0f - (DistBot / Thickness);
@@ -70,16 +64,6 @@ FORCEINLINE void VF_ApplyBoundarySeal(float& Density, float WorldZ,
}
}
// The same structural seal, limited to a strate's upper boundary. Native finite fields use this
// when their lower boundary intentionally has no seal; keeping the math here makes that ceiling
// use the same shared density primitive as every two-sided strate seal.
FORCEINLINE void VF_ApplyUpperBoundarySeal(float& Density, float WorldZ,
float StrateTopZ, float Thickness, float BaseDensity)
{
if (VoxelDensityAblation::IsBoundarySealOff() || Thickness <= 0.0f) return;
VF_ApplyUpperBoundarySealValue(Density, WorldZ, StrateTopZ, Thickness, BaseDensity);
}
//=============================================================================
// CARVE DE PASSAGE / PASSAGE CARVING
//=============================================================================
-7
View File
@@ -419,13 +419,6 @@ public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Voxel|Strates", meta = (ClampMin = "0", ClampMax = "16"))
int32 InterStrateGapChunks = 0;
// Physical width of one vertical strate-layout chunk. This is independent of the
// Core tile width (32^3 voxels) and of the source generator's voxel resolution.
// 8 m preserves the owner's current SurfaceWorld extent at 25 cm Core voxels.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Voxel|Strates|World Assembly",
meta = (ClampMin = "0.25", ClampMax = "64.0", Units = "m"))
float StrateLayoutChunkSizeMeters = 8.0f;
//=========================================================================
// SPINE & INTER-STRATE CONNECTIONS (the (0,0) descent axis)
//=========================================================================
@@ -244,13 +244,6 @@ public:
UFUNCTION(BlueprintCallable, Category = "Strate")
int32 GetStrateIndex(float WorldZ) const;
// Director-resolved physical strate chunk width expressed in owner voxel units.
// This is independent of Core's 32^3 tile width.
float GetStrateLayoutChunkWidthVoxels() const { return StrateLayoutChunkWidthVoxels; }
uint32 GetStrateLayoutChunkSizeMicrometres() const { return StrateLayoutChunkSizeMicrometres; }
void SetHardTransitionFallbackForAssembly(bool bEnabled)
{ bHardTransitionFallbackForAssembly = bEnabled; }
/** Layout/passage generation counter (bumped by every Initialize → GeneratePassages).
* Hot-path callers key thread_local memos on this so an editor rebuild (RebuildStrates /
* live edit) can never serve a stale strate index or passage shortlist. */
@@ -532,11 +525,6 @@ protected:
// VoxelSettings::InterStrateGapChunks during Initialize().
int32 InterStrateGapChunks = 0;
// Resolved once from VoxelSettings::StrateLayoutChunkSizeMeters during Initialize().
float StrateLayoutChunkWidthVoxels = 32.0f;
uint32 StrateLayoutChunkSizeMicrometres = 8000000;
bool bHardTransitionFallbackForAssembly = false;
// Production keeps the legacy writer available only as a fail-closed fallback for a
// non-native/malformed passage; native D-floors bypass it. This switch never changes the
// passage carve or air contract.
+11 -7
View File
@@ -1852,6 +1852,8 @@ struct VOXELFORGE_API FStrateDisturbanceParams
UENUM(BlueprintType)
enum class EVoxelPassageStyle : uint8
{
// “Straight” is retained as the authored style name for the base connection, but its runtime
// geometry is a gentle two-leg switchback rather than a vertical shaft.
Straight UMETA(DisplayName = "Straight (walkable sloped tunnel)"),
Worm UMETA(DisplayName = "Worm (organic meander around the axis)"),
Spiral UMETA(DisplayName = "Spiral (corkscrew descent)"),
@@ -1876,12 +1878,14 @@ struct VOXELFORGE_API FStratePassageConfig
// Tunnel shape.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Passage")
EVoxelPassageStyle Style = EVoxelPassageStyle::Worm;
EVoxelPassageStyle Style = EVoxelPassageStyle::Straight;
// ----- WIDTH (tapers along the length) -----
// Radius at the two mouths (entry/exit) and at the middle. Equal = uniform tube;
// Core raises both radii to at least 12 owner voxels (1.5 m) for capsule clearance.
// The passage landing remains wider for turning.
// The walkable default is 1.5x the original comfortable profile: 2.25 m diameter at mouths
// and 1.875 m at the waist when the stored radii remain 9/7.5 voxels at 12.5 cm per voxel.
// Double these asset values to retain the previous 4.5/3.75 m dimensions. The §6.5 landing
// room remains wider for turning.
// Mouth > Mid = chambers at the ends with a squeeze between; Mid > Mouth = a bulge.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Passage|Width", meta = (ClampMin = "1.0"))
float MouthRadius = 9.0f;
@@ -1908,8 +1912,8 @@ struct VOXELFORGE_API FStratePassageConfig
float DistanceMax = 192.0f;
// ----- SHAPE detail -----
// Max sideways variation from the winding path's axis (voxels). Core keeps the route inside
// DistanceMax and adds enough distance to meet the walkable grade.
// Exotic styles only: max sideways excursion from the axis (voxels). 24 = 6 m; 0 = straight
// even in Worm style. The default walkable switchback does not use this wander value.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Passage|Shape", meta = (ClampMin = "0.0"))
float Wander = 24.0f;
@@ -1922,8 +1926,8 @@ struct VOXELFORGE_API FStratePassageConfig
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Passage|Shape", meta = (ClampMin = "0.0"))
float VerticalWobble = 0.0f;
// Spiral style: helix radius (voxels) and minimum number of turns. Core adds turns when
// needed to meet the walkable grade. The default stored radius is 3 m at the legacy scale.
// Spiral style: helix radius (voxels) and number of full turns over the descent. The default
// radius is 6 m.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Passage|Spiral", meta = (ClampMin = "1.0"))
float SpiralRadius = 24.0f;
+1 -1
View File
@@ -118,7 +118,7 @@ PIDS=()
CORE_LIBRARY="$BUILD_DIR/libVoxelForgeCore.a"
"$(command -v ar)" rcs "$CORE_LIBRARY" "${CORE_OBJECTS[@]}"
OUTPUT="$BIN_DIR/VoxelForgeCoreHeadless-$VARIANT"
"$COMPILER" -pthread "${LEGACY_OBJECTS[@]}" "$CORE_LIBRARY" -o "$OUTPUT"
"$COMPILER" -pthread "${LEGACY_OBJECTS[@]}" "$CORE_LIBRARY" -lz -o "$OUTPUT"
CAPTURE_OUTPUT="$BIN_DIR/VoxelForgeOffscreenCapture-$VARIANT"
"$COMPILER" -std=c++20 -O2 -fno-fast-math -pthread \
"$ROOT/Source/LinuxOffscreenCapture.cpp" -o "$CAPTURE_OUTPUT" \
+2 -7
View File
@@ -153,13 +153,8 @@ radius range, top flattening, taper, bounded contour warp, roughness, blend, con
route constraints. `PlanFloatingIslandCluster` emits stable island and connector IDs, a connected
cluster graph, conservative influence AABBs, and a centerline route. At least the primary chain is
always planned; `islandDensityQ16` controls up to two optional side sites. Connectors carry a sharp-tag
ready bit for a later hybrid-mesher adapter. The schema accepts geometry versions 1 through 3.
Version 3 keeps the version-2 island form, removes the all-XY lower seal, and obtains its ceiling from
the shared upper-strate boundary seal. The resolved upper bound comes from the strate's own chunk
range; `boundarySealSubvoxels` sets the shared seal thickness and remains a planning margin for island
features. It does not define a FloatingIslands-specific ceiling height. Versions 1 and 2 retain their
recorded two-sided boundary seals. Manifests without a geometry version retain version-1 evaluation
and canonical hashes.
ready bit for a later hybrid-mesher adapter. The schema accepts geometry version 1 and 2. Manifests
without a geometry version retain version-1 evaluation and canonical hashes.
`FloatingIslandFieldV1::densitySubvoxels` evaluates the canonical island and connector field.
`interval` returns unknown for boxes overlapping any influence AABB and a certified all-air range
@@ -248,9 +248,9 @@ namespace VoxelForgeCore
// This is independent of tile size and is the fixed input scale for Core field blocks.
// L'assembleur v1 encode coordonnees et scalaires en 1/256 de voxel, independamment des tuiles.
inline constexpr std::int64_t WorldAssemblySubvoxelsPerVoxel = 256;
inline constexpr std::uint32_t WorldAssemblySchemaVersion = 2;
// Version 10 adds per-strate passage styles and rough wall relief to resolved passages.
inline constexpr std::uint32_t WorldAssemblyEvaluatorVersion = 10;
inline constexpr std::uint32_t WorldAssemblySchemaVersion = 1;
// Version 6 binds every compiled tile page to the world's base density evaluator.
inline constexpr std::uint32_t WorldAssemblyEvaluatorVersion = 6;
enum class FieldChannel : std::uint32_t
{
@@ -302,8 +302,6 @@ namespace VoxelForgeCore
std::uint32_t schemaVersion = WorldAssemblySchemaVersion;
std::uint32_t evaluatorVersion = WorldAssemblyEvaluatorVersion;
std::uint32_t unitsPerVoxel = static_cast<std::uint32_t>(WorldAssemblySubvoxelsPerVoxel);
// Resolved physical strate chunk width in 1/256 Core voxel units; tileVoxelCount remains 32.
std::int64_t layoutChunkWidthSubvoxels = 8192;
std::uint32_t seed = 0;
std::int64_t biomeCellSizeSubvoxels = 256 * 800;
std::int64_t biomeWarpSubvoxels = 256 * 250;
@@ -394,12 +392,7 @@ namespace VoxelForgeCore
std::uint32_t schemaVersion = 1;
// Profile 1 preserves the original shallow pads. Profile 2 adds a thick crust,
// bounded lobed roots and arched spans without changing the feature-family schema.
// Version 3 keeps the version-2 island shapes, removes the all-XY lower boundary seal,
// and routes its upper seal through the shared strate-boundary primitive. Version 4
// records the director-resolved strate layout width. Version 5 adds one passage-rooted
// island whose root reaches the owned bedrock and whose surface route ends at its mouth.
// New production adapters opt in explicitly; the compatibility default remains version 4.
std::uint32_t geometryVersion = 4;
std::uint32_t geometryVersion = 2;
std::uint32_t unitsPerVoxel = static_cast<std::uint32_t>(WorldAssemblySubvoxelsPerVoxel);
// Import scale is explicit in microns; the reduced ratio maps owner-authored lengths to Core voxels.
// L'echelle d'import est explicite en microns; le rapport reduit convertit les longueurs owner.
@@ -413,9 +406,6 @@ namespace VoxelForgeCore
std::int64_t layoutCenterTopZSubvoxels = -64 * WorldAssemblySubvoxelsPerVoxel;
std::int64_t layoutMinimumZSubvoxels = -128 * WorldAssemblySubvoxelsPerVoxel;
std::int64_t layoutMaximumZSubvoxels = 0;
// Director-resolved physical strate layout chunk in 1/256 Core voxel units.
// This is independent of the internal 32-voxel Core tile.
std::int64_t layoutChunkWidthSubvoxels = 8192;
std::uint32_t primaryIslandCount = 3;
std::int64_t islandDensityQ16 = 1ll << 15;
// Legacy owner lengths use ownerVoxelSizeMicrons; the scale ratio converts them to Core voxels.
@@ -436,14 +426,6 @@ namespace VoxelForgeCore
std::int64_t boundarySealSubvoxels = 2 * WorldAssemblySubvoxelsPerVoxel;
std::int64_t bridgeHalfWidthSubvoxels = 3 * WorldAssemblySubvoxelsPerVoxel;
std::int64_t bridgeThicknessSubvoxels = 4 * WorldAssemblySubvoxelsPerVoxel;
// Version 5 anchor-island inputs are resolved from that strate's passage config.
// The anchor is the last primary route island and must stay inside the passage disk.
std::uint32_t anchorIslandOrdinal = 2;
std::int64_t anchorPlacementRadiusSubvoxels = 0;
std::int64_t anchorRootRadiusSubvoxels = 0;
std::int64_t anchorIslandMinimumRadiusSubvoxels = 0;
std::int64_t anchorRootBottomZSubvoxels = 0;
std::int64_t anchorMouthOffsetSubvoxels = 0;
WorldAssemblyRouteConstraintsV1 routeConstraints;
std::uint64_t contentHash = 0;
};
@@ -547,8 +529,7 @@ namespace VoxelForgeCore
std::uint64_t contentHash = 0;
static std::optional<FloatingIslandManifestV1> FromJson(
std::string_view json, std::string& error,
std::int64_t resolvedLayoutChunkWidthSubvoxels = 0);
std::string_view json, std::string& error);
bool finalize(std::string& error);
bool validate(std::string& error) const;
std::string ToJson() const;
@@ -580,147 +561,6 @@ namespace VoxelForgeCore
std::string ToJson() const;
};
// Read-only, versioned account of the physical layout resolved by the director and the
// Core adapter. Coordinates are half-open micrometre intervals; recipe anchors retain their
// source fixed-point units so this record never rounds the recipe itself.
inline constexpr std::uint32_t ResolvedLayoutSchemaVersionV3 = 3;
enum class ResolvedLayoutValidationModeV3 : std::uint8_t { compatibility, strict };
struct ResolvedLayoutAnchorV2
{
std::string kind;
std::string stableId;
std::string units;
std::vector<std::int64_t> values;
};
struct ResolvedLayoutBandV2
{
std::string kind; // ceiling, content, bedrock
std::int64_t bottomMicrometres = 0;
std::int64_t topMicrometres = 0;
bool presentInCurrentField = false;
bool diggable = true;
bool protectedBand = false;
std::string behaviour;
std::string densitySide;
std::string capPath;
std::int64_t solidDensityQ16 = 1ll << 16;
};
struct ResolvedLayoutStratumV2
{
std::string stableId;
std::int32_t order = 0;
std::int32_t strateIndex = -1;
std::string generatorKind;
std::string recipeId;
std::uint32_t recipeVersion = 0;
std::int64_t interiorBottomMicrometres = 0;
std::int64_t interiorTopMicrometres = 0;
std::uint32_t voxelSizeMicrometres = 0;
std::array<std::int64_t, 3> latticeOriginMicrometres{};
ResolvedLayoutBandV2 ceiling;
ResolvedLayoutBandV2 content;
ResolvedLayoutBandV2 bedrock;
std::string transitionMode; // mode at this strate's lower interface
std::int32_t transitionBlendChunks = 0;
std::int64_t transitionWidthMicrometres = 0;
std::int64_t transitionWarpAmplitudeMicrometres = 0;
std::int64_t transitionInterpenetrationMicrometres = 0;
bool transitionHonouredInCore = false;
bool transitionFallsBackToHard = false;
std::string transitionDispatchPath;
std::string boundDispatchPath;
std::string queryDispatchPath;
std::string managerLookup;
std::int64_t managerChunkWidthMicrometres = 0;
std::int64_t dispatchChunkWidthMicrometres = 0;
std::vector<ResolvedLayoutAnchorV2> anchors;
};
struct ResolvedLayoutIssueV2
{
std::string code;
std::string detail;
};
struct ResolvedLayoutPassagePointV1
{
std::array<std::int64_t, 3> positionSubvoxels{};
std::int64_t radiusSubvoxels = 0;
};
struct ResolvedLayoutPassageV1
{
std::string stableId;
std::int32_t upperStrateIndex = -1;
std::int32_t lowerStrateIndex = -1;
std::int64_t placementRadiusSubvoxels = 0;
std::array<std::int64_t, 3> upperMouthSubvoxels{};
std::array<std::int64_t, 3> lowerMouthSubvoxels{};
std::int64_t mouthRadiusSubvoxels = 0;
std::int64_t midRadiusSubvoxels = 0;
// Derived from the mouth binding; the main descent is monotone through this point.
std::size_t lowerMouthControlIndex = 0;
std::vector<ResolvedLayoutPassagePointV1> controlPoints;
};
struct ResolvedLayoutPassageConfigV1
{
std::int32_t upperStrateIndex = -1;
std::int32_t connections = 1;
// EVoxelPassageStyle numeric values: Straight=0, Worm=1, Spiral=2, Cascading=3.
std::uint32_t style = 1;
std::int64_t mouthRadiusSubvoxels = 0;
std::int64_t midRadiusSubvoxels = 0;
std::int64_t reachMinimumSubvoxels = 0;
std::int64_t reachMaximumSubvoxels = 0;
std::int64_t distanceMinimumSubvoxels = 0;
std::int64_t distanceMaximumSubvoxels = 0;
std::int64_t wanderSubvoxels = 0;
std::uint32_t segments = 20;
std::int64_t verticalWobbleSubvoxels = 0;
std::int64_t spiralRadiusSubvoxels = 0;
std::int64_t spiralTurnsQ16 = 2ll << 16;
std::uint32_t cascadeSteps = 4;
std::int64_t cascadeLedgeSubvoxels = 0;
};
struct VFCORE_API ResolvedLayoutSnapshotV3
{
std::uint32_t schemaVersion = ResolvedLayoutSchemaVersionV3;
std::string worldIdentity;
std::uint32_t ownerVoxelSizeMicrometres = 0;
std::uint32_t coreVoxelSizeMicrometres = 0;
std::uint32_t strateLayoutChunkSizeMicrometres = 8000000;
std::int64_t strateLayoutChunkWidthSubvoxels = 8192;
std::vector<ResolvedLayoutStratumV2> strates;
std::vector<ResolvedLayoutPassageV1> passages;
std::string stableIdentity;
bool finalize(std::string& error);
bool validate(ResolvedLayoutValidationModeV3 mode,
std::vector<ResolvedLayoutIssueV2>& issues,
std::string& error) const;
std::string ToJson() const;
static std::optional<ResolvedLayoutSnapshotV3> FromJson(
std::string_view json, std::string& error);
};
struct ResolvedLayoutValidatorAuditV3
{
std::uint32_t controlsRun = 0;
std::uint32_t controlsRejectedAsExpected = 0;
bool passed = false;
std::vector<ResolvedLayoutIssueV2> failures;
};
VFCORE_API ResolvedLayoutValidatorAuditV3 AuditResolvedLayoutValidatorV3();
VFCORE_API bool PlanResolvedLayoutPassagesV1(
ResolvedLayoutSnapshotV3& layout, std::int32_t seed,
const std::vector<ResolvedLayoutPassageConfigV1>& configs,
std::string& error);
struct FloatingIslandBoundsAuditResult
{
std::uint64_t boxesTested = 0;
@@ -998,8 +838,6 @@ namespace VoxelForgeCore
explicit operator bool() const noexcept { return static_cast<bool>(data_); }
const WorldConfiguration& configuration() const;
const WorldAssemblyManifest* worldAssembly() const noexcept;
const ResolvedLayoutSnapshotV3* resolvedLayout() const noexcept;
ResolvedWorldSnapshot withoutResolvedLayoutPassages() const;
private:
struct Data;
@@ -1256,11 +1094,11 @@ namespace VoxelForgeCore
// LOD8-only planar horizon interior grid; zero follows the MC step, 128 restores S9.
// Grille interieure LOD8 seulement; zero suit la maille MC, 128 restaure S9.
std::int32_t lod8HorizonInteriorStepVoxels = 0;
// Bump when shared stratum-boundary caps or the distant horizon representation changes.
// LOD4-8 mesh hashes are salted; density and LOD0-3 keep their direct identities.
// Incremente quand les plafonds partages ou l'horizon lointain changent.
// Les hashes de maillage LOD4-8 incluent cette version; LOD0-3 gardent leur identite directe.
std::uint32_t farHorizonVersion = 4;
// Bump when the distant cap representation changes. LOD4-8 mesh hashes are salted;
// density and LOD0-3 hashes remain unchanged.
// Incremente quand le plafond lointain change. Les hashes LOD4-8 incluent cette version;
// densite et hashes LOD0-3 restent inchanges.
std::uint32_t farHorizonVersion = 3;
// Linux research controls for reproducing L5 negative controls. Defaults preserve output.
std::uint32_t diagnosticGlobalOctaveDrop = 0;
std::uint32_t diagnosticCellStride = 1;
@@ -1314,8 +1152,6 @@ namespace VoxelForgeCore
ShapeBuildStats buildStats() const;
float densityAt(Vec3d voxelPosition) const;
// Audit-only selector provenance for the same point evaluator; never used by meshing.
std::string densityDispatchPathAt(Vec3d voxelPosition) const;
// Analytic source distance without the occupancy-preserving near-zero clamp or packed proxy.
float unclampedDensityAt(Vec3d voxelPosition) const;
DetailFieldSample detailSampleAt(Vec3d voxelPosition) const;
+8 -340
View File
@@ -817,9 +817,8 @@ inline void AppendFarConnectorShells(const FStandaloneShapeWorld& Shape,const FV
struct FFarMeshColumnIndex
{
FFarMeshColumnIndex(const FVoxelMeshData& InMesh,const FIntVector& InOrigin,int32 InExtent,
int32 InCells,double InStep,double InVoxelSizeCm)
int32 InCells,double InStep)
:Mesh(InMesh),Origin(InOrigin),Extent(InExtent),Cells(InCells),Step(InStep),
VoxelSizeCm(InVoxelSizeCm),
ByColumn(static_cast<size_t>(InCells)*InCells)
{
for(int32 Triangle=0;Triangle+2<Mesh.Triangles.Num();Triangle+=3)
@@ -865,98 +864,16 @@ struct FFarMeshColumnIndex
return Hits;
}
bool HasDownwardHit(double X,double Y,double Z,double Tolerance) const
{
const int32 CX=std::clamp(static_cast<int32>(std::floor((X-Origin.X)/Step)),0,Cells-1);
const int32 CY=std::clamp(static_cast<int32>(std::floor((Y-Origin.Y)/Step)),0,Cells-1);
const auto& Candidates=ByColumn[static_cast<size_t>(CY)*Cells+CX];
for(const int32 Triangle:Candidates)
{
const int32 IA=Mesh.Triangles[Triangle*3],IB=Mesh.Triangles[Triangle*3+1],
IC=Mesh.Triangles[Triangle*3+2];
if(IA<0||IB<0||IC<0||IA>=Mesh.Normals.Num()||IB>=Mesh.Normals.Num()
||IC>=Mesh.Normals.Num())continue;
if(Mesh.Normals[IA].Z+Mesh.Normals[IB].Z+Mesh.Normals[IC].Z>=-1.5)continue;
const double AX=PositionAxis(IA,0),AY=PositionAxis(IA,1),AZ=PositionAxis(IA,2);
const double BX=PositionAxis(IB,0),BY=PositionAxis(IB,1),BZ=PositionAxis(IB,2);
const double CXv=PositionAxis(IC,0),CYv=PositionAxis(IC,1),CZ=PositionAxis(IC,2);
const double Den=(BX-AX)*(CYv-AY)-(BY-AY)*(CXv-AX);
if(std::abs(Den)<1.0e-10)continue;
const double U=((X-AX)*(CYv-AY)-(Y-AY)*(CXv-AX))/Den;
const double V=((BX-AX)*(Y-AY)-(BY-AY)*(X-AX))/Den;
const double W=1.0-U-V;
if(U<-1.0e-7||V<-1.0e-7||W<-1.0e-7)continue;
const double Hit=AZ+U*(BZ-AZ)+V*(CZ-AZ);
if(std::abs(Hit-Z)<=Tolerance)return true;
}
return false;
}
bool HasDownwardCellCoverage(double X0,double Y0,double X1,double Y1,
double Z,double Tolerance) const
{
// Probe the perimeter as well as the interior: sparse interior-only probes can
// incorrectly hide a missing ceiling quad at an MC grid vertex.
// Sonder le perimetre et l'interieur: des sondes seulement interieures peuvent
// masquer un carre de plafond manquant sur un sommet de la grille MC.
constexpr double Samples[5]={0.0,0.25,0.5,0.75,1.0};
for(const double V:Samples)for(const double U:Samples)
{
const double X=X0+(X1-X0)*U;
const double Y=Y0+(Y1-Y0)*V;
if(!HasDownwardHit(X,Y,Z,Tolerance))return false;
}
return true;
}
bool HasUpwardHit(double X,double Y,double Z,double Tolerance) const
{
const int32 CX=std::clamp(static_cast<int32>(std::floor((X-Origin.X)/Step)),0,Cells-1);
const int32 CY=std::clamp(static_cast<int32>(std::floor((Y-Origin.Y)/Step)),0,Cells-1);
const auto& Candidates=ByColumn[static_cast<size_t>(CY)*Cells+CX];
for(const int32 Triangle:Candidates)
{
const int32 IA=Mesh.Triangles[Triangle*3],IB=Mesh.Triangles[Triangle*3+1],
IC=Mesh.Triangles[Triangle*3+2];
if(IA<0||IB<0||IC<0||IA>=Mesh.Normals.Num()||IB>=Mesh.Normals.Num()
||IC>=Mesh.Normals.Num())continue;
if(Mesh.Normals[IA].Z+Mesh.Normals[IB].Z+Mesh.Normals[IC].Z<=1.5)continue;
const double AX=PositionAxis(IA,0),AY=PositionAxis(IA,1),AZ=PositionAxis(IA,2);
const double BX=PositionAxis(IB,0),BY=PositionAxis(IB,1),BZ=PositionAxis(IB,2);
const double CXv=PositionAxis(IC,0),CYv=PositionAxis(IC,1),CZ=PositionAxis(IC,2);
const double Den=(BX-AX)*(CYv-AY)-(BY-AY)*(CXv-AX);
if(std::abs(Den)<1.0e-10)continue;
const double U=((X-AX)*(CYv-AY)-(Y-AY)*(CXv-AX))/Den;
const double V=((BX-AX)*(Y-AY)-(BY-AY)*(X-AX))/Den;
const double W=1.0-U-V;
if(U<-1.0e-7||V<-1.0e-7||W<-1.0e-7)continue;
const double Hit=AZ+U*(BZ-AZ)+V*(CZ-AZ);
if(std::abs(Hit-Z)<=Tolerance)return true;
}
return false;
}
bool HasUpwardCellCoverage(double X0,double Y0,double X1,double Y1,
double Z,double Tolerance) const
{
constexpr double Samples[5]={0.0,0.25,0.5,0.75,1.0};
for(const double V:Samples)for(const double U:Samples)
if(!HasUpwardHit(X0+(X1-X0)*U,Y0+(Y1-Y0)*V,Z,Tolerance))return false;
return true;
}
private:
double PositionAxis(int32 Index,int32 Axis) const
{
const FVector& P=Mesh.Vertices[Index];
const double WorldCentimetres=Axis==0?P.X:(Axis==1?P.Y:P.Z);
return WorldCentimetres/VoxelSizeCm;
return (Axis==0?P.X:(Axis==1?P.Y:P.Z))*0.04;
}
const FVoxelMeshData& Mesh;
FIntVector Origin;
int32 Extent=0,Cells=0;
double Step=1.0;
double VoxelSizeCm=25.0;
std::vector<std::vector<int32>> ByColumn;
};
@@ -1057,11 +974,11 @@ inline void AppendFarStratumShells(const FStandaloneOwnerWorld& World,const FSta
std::vector<FBoundary> Boundaries;
for(const FStrateSlot& Slot:Layout)
{
FStandaloneShapeWorld::FResolvedStratumBounds Resolved;
if(!Shape.GetResolvedStratumBounds(Slot,Resolved))continue;
const double HalfWidth=std::max(8.0,Resolved.SealThickness+8.0);
Boundaries.push_back({Resolved.BottomZ,HalfWidth});
Boundaries.push_back({Resolved.TopZ,HalfWidth});
const FStrateGenerationParams Params=World.Manager->GetGenerationParams(
FIntVector(0,0,(Slot.TopChunkZ+Slot.BottomChunkZ)/2));
const double HalfWidth=std::max(8.0,static_cast<double>(Params.BoundarySealThickness)+8.0);
Boundaries.push_back({static_cast<double>(Slot.BottomChunkZ)*CHUNK_SIZE,HalfWidth});
Boundaries.push_back({static_cast<double>(Slot.TopChunkZ+1)*CHUNK_SIZE,HalfWidth});
}
std::sort(Boundaries.begin(),Boundaries.end(),[](const FBoundary& A,const FBoundary& B){return A.Z<B.Z;});
Boundaries.erase(std::unique(Boundaries.begin(),Boundaries.end(),[](const FBoundary& A,const FBoundary& B)
@@ -1079,8 +996,7 @@ inline void AppendFarStratumShells(const FStandaloneOwnerWorld& World,const FSta
const bool bHasColors=Mesh.Colors.Num()==OldVertexCount;
const FColor Color=bHasColors&&OldVertexCount>0?Mesh.Colors[0]:FColor(160,160,160,255);
const int32 Cells=std::max(1,World.CoarseTileCells);
FFarMeshColumnIndex MeshIndex(Mesh,Origin,Extent,Cells,Step,
static_cast<double>(World.CoreVoxelSizeMicrons)/10000.0);
FFarMeshColumnIndex MeshIndex(Mesh,Origin,Extent,Cells,Step);
std::vector<FVector> NewVertices,NewNormals;
std::vector<FVector2f> NewUVs;std::vector<FColor> NewColors;
std::vector<int32> NewTriangles;
@@ -1216,251 +1132,3 @@ inline void AppendFarStratumShells(const FStandaloneOwnerWorld& World,const FSta
Mesh.TriangleSkirtFaceMasks=std::move(CombinedFaceMasks);
Mesh.NumSurfaceVertices=OldSurfaceVertices+AddedVertices;
}
inline void AppendStratumBoundaryCeilings(const FStandaloneOwnerWorld& World,
const FStandaloneShapeWorld& Shape,const FVoxelTileKey& Key,int32 Step,FVoxelMeshData& Mesh)
{
if(Key.Level<0||Step<=0||!World.Manager)return;
const FIntVector Origin=Key.OriginVoxels();
const int32 Extent=Key.ExtentVoxels();
const int32 GridStep=Step;
if(Extent<=0||GridStep<=0||Extent%GridStep!=0)return;
const int32 GridSide=Extent/GridStep+1;
struct FCandidate
{
double FaceZ=0.0;
double Thickness=0.0;
std::vector<uint8> SolidAbove;
};
std::vector<FCandidate> Candidates;
const double CoreMicrons=std::max<std::uint32_t>(1,World.CoreVoxelSizeMicrons);
for(const FStrateSlot& Slot:World.Manager->GetLayout())
{
const auto* Stratum=Shape.FindResolvedLayoutStratum(Slot.StrateIndex);
if(!Stratum||!Stratum->ceiling.presentInCurrentField
||Stratum->ceiling.topMicrometres<=Stratum->ceiling.bottomMicrometres)continue;
FCandidate Candidate;
Candidate.FaceZ=static_cast<double>(Stratum->ceiling.bottomMicrometres)/CoreMicrons;
Candidate.Thickness=static_cast<double>(Stratum->ceiling.topMicrometres
-Stratum->ceiling.bottomMicrometres)/CoreMicrons;
if(Candidate.FaceZ<Origin.Z-1.0e-6||Candidate.FaceZ>Origin.Z+Extent+1.0e-6)continue;
const double Epsilon=std::min(0.5,Candidate.Thickness*0.25);
if(Epsilon<=0.0)continue;
Candidate.SolidAbove.resize(static_cast<std::size_t>(GridSide)*GridSide,0);
bool AnySolidAbove=false;
for(int32 Y=0;Y<GridSide;++Y)for(int32 X=0;X<GridSide;++X)
{
const double WorldX=Origin.X+X*GridStep;
const double WorldY=Origin.Y+Y*GridStep;
const float Above=Shape.DensityAt(static_cast<float>(WorldX),static_cast<float>(WorldY),
static_cast<float>(Candidate.FaceZ+Epsilon));
const bool bSolidAbove=std::isfinite(Above)&&Above<0.0f;
Candidate.SolidAbove[static_cast<std::size_t>(Y*GridSide+X)]=bSolidAbove?1:0;
AnySolidAbove=AnySolidAbove||bSolidAbove;
}
if(AnySolidAbove)Candidates.push_back(std::move(Candidate));
}
if(Candidates.empty())return;
const int32 Cells=std::max(1,World.CoarseTileCells);
FFarMeshColumnIndex MeshIndex(Mesh,Origin,Extent,Cells,Step,
static_cast<double>(World.CoreVoxelSizeMicrons)/10000.0);
const int32 OldVertexCount=Mesh.Vertices.Num();
const int32 OldSurfaceVertices=std::clamp(Mesh.NumSurfaceVertices,0,OldVertexCount);
const bool bHasUVs=Mesh.UVs.Num()==OldVertexCount;
const bool bHasColors=Mesh.Colors.Num()==OldVertexCount;
const FColor Color=bHasColors&&OldVertexCount>0?Mesh.Colors[0]:FColor(160,160,160,255);
const double VoxelSizeCm=static_cast<double>(World.CoreVoxelSizeMicrons)/10000.0;
std::vector<FVector> NewVertices,NewNormals;
std::vector<FVector2f> NewUVs;
std::vector<FColor> NewColors;
std::vector<int32> NewTriangles;
for(const FCandidate& Candidate:Candidates)
{
std::vector<int32> VertexMap(static_cast<std::size_t>(GridSide)*GridSide,INDEX_NONE);
const double CeilingZ=Candidate.FaceZ;
const auto AddVertex=[&](int32 X,int32 Y)
{
const std::size_t GridIndex=static_cast<std::size_t>(Y*GridSide+X);
int32& Mapped=VertexMap[GridIndex];
if(Mapped!=INDEX_NONE)return Mapped;
Mapped=static_cast<int32>(NewVertices.size());
const double WorldX=Origin.X+X*GridStep,WorldY=Origin.Y+Y*GridStep;
NewVertices.emplace_back(WorldX*VoxelSizeCm,WorldY*VoxelSizeCm,CeilingZ*VoxelSizeCm);
NewNormals.emplace_back(0.0,0.0,-1.0);
if(bHasUVs)NewUVs.emplace_back(static_cast<float>(WorldX),static_cast<float>(WorldY));
if(bHasColors)NewColors.push_back(Color);
return Mapped;
};
for(int32 Y=0;Y+1<GridSide;++Y)for(int32 X=0;X+1<GridSide;++X)
{
const std::size_t I00=static_cast<std::size_t>(Y*GridSide+X);
const std::size_t I10=I00+1,I01=I00+GridSide,I11=I01+1;
if(!Candidate.SolidAbove[I00]||!Candidate.SolidAbove[I10]
||!Candidate.SolidAbove[I01]||!Candidate.SolidAbove[I11])continue;
const double CellX0=Origin.X+X*GridStep,CellY0=Origin.Y+Y*GridStep;
const double CellX1=CellX0+GridStep,CellY1=CellY0+GridStep;
// Suppress a coincident plane only when it covers the full cell. A hit at just the
// center of a curved shell triangle is not enough to leave the rest of this cap cell open.
if(MeshIndex.HasDownwardCellCoverage(CellX0,CellY0,CellX1,CellY1,CeilingZ,0.001))continue;
const int32 A=AddVertex(X,Y),B=AddVertex(X+1,Y);
const int32 C=AddVertex(X+1,Y+1),D=AddVertex(X,Y+1);
NewTriangles.insert(NewTriangles.end(),{A,C,B,A,D,C});
}
}
if(NewTriangles.empty())return;
const int32 AddedVertices=static_cast<int32>(NewVertices.size());
auto InsertVertices=[&](auto& Existing,const auto& Added)
{
using TArrayType=std::remove_reference_t<decltype(Existing)>;
TArrayType Combined;Combined.Reserve(Existing.Num()+static_cast<int32>(Added.size()));
for(int32 I=0;I<OldSurfaceVertices;++I)Combined.Add(Existing[I]);
for(const auto& Value:Added)Combined.Add(Value);
for(int32 I=OldSurfaceVertices;I<Existing.Num();++I)Combined.Add(Existing[I]);
Existing=std::move(Combined);
};
InsertVertices(Mesh.Vertices,NewVertices);InsertVertices(Mesh.Normals,NewNormals);
if(bHasUVs)InsertVertices(Mesh.UVs,NewUVs);
if(bHasColors)InsertVertices(Mesh.Colors,NewColors);
for(int32& Index:Mesh.Triangles)if(Index>=OldSurfaceVertices)Index+=AddedVertices;
const int32 CeilingStart=std::max(0,Mesh.Triangles.Num()-Mesh.NumCeilingTriangles*3);
TArray<int32> CombinedTriangles;CombinedTriangles.Reserve(
Mesh.Triangles.Num()+static_cast<int32>(NewTriangles.size()));
for(int32 I=0;I<CeilingStart;++I)CombinedTriangles.Add(Mesh.Triangles[I]);
for(const int32 Index:NewTriangles)CombinedTriangles.Add(OldSurfaceVertices+Index);
for(int32 I=CeilingStart;I<Mesh.Triangles.Num();++I)CombinedTriangles.Add(Mesh.Triangles[I]);
const int32 OldTriangleCount=Mesh.Triangles.Num()/3;
TArray<uint8> ExistingFaceMasks=Mesh.TriangleSkirtFaceMasks;
ExistingFaceMasks.SetNum(OldTriangleCount);
TArray<uint8> CombinedFaceMasks;CombinedFaceMasks.Reserve(
OldTriangleCount+static_cast<int32>(NewTriangles.size()/3));
for(int32 Triangle=0;Triangle<CeilingStart/3;++Triangle)
CombinedFaceMasks.Add(ExistingFaceMasks[Triangle]);
for(std::size_t Triangle=0;Triangle<NewTriangles.size()/3;++Triangle)
CombinedFaceMasks.Add(0);
for(int32 Triangle=CeilingStart/3;Triangle<OldTriangleCount;++Triangle)
CombinedFaceMasks.Add(ExistingFaceMasks[Triangle]);
Mesh.Triangles=std::move(CombinedTriangles);
Mesh.TriangleSkirtFaceMasks=std::move(CombinedFaceMasks);
Mesh.NumSurfaceVertices=OldSurfaceVertices+AddedVertices;
Mesh.NumCeilingTriangles+=static_cast<int32>(NewTriangles.size()/3);
}
// Add the interior-facing top of each bedrock band. The density composition already
// makes this band solid and editable; this planar closure keeps its visible floor
// continuous when a coarse marching-cubes step would otherwise skip a sub-voxel band.
inline void AppendStratumBoundaryFloors(const FStandaloneOwnerWorld& World,
const FStandaloneShapeWorld& Shape,const FVoxelTileKey& Key,int32 Step,FVoxelMeshData& Mesh)
{
if(Key.Level<0||Step<=0||!World.Manager||!Shape.ResolvedLayout)return;
const FIntVector Origin=Key.OriginVoxels();
const int32 Extent=Key.ExtentVoxels();
if(Extent<=0||Extent%Step!=0)return;
const int32 GridSide=Extent/Step+1;
struct FCandidate { double FloorZ=0.0; double Thickness=0.0; };
std::vector<FCandidate> Candidates;
const double CoreMicrons=std::max<std::uint32_t>(1,World.CoreVoxelSizeMicrons);
for(const FStrateSlot& Slot:World.Manager->GetLayout())
{
const auto* Stratum=Shape.FindResolvedLayoutStratum(Slot.StrateIndex);
if(!Stratum||!Stratum->bedrock.presentInCurrentField
||Stratum->bedrock.topMicrometres<=Stratum->bedrock.bottomMicrometres)continue;
const double FloorZ=static_cast<double>(Stratum->bedrock.topMicrometres)/CoreMicrons;
if(FloorZ<Origin.Z-1.0e-6||FloorZ>Origin.Z+Extent+1.0e-6)continue;
Candidates.push_back({FloorZ,static_cast<double>(Stratum->bedrock.topMicrometres
-Stratum->bedrock.bottomMicrometres)/CoreMicrons});
}
if(Candidates.empty())return;
const int32 Cells=std::max(1,World.CoarseTileCells);
FFarMeshColumnIndex MeshIndex(Mesh,Origin,Extent,Cells,Step,
static_cast<double>(World.CoreVoxelSizeMicrons)/10000.0);
const int32 OldVertexCount=Mesh.Vertices.Num();
const int32 OldSurfaceVertices=std::clamp(Mesh.NumSurfaceVertices,0,OldVertexCount);
const bool bHasUVs=Mesh.UVs.Num()==OldVertexCount;
const bool bHasColors=Mesh.Colors.Num()==OldVertexCount;
const FColor Color=bHasColors&&OldVertexCount>0?Mesh.Colors[0]:FColor(160,160,160,255);
const double VoxelSizeCm=static_cast<double>(World.CoreVoxelSizeMicrons)/10000.0;
std::vector<FVector> NewVertices,NewNormals;
std::vector<FVector2f> NewUVs;
std::vector<FColor> NewColors;
std::vector<int32> NewTriangles;
for(const FCandidate& Candidate:Candidates)
{
const double Epsilon=std::min(0.5,Candidate.Thickness*0.25);
if(Epsilon<=0.0)continue;
std::vector<uint8> SolidBelow(static_cast<std::size_t>(GridSide)*GridSide,0);
for(int32 Y=0;Y<GridSide;++Y)for(int32 X=0;X<GridSide;++X)
{
const double WorldX=Origin.X+X*Step,WorldY=Origin.Y+Y*Step;
const float Density=Shape.DensityAt(static_cast<float>(WorldX),static_cast<float>(WorldY),
static_cast<float>(Candidate.FloorZ-Epsilon));
SolidBelow[static_cast<std::size_t>(Y*GridSide+X)]=
std::isfinite(Density)&&Density<0.0f?1:0;
}
std::vector<int32> VertexMap(static_cast<std::size_t>(GridSide)*GridSide,INDEX_NONE);
const auto AddVertex=[&](int32 X,int32 Y)
{
const std::size_t GridIndex=static_cast<std::size_t>(Y*GridSide+X);
int32& Mapped=VertexMap[GridIndex];
if(Mapped!=INDEX_NONE)return Mapped;
Mapped=static_cast<int32>(NewVertices.size());
const double WorldX=Origin.X+X*Step,WorldY=Origin.Y+Y*Step;
NewVertices.emplace_back(WorldX*VoxelSizeCm,WorldY*VoxelSizeCm,
Candidate.FloorZ*VoxelSizeCm);
NewNormals.emplace_back(0.0,0.0,1.0);
if(bHasUVs)NewUVs.emplace_back(static_cast<float>(WorldX),static_cast<float>(WorldY));
if(bHasColors)NewColors.push_back(Color);
return Mapped;
};
for(int32 Y=0;Y+1<GridSide;++Y)for(int32 X=0;X+1<GridSide;++X)
{
const std::size_t I00=static_cast<std::size_t>(Y*GridSide+X);
const std::size_t I10=I00+1,I01=I00+GridSide,I11=I01+1;
if(!SolidBelow[I00]||!SolidBelow[I10]||!SolidBelow[I01]||!SolidBelow[I11])continue;
const double X0=Origin.X+X*Step,Y0=Origin.Y+Y*Step;
const double X1=X0+Step,Y1=Y0+Step;
if(MeshIndex.HasUpwardCellCoverage(X0,Y0,X1,Y1,Candidate.FloorZ,0.001))continue;
const int32 A=AddVertex(X,Y),B=AddVertex(X+1,Y);
const int32 C=AddVertex(X+1,Y+1),D=AddVertex(X,Y+1);
NewTriangles.insert(NewTriangles.end(),{A,B,C,A,C,D});
}
}
if(NewTriangles.empty())return;
const int32 AddedVertices=static_cast<int32>(NewVertices.size());
auto InsertVertices=[&](auto& Existing,const auto& Added)
{
using TArrayType=std::remove_reference_t<decltype(Existing)>;
TArrayType Combined;Combined.Reserve(Existing.Num()+static_cast<int32>(Added.size()));
for(int32 I=0;I<OldSurfaceVertices;++I)Combined.Add(Existing[I]);
for(const auto& Value:Added)Combined.Add(Value);
for(int32 I=OldSurfaceVertices;I<Existing.Num();++I)Combined.Add(Existing[I]);
Existing=std::move(Combined);
};
InsertVertices(Mesh.Vertices,NewVertices);InsertVertices(Mesh.Normals,NewNormals);
if(bHasUVs)InsertVertices(Mesh.UVs,NewUVs);
if(bHasColors)InsertVertices(Mesh.Colors,NewColors);
for(int32& Index:Mesh.Triangles)if(Index>=OldSurfaceVertices)Index+=AddedVertices;
const int32 CeilingStart=std::max(0,Mesh.Triangles.Num()-Mesh.NumCeilingTriangles*3);
TArray<int32> CombinedTriangles;CombinedTriangles.Reserve(
Mesh.Triangles.Num()+static_cast<int32>(NewTriangles.size()));
for(int32 I=0;I<CeilingStart;++I)CombinedTriangles.Add(Mesh.Triangles[I]);
for(const int32 Index:NewTriangles)CombinedTriangles.Add(OldSurfaceVertices+Index);
for(int32 I=CeilingStart;I<Mesh.Triangles.Num();++I)CombinedTriangles.Add(Mesh.Triangles[I]);
const int32 OldTriangleCount=Mesh.Triangles.Num()/3;
TArray<uint8> ExistingFaceMasks=Mesh.TriangleSkirtFaceMasks;
ExistingFaceMasks.SetNum(OldTriangleCount);
TArray<uint8> CombinedFaceMasks;CombinedFaceMasks.Reserve(
OldTriangleCount+static_cast<int32>(NewTriangles.size()/3));
for(int32 Triangle=0;Triangle<CeilingStart/3;++Triangle)
CombinedFaceMasks.Add(ExistingFaceMasks[Triangle]);
for(std::size_t Triangle=0;Triangle<NewTriangles.size()/3;++Triangle)
CombinedFaceMasks.Add(0);
for(int32 Triangle=CeilingStart/3;Triangle<OldTriangleCount;++Triangle)
CombinedFaceMasks.Add(ExistingFaceMasks[Triangle]);
Mesh.Triangles=std::move(CombinedTriangles);
Mesh.TriangleSkirtFaceMasks=std::move(CombinedFaceMasks);
Mesh.NumSurfaceVertices=OldSurfaceVertices+AddedVertices;
}
+12 -155
View File
@@ -170,8 +170,6 @@ namespace floating_island_detail
HashWord(hash, static_cast<std::uint64_t>(recipe.layoutCenterTopZSubvoxels), 8);
HashWord(hash, static_cast<std::uint64_t>(recipe.layoutMinimumZSubvoxels), 8);
HashWord(hash, static_cast<std::uint64_t>(recipe.layoutMaximumZSubvoxels), 8);
if(recipe.geometryVersion>=4)
HashWord(hash,static_cast<std::uint64_t>(recipe.layoutChunkWidthSubvoxels),8);
HashWord(hash, recipe.primaryIslandCount, 4);
HashWord(hash, static_cast<std::uint64_t>(recipe.islandDensityQ16), 8);
HashWord(hash, static_cast<std::uint64_t>(recipe.spacingSubvoxels), 8);
@@ -188,15 +186,6 @@ namespace floating_island_detail
HashWord(hash, static_cast<std::uint64_t>(recipe.crustDepthBonusQ16), 8);
HashWord(hash, static_cast<std::uint64_t>(recipe.rootDepthRatioQ16), 8);
}
if (recipe.geometryVersion >= 5)
{
HashWord(hash, recipe.anchorIslandOrdinal, 4);
HashWord(hash, static_cast<std::uint64_t>(recipe.anchorPlacementRadiusSubvoxels), 8);
HashWord(hash, static_cast<std::uint64_t>(recipe.anchorRootRadiusSubvoxels), 8);
HashWord(hash, static_cast<std::uint64_t>(recipe.anchorIslandMinimumRadiusSubvoxels), 8);
HashWord(hash, static_cast<std::uint64_t>(recipe.anchorRootBottomZSubvoxels), 8);
HashWord(hash, static_cast<std::uint64_t>(recipe.anchorMouthOffsetSubvoxels), 8);
}
HashWord(hash, static_cast<std::uint64_t>(recipe.blendRadiusSubvoxels), 8);
HashWord(hash, static_cast<std::uint64_t>(recipe.contourWarpSubvoxels), 8);
HashWord(hash, static_cast<std::uint64_t>(recipe.roughnessSubvoxels), 8);
@@ -256,10 +245,10 @@ namespace floating_island_detail
inline bool ValidateRecipe(const FloatingIslandRecipeV1& recipe, std::string& error)
{
const std::array<std::int64_t, 32> values = {
const std::array<std::int64_t, 25> values = {
recipe.layoutOriginXSubvoxels, recipe.layoutOriginYSubvoxels,
recipe.layoutCenterTopZSubvoxels, recipe.layoutMinimumZSubvoxels,
recipe.layoutMaximumZSubvoxels, recipe.layoutChunkWidthSubvoxels, recipe.islandDensityQ16,
recipe.layoutMaximumZSubvoxels, recipe.islandDensityQ16,
recipe.spacingSubvoxels, recipe.minimumRadiusSubvoxels,
recipe.maximumRadiusSubvoxels, recipe.thicknessRatioQ16,
recipe.verticalJitterQ16, recipe.topFlattenQ16,
@@ -268,10 +257,6 @@ namespace floating_island_detail
recipe.blendRadiusSubvoxels, recipe.contourWarpSubvoxels,
recipe.roughnessSubvoxels, recipe.boundarySealSubvoxels,
recipe.bridgeHalfWidthSubvoxels, recipe.bridgeThicknessSubvoxels,
static_cast<std::int64_t>(recipe.anchorIslandOrdinal),
recipe.anchorPlacementRadiusSubvoxels, recipe.anchorRootRadiusSubvoxels,
recipe.anchorIslandMinimumRadiusSubvoxels, recipe.anchorRootBottomZSubvoxels,
recipe.anchorMouthOffsetSubvoxels,
recipe.routeConstraints.capsuleRadiusSubvoxels,
recipe.routeConstraints.capsuleHeightSubvoxels,
recipe.routeConstraints.maximumGradeQ16};
@@ -281,7 +266,7 @@ namespace floating_island_detail
? recipe.ownerVoxelSizeMicrons / ScaleGcd : 0;
const std::uint32_t ExpectedDenominator = ScaleGcd > 0
? recipe.coreVoxelSizeMicrons / ScaleGcd : 0;
if (recipe.schemaVersion != 1 || recipe.geometryVersion < 1 || recipe.geometryVersion > 5
if (recipe.schemaVersion != 1 || (recipe.geometryVersion != 1 && recipe.geometryVersion != 2)
|| (recipe.geometryVersion == 1
&& (recipe.crustDepthBonusQ16 != 0 || recipe.rootDepthRatioQ16 != 0))
|| recipe.unitsPerVoxel != Q
@@ -290,11 +275,6 @@ namespace floating_island_detail
|| recipe.ownerToCoreScaleNumerator != ExpectedNumerator
|| recipe.ownerToCoreScaleDenominator != ExpectedDenominator
|| recipe.primaryIslandCount < 3 || recipe.primaryIslandCount > 9
|| recipe.layoutChunkWidthSubvoxels <= 0
|| static_cast<long double>(recipe.layoutChunkWidthSubvoxels)*recipe.coreVoxelSizeMicrons
< 250000.0L*Q
|| static_cast<long double>(recipe.layoutChunkWidthSubvoxels)*recipe.coreVoxelSizeMicrons
> 64000000.0L*Q
|| recipe.layoutMaximumZSubvoxels <= recipe.layoutMinimumZSubvoxels
|| recipe.layoutMaximumZSubvoxels - recipe.layoutMinimumZSubvoxels > 2048 * Q
|| std::any_of(values.begin(), values.end(), [](auto value) { return !ValidScalar(value); }))
@@ -336,21 +316,6 @@ namespace floating_island_detail
|| constraints.minimumClearanceSubvoxels < 0
|| constraints.minimumSupportProbes == 0 || constraints.minimumSupportProbes > 5)
{ error = "floating-island shape or route parameters are outside the supported range"; return false; }
if (recipe.geometryVersion >= 5
&& (recipe.anchorIslandOrdinal != recipe.primaryIslandCount - 1
|| recipe.anchorPlacementRadiusSubvoxels <= 0
|| recipe.anchorRootRadiusSubvoxels < recipe.anchorMouthOffsetSubvoxels
+ recipe.routeConstraints.capsuleRadiusSubvoxels + Q
|| recipe.anchorIslandMinimumRadiusSubvoxels
< recipe.anchorMouthOffsetSubvoxels
+ recipe.routeConstraints.capsuleRadiusSubvoxels + Q
|| recipe.anchorIslandMinimumRadiusSubvoxels > 64 * Q
|| recipe.anchorRootBottomZSubvoxels < recipe.layoutMinimumZSubvoxels
+ recipe.boundarySealSubvoxels
|| recipe.anchorRootBottomZSubvoxels >= recipe.layoutCenterTopZSubvoxels
|| recipe.anchorMouthOffsetSubvoxels <= 0
|| recipe.anchorMouthOffsetSubvoxels > 64 * Q))
{ error = "floating-island bedrock anchor is outside its passage or rock-thickness bounds"; return false; }
return true;
}
@@ -753,25 +718,6 @@ namespace floating_island_detail
const double rootBlend = std::clamp(radius * 0.12, 2.0 * Q, 5.0 * Q);
for (std::int32_t root = 0; root < rootCount; ++root)
sdf = SmoothMin(sdf, RootLobeDensity(recipe, island, root, x, y, z), rootBlend);
if (recipe.geometryVersion >= 5 && island.ordinal == recipe.anchorIslandOrdinal
&& recipe.anchorRootBottomZSubvoxels < island.bottomZSubvoxels)
{
const double rootTop = static_cast<double>(island.bottomZSubvoxels);
const double rootBottom = static_cast<double>(recipe.anchorRootBottomZSubvoxels);
const double depth = std::max(1.0, rootTop - rootBottom);
const double blend = std::clamp(static_cast<double>(recipe.anchorRootRadiusSubvoxels)
* 0.12, 3.0 * Q, 6.0 * Q);
// A slightly flared lower buttress joins the island's own root lobes to bedrock.
// Une base legerement evasee relie les racines de l'ile a la roche de fond.
const double t = std::clamp((rootTop - z) / depth, 0.0, 1.0);
const double rootRadius = static_cast<double>(recipe.anchorRootRadiusSubvoxels)
* (0.92 + 0.08 * SmoothStep(t));
double rootSdf = std::max({Column.Radial - rootRadius,
rootBottom - z, z - rootTop});
rootSdf = ApplySurfaceDetail(recipe, island.stableId ^ 0x414e43484f52524full,
rootSdf, x, y, z, 0.75);
sdf = SmoothMin(sdf, rootSdf, blend);
}
const double topDetailScale = topDistance >= std::max(sideDistance, undersideDistance)
|| z >= static_cast<double>(IslandCrustBottom(recipe, island)) + radius * 0.45
? 0.25 : 1.0;
@@ -942,15 +888,9 @@ namespace floating_island_detail
FloatingIslandAnchorV1& island)
{
const std::int64_t pad = IslandBlendMargin(recipe) + recipe.roughnessSubvoxels;
const bool isAnchor=recipe.geometryVersion>=5
&&island.ordinal==recipe.anchorIslandOrdinal;
const std::int64_t reach = std::max(island.radiusSubvoxels,
isAnchor?recipe.anchorRootRadiusSubvoxels:std::int64_t{0})
+ recipe.contourWarpSubvoxels + pad;
const std::int64_t reach = island.radiusSubvoxels + recipe.contourWarpSubvoxels + pad;
island.influenceMinimumSubvoxels = {island.centerSubvoxels[0] - reach,
island.centerSubvoxels[1] - reach,
(isAnchor?std::min(island.bottomZSubvoxels,recipe.anchorRootBottomZSubvoxels)
:island.bottomZSubvoxels)-pad};
island.centerSubvoxels[1] - reach, island.bottomZSubvoxels - pad};
island.influenceMaximumSubvoxels = {island.centerSubvoxels[0] + reach,
island.centerSubvoxels[1] + reach, island.topZSubvoxels + pad};
}
@@ -995,19 +935,12 @@ namespace floating_island_detail
std::unordered_set<std::uint64_t> islandIds;
std::unordered_set<std::uint32_t> ordinals;
const FloatingIslandAnchorV1* anchorIsland = nullptr;
for (const auto& island : plan.islands)
{
const bool isAnchor=recipe.geometryVersion>=5
&&island.ordinal==recipe.anchorIslandOrdinal;
if(isAnchor)anchorIsland=&island;
if (island.stableId == 0 || !islandIds.insert(island.stableId).second
|| !ordinals.insert(island.ordinal).second
|| island.radiusSubvoxels < (isAnchor?recipe.anchorIslandMinimumRadiusSubvoxels
:recipe.minimumRadiusSubvoxels)
|| island.radiusSubvoxels > (isAnchor
?std::max(recipe.anchorIslandMinimumRadiusSubvoxels,recipe.maximumRadiusSubvoxels)
:recipe.maximumRadiusSubvoxels)
|| island.radiusSubvoxels < recipe.minimumRadiusSubvoxels
|| island.radiusSubvoxels > recipe.maximumRadiusSubvoxels
|| island.topHalfSubvoxels <= 0 || island.topZSubvoxels <= island.bottomZSubvoxels
|| island.taperEndQ16 < recipe.taperEndMinimumQ16
|| island.taperEndQ16 > recipe.taperEndMaximumQ16
@@ -1024,16 +957,12 @@ namespace floating_island_detail
{ error = "floating-island anchor has invalid coordinates or an inverted bound"; return false; }
}
const std::int64_t pad = IslandBlendMargin(recipe) + recipe.roughnessSubvoxels;
const std::int64_t reach = std::max(island.radiusSubvoxels,
isAnchor?recipe.anchorRootRadiusSubvoxels:std::int64_t{0})
+ recipe.contourWarpSubvoxels + pad;
const std::int64_t reach = island.radiusSubvoxels + recipe.contourWarpSubvoxels + pad;
if (island.influenceMinimumSubvoxels[0] > island.centerSubvoxels[0] - reach
|| island.influenceMaximumSubvoxels[0] < island.centerSubvoxels[0] + reach
|| island.influenceMinimumSubvoxels[1] > island.centerSubvoxels[1] - reach
|| island.influenceMaximumSubvoxels[1] < island.centerSubvoxels[1] + reach
|| island.influenceMinimumSubvoxels[2] > (isAnchor
?std::min(island.bottomZSubvoxels,recipe.anchorRootBottomZSubvoxels)
:island.bottomZSubvoxels) - pad
|| island.influenceMinimumSubvoxels[2] > island.bottomZSubvoxels - pad
|| island.influenceMaximumSubvoxels[2] < island.topZSubvoxels + pad
|| island.bottomZSubvoxels < recipe.layoutMinimumZSubvoxels + recipe.boundarySealSubvoxels
|| island.topZSubvoxels > recipe.layoutMaximumZSubvoxels - recipe.boundarySealSubvoxels)
@@ -1042,19 +971,6 @@ namespace floating_island_detail
for (std::uint32_t ordinal = 0; ordinal < recipe.primaryIslandCount; ++ordinal)
if (!ordinals.contains(ordinal))
{ error = "floating-island route chain is missing a primary seeded anchor"; return false; }
if(recipe.geometryVersion>=5)
{
if(!anchorIsland)
{error="floating-island plan is missing its unique passage anchor island";return false;}
const double anchorDistance=std::hypot(
static_cast<double>(anchorIsland->centerSubvoxels[0]),
static_cast<double>(anchorIsland->centerSubvoxels[1]));
if(anchorDistance>recipe.anchorPlacementRadiusSubvoxels
||recipe.anchorRootBottomZSubvoxels>=anchorIsland->bottomZSubvoxels
||recipe.anchorMouthOffsetSubvoxels+recipe.routeConstraints.capsuleRadiusSubvoxels
>=anchorIsland->radiusSubvoxels)
{error="floating-island anchor island or its mouth leaves the passage radius or rock envelope";return false;}
}
std::unordered_set<std::uint64_t> edgeIds;
std::unordered_map<std::uint64_t, std::vector<std::uint64_t>> adjacency;
@@ -1280,8 +1196,7 @@ namespace floating_island_detail
}
std::optional<FloatingIslandManifestV1> FloatingIslandManifestV1::FromJson(
std::string_view json, std::string& error,
std::int64_t resolvedLayoutChunkWidthSubvoxels)
std::string_view json, std::string& error)
{
VFJson::Value root;
if (!VFJson::Parser(std::string(json)).Parse(root, error)) return std::nullopt;
@@ -1307,31 +1222,6 @@ std::optional<FloatingIslandManifestV1> FloatingIslandManifestV1::FromJson(
manifest.recipe.crustDepthBonusQ16 = 0;
manifest.recipe.rootDepthRatioQ16 = 0;
}
if(manifest.recipe.geometryVersion>=4)
{
if(!floating_island_detail::ReadInteger(recipeValue.Get("layout_chunk_width_q"),
manifest.recipe.layoutChunkWidthSubvoxels))
{error="floating-island recipe is missing its resolved layout chunk width";return std::nullopt;}
if(resolvedLayoutChunkWidthSubvoxels>0
&& manifest.recipe.layoutChunkWidthSubvoxels!=resolvedLayoutChunkWidthSubvoxels)
{error="floating-island recipe layout width disagrees with the resolved world layout";return std::nullopt;}
}
if(manifest.recipe.geometryVersion>=5)
{
if(!floating_island_detail::ReadU32(recipeValue.Get("anchor_island_ordinal"),
manifest.recipe.anchorIslandOrdinal)
||!floating_island_detail::ReadInteger(recipeValue.Get("anchor_placement_radius_q"),
manifest.recipe.anchorPlacementRadiusSubvoxels)
||!floating_island_detail::ReadInteger(recipeValue.Get("anchor_root_radius_q"),
manifest.recipe.anchorRootRadiusSubvoxels)
||!floating_island_detail::ReadInteger(recipeValue.Get("anchor_island_minimum_radius_q"),
manifest.recipe.anchorIslandMinimumRadiusSubvoxels)
||!floating_island_detail::ReadInteger(recipeValue.Get("anchor_root_bottom_z_q"),
manifest.recipe.anchorRootBottomZSubvoxels)
||!floating_island_detail::ReadInteger(recipeValue.Get("anchor_mouth_offset_q"),
manifest.recipe.anchorMouthOffsetSubvoxels))
{error="floating-island geometry version 5 is missing a passage-rooted anchor field";return std::nullopt;}
}
if (!floating_island_detail::ReadU32(root.Get("schema_version"), schema)
|| !floating_island_detail::ReadHash(root.Get("content_hash"), manifestHash)
|| !floating_island_detail::ReadU32(recipeValue.Get("schema_version"), manifest.recipe.schemaVersion)
@@ -1367,10 +1257,6 @@ std::optional<FloatingIslandManifestV1> FloatingIslandManifestV1::FromJson(
|| !floating_island_detail::ReadHash(planValue.Get("content_hash"), planHash)
|| schema != 1)
{ error = "floating-island manifest is missing a required versioned recipe or plan field"; return std::nullopt; }
if(manifest.recipe.geometryVersion<4 && resolvedLayoutChunkWidthSubvoxels>0)
manifest.recipe.layoutChunkWidthSubvoxels=resolvedLayoutChunkWidthSubvoxels;
else if(manifest.recipe.geometryVersion<4)
{ error="legacy floating-island manifest requires the world's resolved layout chunk width"; return std::nullopt; }
manifest.recipe.contentHash = recipeHash;
manifest.contentHash = manifestHash;
manifest.plan.contentHash = planHash;
@@ -1482,15 +1368,6 @@ std::string FloatingIslandManifestV1::ToJson() const
out << ",\"geometry_version\":" << recipe.geometryVersion
<< ",\"crust_depth_bonus_q16\":" << recipe.crustDepthBonusQ16
<< ",\"root_depth_ratio_q16\":" << recipe.rootDepthRatioQ16;
if(recipe.geometryVersion>=4)
out << ",\"layout_chunk_width_q\":" << recipe.layoutChunkWidthSubvoxels;
if(recipe.geometryVersion>=5)
out << ",\"anchor_island_ordinal\":" << recipe.anchorIslandOrdinal
<< ",\"anchor_placement_radius_q\":" << recipe.anchorPlacementRadiusSubvoxels
<< ",\"anchor_root_radius_q\":" << recipe.anchorRootRadiusSubvoxels
<< ",\"anchor_island_minimum_radius_q\":" << recipe.anchorIslandMinimumRadiusSubvoxels
<< ",\"anchor_root_bottom_z_q\":" << recipe.anchorRootBottomZSubvoxels
<< ",\"anchor_mouth_offset_q\":" << recipe.anchorMouthOffsetSubvoxels;
out << ",\"blend_radius_q\":" << recipe.blendRadiusSubvoxels
<< ",\"contour_warp_q\":" << recipe.contourWarpSubvoxels
<< ",\"roughness_q\":" << recipe.roughnessSubvoxels
@@ -1652,9 +1529,6 @@ std::optional<FloatingIslandManifestV1> PlanFloatingIslandCluster(
auto island = floating_island_detail::MakeIsland(recipe, i,
primaryXY[i][0], primaryXY[i][1], tops[i], site);
island.radiusSubvoxels = radii[i];
if(recipe.geometryVersion>=5&&i==recipe.anchorIslandOrdinal)
island.radiusSubvoxels=std::max(island.radiusSubvoxels,
recipe.anchorIslandMinimumRadiusSubvoxels);
island.topHalfSubvoxels = std::max<std::int64_t>(1, island.radiusSubvoxels / 5);
island.centerSubvoxels[2] = island.topZSubvoxels - island.topHalfSubvoxels;
island.bottomZSubvoxels = floating_island_detail::IslandBottom(recipe,
@@ -1741,31 +1615,14 @@ std::optional<FloatingIslandManifestV1> PlanFloatingIslandCluster(
static_cast<double>(a.centerSubvoxels[0]) + dx * t);
const std::int64_t y = floating_island_detail::RoundQ(
static_cast<double>(a.centerSubvoxels[1]) + dy * t);
std::int64_t routeX=x,routeY=y;
if(recipe.geometryVersion>=5&&segment+2==count&&piece==pieces)
{
const auto& anchor=islands[recipe.anchorIslandOrdinal];
const std::uint32_t side=static_cast<std::uint32_t>(
floating_island_detail::UnitQ16(recipe.seed,anchor.stableId,
0x414e43484f524d50ull)&1u);
const double routeAngle=std::atan2(dy,dx);
const double angle=routeAngle+(side?1.0:-1.0)
*floating_island_detail::Pi/2.0;
const double mouthX=static_cast<double>(anchor.centerSubvoxels[0])
+static_cast<double>(recipe.anchorMouthOffsetSubvoxels)*std::cos(angle);
const double mouthY=static_cast<double>(anchor.centerSubvoxels[1])
+static_cast<double>(recipe.anchorMouthOffsetSubvoxels)*std::sin(angle);
routeX=floating_island_detail::RoundQ(mouthX);
routeY=floating_island_detail::RoundQ(mouthY);
}
const auto surface = floating_island_detail::FindCapsuleFootingTopZ(
recipe, manifest.plan, routeX, routeY);
recipe, manifest.plan, x, y);
if (!surface)
{ error = "island planner could not find a full capsule-width support surface along its connector chain"; return std::nullopt; }
WorldAssemblyRoutePointV1 point;
point.stableFeatureId = floating_island_detail::StableId(recipe.seed,
0x500000000ull + routeOrdinal, 0x524f555445ull);
point.positionSubvoxels = {routeX, routeY, *surface + capsuleHalf
point.positionSubvoxels = {x, y, *surface + capsuleHalf
+ recipe.routeConstraints.minimumClearanceSubvoxels
+ (recipe.geometryVersion >= 2 ? floating_island_detail::Q / 8 : 0)};
point.radiusSubvoxels = routeRadius;
File diff suppressed because it is too large. Load diff
+100 -548
View File
@@ -5,7 +5,6 @@
#include "VoxelCaveMorphology.h"
#include "VoxelNoise.h"
#include "VoxelStrateManager.h"
#include "VoxelDensityPrimitives.h"
#include "VoxelForgeCore/VoxelForgeCore.h"
#include "VoxelForgeFieldShared.h"
@@ -33,14 +32,6 @@
class FStandaloneShapeWorld
{
public:
const VoxelForgeCore::ResolvedLayoutSnapshotV3* ResolvedLayout=nullptr;
struct FResolvedStratumBounds
{
double BottomZ=0.0;
double TopZ=0.0;
double SealThickness=0.0;
};
double GetCoreVoxelSizeCm() const
{
return Owner == nullptr || Owner->CoreVoxelSizeMicrons == 0
@@ -48,362 +39,12 @@ public:
: static_cast<double>(Owner->CoreVoxelSizeMicrons) / 10000.0;
}
double GetResolvedLayoutChunkWidthVoxels() const
double GetCoreVoxelsPerOwnerChunk() const
{
return ResolvedLayout&&ResolvedLayout->strateLayoutChunkWidthSubvoxels>0
?static_cast<double>(ResolvedLayout->strateLayoutChunkWidthSubvoxels)
/VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel
:Owner?static_cast<double>(Owner->StrateLayoutChunkWidthSubvoxels)
/VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel:0.0;
}
const VoxelForgeCore::ResolvedLayoutStratumV2* FindResolvedLayoutStratum(int32 StrateIndex) const
{
if(!ResolvedLayout)return nullptr;
const auto it=std::find_if(ResolvedLayout->strates.begin(),ResolvedLayout->strates.end(),
[StrateIndex](const auto& item){return item.strateIndex==StrateIndex;});
return it==ResolvedLayout->strates.end()?nullptr:&*it;
}
bool IsInsideResolvedStrateBoundaryBand(float Z) const
{
if(!ResolvedLayout||!Owner||!Owner->Manager||!std::isfinite(Z))return false;
const double worldZCentimetres=static_cast<double>(Z)*GetCoreVoxelSizeCm();
const int32 strateIndex=Owner->Manager->GetStrateIndex(static_cast<float>(worldZCentimetres));
const auto* stratum=FindResolvedLayoutStratum(strateIndex);
if(!stratum)return false;
const double zMicrometres=static_cast<double>(Z)*Owner->CoreVoxelSizeMicrons;
const auto solidAt=[&](const VoxelForgeCore::ResolvedLayoutBandV2& band)
{return band.presentInCurrentField&&zMicrometres>=band.bottomMicrometres
&&zMicrometres<band.topMicrometres;};
return solidAt(stratum->ceiling)||solidAt(stratum->bedrock);
}
float ApplyResolvedStrateBoundaryBand(float density,float X,float Y,float Z) const
{
(void)X;(void)Y;
if(!ResolvedLayout||!Owner||!Owner->Manager||!std::isfinite(Z))return density;
const double worldZCentimetres=static_cast<double>(Z)*GetCoreVoxelSizeCm();
const int32 strateIndex=Owner->Manager->GetStrateIndex(static_cast<float>(worldZCentimetres));
const auto* stratum=FindResolvedLayoutStratum(strateIndex);
if(!stratum)return density;
const double zMicrometres=static_cast<double>(Z)*Owner->CoreVoxelSizeMicrons;
const auto solidAt=[&](const VoxelForgeCore::ResolvedLayoutBandV2& band)
{return band.presentInCurrentField&&zMicrometres>=band.bottomMicrometres
&&zMicrometres<band.topMicrometres;};
const auto* band=solidAt(stratum->ceiling)?&stratum->ceiling
:solidAt(stratum->bedrock)?&stratum->bedrock:nullptr;
if(!band)return density;
return -std::max(0.05f,static_cast<float>(band->solidDensityQ16)/65536.0f);
}
float ApplyResolvedStratePassageCarves(float density,float X,float Y,float Z) const
{
if(!ResolvedLayout||ResolvedLayout->passages.empty()||!std::isfinite(X)
||!std::isfinite(Y)||!std::isfinite(Z))return density;
constexpr double Q=static_cast<double>(VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel);
const double qx=static_cast<double>(X)*Q,qy=static_cast<double>(Y)*Q,qz=static_cast<double>(Z)*Q;
const double qPerMetre=Q*1000000.0/std::max<std::uint32_t>(1,ResolvedLayout->coreVoxelSizeMicrometres);
const double floorThicknessVoxels=qPerMetre/Q;
const double playerCenterAboveFloorQ=1.13*qPerMetre;
float composed=density;
const auto composeRouteMouthSupport=[&](std::int32_t strateIndex,
const std::array<std::int64_t,3>& mouth,bool departure)
{
const double mouthDx=qx-static_cast<double>(mouth[0]);
const double mouthDy=qy-static_cast<double>(mouth[1]);
const double routeSupportReach=13.0*qPerMetre;
if(mouthDx*mouthDx+mouthDy*mouthDy>routeSupportReach*routeSupportReach)return;
const auto stratum=std::find_if(ResolvedLayout->strates.begin(),
ResolvedLayout->strates.end(),[strateIndex](const auto& value)
{return value.strateIndex==strateIndex;});
if(stratum==ResolvedLayout->strates.end())return;
std::array<const VoxelForgeCore::ResolvedLayoutAnchorV2*,5> route{};
std::size_t routeCount=0;
for(const auto& anchor:stratum->anchors)
if(anchor.kind=="route_point"&&anchor.values.size()>=3)
{
if(departure)
{
if(routeCount<route.size())route[routeCount++]=&anchor;
else
{
std::move(route.begin()+1,route.end(),route.begin());
route.back()=&anchor;
}
}
else if(routeCount<route.size())route[routeCount++]=&anchor;
}
if(routeCount<2)return;
const std::size_t lastSegment=routeCount-1;
const double floorThickness=1000000.0/std::max<std::uint32_t>(1,
ResolvedLayout->coreVoxelSizeMicrometres);
for(std::size_t index=0;index<lastSegment;++index)
{
const auto& a=*route[index];const auto& b=*route[index+1];
const double dx=static_cast<double>(b.values[0]-a.values[0]);
const double dy=static_cast<double>(b.values[1]-a.values[1]);
const double lengthSq=dx*dx+dy*dy;
const double t=lengthSq>0.0?std::clamp(((qx-a.values[0])*dx
+(qy-a.values[1])*dy)/lengthSq,0.0,1.0):0.0;
const double centerX=a.values[0]+t*dx,centerY=a.values[1]+t*dy;
const double centerZ=a.values[2]+t*(static_cast<double>(b.values[2])-a.values[2]);
const double routeRadius=a.values.size()>=4
?a.values[3]+t*(static_cast<double>(b.values[3])-a.values[3]):0.0;
const double halfWidth=std::max(0.75*qPerMetre,routeRadius);
const double horizontalX=qx-centerX,horizontalY=qy-centerY;
if(horizontalX*horizontalX+horizontalY*horizontalY>halfWidth*halfWidth)continue;
const double floorVoxels=(centerZ-1.20*qPerMetre)/Q;
if(Z<floorVoxels-floorThickness||Z>floorVoxels+1.0/Q)continue;
composed=std::min(composed,static_cast<float>(
std::clamp(Z-floorVoxels,-floorThickness,0.0)));
}
};
// Seed the route floor first. The bore carve below reopens any overlap at the
// mouth, then applies its own lower tread, so neither shape blocks the capsule.
for(const auto& passage:ResolvedLayout->passages)
{
composeRouteMouthSupport(passage.upperStrateIndex,passage.upperMouthSubvoxels,true);
// The lower mouth emerges into its native terrain. Keep the passage tread
// support, but do not stamp short, flat route-anchor shelves over that cave mouth.
}
for(const auto& passage:ResolvedLayout->passages)
{
if(passage.controlPoints.size()<2)continue;
const double placementRadiusQ=static_cast<double>(passage.placementRadiusSubvoxels)
+static_cast<double>(passage.midRadiusSubvoxels);
if(qx*qx+qy*qy>placementRadiusQ*placementRadiusQ)continue;
const double firstFloorQ=passage.controlPoints.front().positionSubvoxels[2]
-passage.controlPoints.front().radiusSubvoxels+playerCenterAboveFloorQ;
const double lastFloorQ=passage.controlPoints.back().positionSubvoxels[2]
-passage.controlPoints.back().radiusSubvoxels+playerCenterAboveFloorQ;
if(qz>firstFloorQ+2.0*passage.mouthRadiusSubvoxels
||qz<lastFloorQ-2.0*passage.mouthRadiusSubvoxels)continue;
const auto floorProfile=[&](const auto& point)
{return point.positionSubvoxels[2]-point.radiusSubvoxels+playerCenterAboveFloorQ;};
const std::ptrdiff_t lastIndex=static_cast<std::ptrdiff_t>(passage.controlPoints.size())-1;
const std::ptrdiff_t lowerMouthIndex=std::clamp<std::ptrdiff_t>(
static_cast<std::ptrdiff_t>(passage.lowerMouthControlIndex),1,lastIndex);
const auto mainEnd=passage.controlPoints.begin()+lowerMouthIndex+1;
// The tube radius is measured from its centerline, while floorProfile is
// one player-center offset away. Search the full vertical radius of the SDF;
// a narrow point window misses earlier turns of a low-pitch helix.
const double carveSearchMargin=std::max(passage.mouthRadiusSubvoxels,
passage.midRadiusSubvoxels)+0.25*qPerMetre;
const auto carveHigh=std::lower_bound(passage.controlPoints.begin(),mainEnd,
qz+carveSearchMargin,
[&](const auto& point,double value){return floorProfile(point)>value;});
const auto carveLow=std::lower_bound(passage.controlPoints.begin(),mainEnd,
qz-carveSearchMargin,
[&](const auto& point,double value){return floorProfile(point)>value;});
const std::ptrdiff_t carveBegin=std::max<std::ptrdiff_t>(0,
(carveHigh-passage.controlPoints.begin())-1);
const std::ptrdiff_t carveEnd=std::min<std::ptrdiff_t>(lowerMouthIndex-1,
(carveLow-passage.controlPoints.begin())+1);
double bestSignedDistance=std::numeric_limits<double>::infinity();
double bestT=0.0;
std::ptrdiff_t bestIndex=0;
bool hasSupportFloor=false;
double bestSupportDensity=0.0;
const auto considerCarveSegment=[&](std::ptrdiff_t index)
{
const auto& a=passage.controlPoints[static_cast<std::size_t>(index)];
const auto& b=passage.controlPoints[static_cast<std::size_t>(index+1)];
const double ax=static_cast<double>(a.positionSubvoxels[0]);
const double ay=static_cast<double>(a.positionSubvoxels[1]);
const double az=static_cast<double>(a.positionSubvoxels[2]);
const double dx=static_cast<double>(b.positionSubvoxels[0])-ax;
const double dy=static_cast<double>(b.positionSubvoxels[1])-ay;
const double dz=static_cast<double>(b.positionSubvoxels[2])-az;
const double lengthSq=dx*dx+dy*dy+dz*dz;
if(lengthSq<=0.0)return;
const double t=std::clamp(((qx-ax)*dx+(qy-ay)*dy+(qz-az)*dz)/lengthSq,0.0,1.0);
const double cx=ax+t*dx,cy=ay+t*dy,cz=az+t*dz;
const double ex=qx-cx,ey=qy-cy,ez=qz-cz;
const double radius=static_cast<double>(a.radiusSubvoxels)
+t*(b.radiusSubvoxels-a.radiusSubvoxels);
const double signedDistance=DeterministicSqrt(ex*ex+ey*ey+ez*ez)-radius;
if(signedDistance<bestSignedDistance)
{bestSignedDistance=signedDistance;bestT=t;bestIndex=index;}
};
for(std::ptrdiff_t index=carveBegin;index<=carveEnd;++index)
considerCarveSegment(index);
// The route-bound landing can rise and fall after the lower mouth. Scan
// that short tail directly; binary search is only valid on the descent.
for(std::ptrdiff_t index=lowerMouthIndex;index<lastIndex;++index)
considerCarveSegment(index);
if(!std::isfinite(bestSignedDistance))continue;
const auto& nearestA=passage.controlPoints[static_cast<std::size_t>(bestIndex)];
const auto& nearestB=passage.controlPoints[static_cast<std::size_t>(bestIndex+1)];
const double nearestRadius=nearestA.radiusSubvoxels+bestT*(
static_cast<double>(nearestB.radiusSubvoxels)-nearestA.radiusSubvoxels);
const double nearestDx=static_cast<double>(nearestB.positionSubvoxels[0])
-nearestA.positionSubvoxels[0];
const double nearestDy=static_cast<double>(nearestB.positionSubvoxels[1])
-nearestA.positionSubvoxels[1];
const double nearestHorizontalSq=nearestDx*nearestDx+nearestDy*nearestDy;
const double supportPathT=nearestHorizontalSq>0.0
?std::clamp(((qx-nearestA.positionSubvoxels[0])*nearestDx
+(qy-nearestA.positionSubvoxels[1])*nearestDy)/nearestHorizontalSq,0.0,1.0)
:bestT;
const double supportPathRadius=nearestA.radiusSubvoxels+supportPathT*(
static_cast<double>(nearestB.radiusSubvoxels)-nearestA.radiusSubvoxels);
const double supportPathPlayerCenterZ=nearestA.positionSubvoxels[2]+supportPathT*(
static_cast<double>(nearestB.positionSubvoxels[2])-nearestA.positionSubvoxels[2])
-supportPathRadius+playerCenterAboveFloorQ;
const double nearestPlayerCenterZ=supportPathPlayerCenterZ;
const double distanceToCenter=std::max(1.0e-9,bestSignedDistance+nearestRadius);
const double verticalWallAlignment=distanceToCenter>1.0e-9
?std::clamp(-(qz-(nearestA.positionSubvoxels[2]+bestT*(
static_cast<double>(nearestB.positionSubvoxels[2])-nearestA.positionSubvoxels[2])))
/distanceToCenter,0.0,1.0):0.0;
const float relief=VF_FieldSurfaceRelief(static_cast<float>(X),static_cast<float>(Y),
static_cast<float>(Z),static_cast<std::uint32_t>(Owner?Owner->Seed:0));
const double wallReliefWeight=1.0-0.80*verticalWallAlignment;
const double roughSignedDistance=bestSignedDistance
+static_cast<double>(std::clamp(relief,-1.0f,1.0f))*0.24*qPerMetre*wallReliefWeight;
// Positive density is air; rough rock is cut with full side/ceiling detail and
// gentler relief on the gravity-facing wall so the supported tread stays open.
composed=std::max(composed,static_cast<float>(-roughSignedDistance/Q));
// At tight bends, keep the tread tied to the player-center profile selected
// by horizontal path position so vertical probe offsets cannot shift the ramp.
const bool fallbackSupport=qz>=nearestPlayerCenterZ-1.50*qPerMetre;
const double supportThicknessVoxels=fallbackSupport
?qPerMetre/Q:0.5*qPerMetre/Q;
double bestSupportDistanceSquared=std::numeric_limits<double>::infinity();
const auto considerSupportSegment=[&](std::ptrdiff_t index)
{
const auto& segmentA=passage.controlPoints[static_cast<std::size_t>(index)];
const auto& segmentB=passage.controlPoints[static_cast<std::size_t>(index+1)];
const double dx=static_cast<double>(segmentB.positionSubvoxels[0])-segmentA.positionSubvoxels[0];
const double dy=static_cast<double>(segmentB.positionSubvoxels[1])-segmentA.positionSubvoxels[1];
const double radiusA=segmentA.radiusSubvoxels;
const double radiusB=segmentB.radiusSubvoxels;
// Keep the tread within the probe band and below the capsule's
// lowest sampled point.
const double floorOffset=0.20;
const double horizontalLengthSq=dx*dx+dy*dy;
const double supportT=horizontalLengthSq>0.0
?std::clamp(((qx-segmentA.positionSubvoxels[0])*dx
+(qy-segmentA.positionSubvoxels[1])*dy)/horizontalLengthSq,0.0,1.0)
:bestT;
const double centerX=segmentA.positionSubvoxels[0]+supportT*dx;
const double centerY=segmentA.positionSubvoxels[1]+supportT*dy;
const double centerZ=segmentA.positionSubvoxels[2]+supportT*(
static_cast<double>(segmentB.positionSubvoxels[2])-segmentA.positionSubvoxels[2]);
const double radius=segmentA.radiusSubvoxels+supportT*(
static_cast<double>(segmentB.radiusSubvoxels)-segmentA.radiusSubvoxels);
const double supportPlayerCenterZ=centerZ-radius+playerCenterAboveFloorQ;
if(fallbackSupport)
{
const double supportProfileError=std::abs(
supportPlayerCenterZ-nearestPlayerCenterZ);
if(supportProfileError>0.06*qPerMetre)return;
}
const double horizontalX=qx-centerX,horizontalY=qy-centerY;
const double horizontalDistance=DeterministicSqrt(horizontalX*horizontalX
+horizontalY*horizontalY);
const double floorQ=centerZ-radius+floorOffset*qPerMetre;
const double floorVoxels=floorQ/Q;
if(Z<floorVoxels-supportThicknessVoxels||Z>floorVoxels+1.0/Q)return;
const double supportHalfWidth=fallbackSupport?radius
:std::max(0.0,radius+2.0*qPerMetre);
if(horizontalDistance>supportHalfWidth)return;
const double supportDistanceSq=horizontalDistance*horizontalDistance
+(Z-floorVoxels)*(Z-floorVoxels);
if(supportDistanceSq>=bestSupportDistanceSquared)return;
bestSupportDistanceSquared=supportDistanceSq;
hasSupportFloor=true;
bestSupportDensity=std::clamp(Z-floorVoxels,
-supportThicknessVoxels,0.0);
};
const std::ptrdiff_t supportBegin=std::max<std::ptrdiff_t>(0,bestIndex-1);
const std::ptrdiff_t supportEnd=std::min<std::ptrdiff_t>(lastIndex-1,bestIndex+1);
for(std::ptrdiff_t index=supportBegin;index<=supportEnd;++index)
considerSupportSegment(index);
if(hasSupportFloor)
composed=std::min(composed,static_cast<float>(bestSupportDensity));
}
return composed;
}
float ApplyResolvedStrateComposition(float density,float X,float Y,float Z) const
{return ApplyResolvedStratePassageCarves(ApplyResolvedStrateBoundaryBand(density,X,Y,Z),X,Y,Z);}
bool ResolvedPassageIntersectsBox(const int32 minimum[3],const int32 maximum[3]) const
{
if(!ResolvedLayout||ResolvedLayout->passages.empty())return false;
constexpr double Q=static_cast<double>(VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel);
for(const auto& passage:ResolvedLayout->passages)
{
for(std::size_t i=1;i<passage.controlPoints.size();++i)
{
const auto& a=passage.controlPoints[i-1];const auto& b=passage.controlPoints[i];
const double radius=static_cast<double>(std::max(a.radiusSubvoxels,b.radiusSubvoxels))/Q;
const double floorThicknessVoxels=Owner&&Owner->CoreVoxelSizeMicrons>0
?1000000.0/Owner->CoreVoxelSizeMicrons:4.0;
const double low[3]={
std::min(a.positionSubvoxels[0],b.positionSubvoxels[0])/Q-radius,
std::min(a.positionSubvoxels[1],b.positionSubvoxels[1])/Q-radius,
std::min(a.positionSubvoxels[2],b.positionSubvoxels[2])/Q-radius-floorThicknessVoxels};
const double high[3]={
std::max(a.positionSubvoxels[0],b.positionSubvoxels[0])/Q+radius,
std::max(a.positionSubvoxels[1],b.positionSubvoxels[1])/Q+radius,
std::max(a.positionSubvoxels[2],b.positionSubvoxels[2])/Q+radius};
bool overlap=true;
for(int axis=0;axis<3;++axis)
overlap&=high[axis]>=minimum[axis]&&low[axis]<=maximum[axis];
if(overlap)return true;
}
}
return false;
}
static bool MakeResolvedStratumBounds(double BottomZ,double TopZ,double SealThickness,
FResolvedStratumBounds& Out)
{
if(!std::isfinite(BottomZ)||!std::isfinite(TopZ)||!std::isfinite(SealThickness)
||TopZ<=BottomZ||SealThickness<0.0)return false;
Out={BottomZ,TopZ,SealThickness};
return true;
}
bool GetResolvedStratumBounds(const FStrateSlot& Slot,FResolvedStratumBounds& Out) const
{
if(!Owner||!Owner->Manager)return false;
if(const auto* resolved=FindResolvedLayoutStratum(Slot.StrateIndex))
{
const double coreMicrons=std::max<std::uint32_t>(1,Owner->CoreVoxelSizeMicrons);
const double bottom=static_cast<double>(resolved->interiorBottomMicrometres)/coreMicrons;
const double top=static_cast<double>(resolved->interiorTopMicrometres)/coreMicrons;
const double ceiling=static_cast<double>(resolved->ceiling.topMicrometres
-resolved->ceiling.bottomMicrometres)/coreMicrons;
const double bedrock=static_cast<double>(resolved->bedrock.topMicrometres
-resolved->bedrock.bottomMicrometres)/coreMicrons;
return MakeResolvedStratumBounds(bottom,top,std::max(ceiling,bedrock),Out);
}
const int32 MidChunkZ=(Slot.TopChunkZ+Slot.BottomChunkZ)/2;
if(bUseNativeManifestFields&&WorldAssembly
&&Owner->Manager->GetGeneratorTypeForChunk(FIntVector(0,0,MidChunkZ))
==ECaveGeneratorType::FloatingIslands)
{
const auto* Plan=FindWorldAssemblyFloatingIslandStratum(Slot.StrateIndex,MidChunkZ);
if(Plan&&Plan->manifest.recipe.geometryVersion>=3)
{
constexpr double Scale=static_cast<double>(
VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel);
return MakeResolvedStratumBounds(
static_cast<double>(Plan->manifest.recipe.layoutMinimumZSubvoxels)/Scale,
static_cast<double>(Plan->manifest.recipe.layoutMaximumZSubvoxels)/Scale,
static_cast<double>(Plan->manifest.recipe.boundarySealSubvoxels)/Scale,Out);
}
}
const FStrateGenerationParams Params=Owner->Manager->GetGenerationParams(
FIntVector(0,0,MidChunkZ));
const double chunkWidth=GetResolvedLayoutChunkWidthVoxels();
return MakeResolvedStratumBounds(static_cast<double>(Slot.BottomChunkZ)*chunkWidth,
static_cast<double>(Slot.TopChunkZ+1)*chunkWidth,
static_cast<double>(Params.BoundarySealThickness),Out);
const double OwnerVoxelSizeCm = Owner == nullptr || Owner->OwnerVoxelSizeMicrons == 0
? 0.5 * static_cast<double>(VOXEL_SIZE)
: static_cast<double>(Owner->OwnerVoxelSizeMicrons) / 10000.0;
return static_cast<double>(CHUNK_SIZE) * OwnerVoxelSizeCm / GetCoreVoxelSizeCm();
}
enum class EDetailVariant : uint8 { Coherent, Smooth, PerVoxel };
@@ -671,12 +312,11 @@ public:
bool bValidatePassageRoutes=true,
const std::vector<VoxelForgeCore::DetailBandTileRegion>& InGpuVisualDetailTiles={},
const std::vector<VoxelForgeCore::DetailBandTileRegion>& InCpuVisualDetailTiles={},
const VoxelForgeCore::WorldAssemblyManifest* InWorldAssembly=nullptr,
const VoxelForgeCore::ResolvedLayoutSnapshotV3* InResolvedLayout=nullptr)
const VoxelForgeCore::WorldAssemblyManifest* InWorldAssembly=nullptr)
{
using Clock=std::chrono::steady_clock;
const auto TotalStart=Clock::now();
Owner=&World;WorldAssembly=InWorldAssembly;ResolvedLayout=InResolvedLayout;
Owner=&World;WorldAssembly=InWorldAssembly;
WorkerCount=std::clamp(Workers,1,16);DetailVariant=Variant;
Scheduler=InScheduler;RoundTunnelsEnabled=bInRoundTunnels;
bUseNativeManifestFields=true;
@@ -833,11 +473,10 @@ public:
const FIntVector& ClipMaxVoxels,EDetailVariant Variant,
bool bInRoundTunnels,
const VoxelForgeCore::WorldAssemblyManifest* InWorldAssembly,
const VoxelForgeCore::ResolvedLayoutSnapshotV3* InResolvedLayout,
std::string& Error)
{
using Clock=std::chrono::steady_clock;
Owner=&World;WorldAssembly=InWorldAssembly;ResolvedLayout=InResolvedLayout;
Owner=&World;WorldAssembly=InWorldAssembly;
WorkerCount=1;DetailVariant=Variant;Scheduler=nullptr;
// Analytic pages retain their bounded owner bins for route bookkeeping. Once published,
// the Core world binds each page to its base shape as the single density evaluator.
@@ -873,20 +512,18 @@ public:
void InitializeNativeSurfaceOnly(FStandaloneOwnerWorld& World,
const VoxelForgeCore::WorldAssemblyManifest* InWorldAssembly,
const VoxelForgeCore::ResolvedLayoutSnapshotV3* InResolvedLayout,
const FIntVector& InMinimum,const FIntVector& InMaximum)
{
Owner=&World;WorldAssembly=InWorldAssembly;ResolvedLayout=InResolvedLayout;
Owner=&World;WorldAssembly=InWorldAssembly;
NativeOnlyMinimum=InMinimum;NativeOnlyMaximum=InMaximum;
bUseNativeManifestFields=true;bNativeOnly=true;bAnalyticOnly=true;Built=true;
NativeOnlyViolations.store(0,std::memory_order_relaxed);
}
bool BuildShapeDependencyProof(FStandaloneOwnerWorld& World,
const FIntVector& MinVoxels,const FIntVector& MaxVoxels,bool bInRoundTunnels,
const VoxelForgeCore::ResolvedLayoutSnapshotV3* InResolvedLayout=nullptr)
const FIntVector& MinVoxels,const FIntVector& MaxVoxels,bool bInRoundTunnels)
{
Owner=&World;ResolvedLayout=InResolvedLayout;WorkerCount=1;RoundTunnelsEnabled=bInRoundTunnels;
Owner=&World;WorkerCount=1;RoundTunnelsEnabled=bInRoundTunnels;
bAnalyticOnly=true;bNativeOnly=false;Stats={};
for(int32 Axis=0;Axis<3;++Axis)
{
@@ -1077,12 +714,12 @@ public:
const double TileZ0=Origin.Z,TileZ1=Origin.Z+static_cast<double>(Cells)*Step;
for(const FStrateSlot& Slot:Owner->Manager->GetLayout())
{
FResolvedStratumBounds Bounds;
if(!GetResolvedStratumBounds(Slot,Bounds))continue;
const FStrateGenerationParams Params=Owner->Manager->GetGenerationParams(
FIntVector(0,0,(Slot.TopChunkZ+Slot.BottomChunkZ)/2));
const float HalfWidth=static_cast<float>(std::max(8.0,
Bounds.SealThickness+8.0));
const float Boundaries[2]={static_cast<float>(Bounds.BottomZ),
static_cast<float>(Bounds.TopZ)};
static_cast<double>(Params.BoundarySealThickness)+8.0));
const float Boundaries[2]={static_cast<float>(Slot.BottomChunkZ)*CHUNK_SIZE,
static_cast<float>(Slot.TopChunkZ+1)*CHUNK_SIZE};
for(const float Z:Boundaries)
if(Z+HalfWidth>=TileZ0&&Z-HalfWidth<=TileZ1)
Out.stratumBoundaries.push_back({Z,HalfWidth});
@@ -1391,19 +1028,19 @@ public:
float NativeDensity=0.0f;
if(!NativeSurfaceDensityAt(X,Y,Z,NativeDensity))
{RecordNativeOnlyViolation();return 0.0f;}
return ApplyEditBrushes(ApplyResolvedStrateComposition(NativeDensity,X,Y,Z),X,Y,Z);
return NativeDensity;
}
float IslandDensity=0.0f;
if(NativeFloatingIslandDensityAt(X,Y,Z,IslandDensity))
{
++ThreadClassificationStats().NativeFloatFieldCalls;
return ApplyEditBrushes(ApplyResolvedStrateComposition(IslandDensity,X,Y,Z),X,Y,Z);
return ApplyEditBrushes(IslandDensity,X,Y,Z);
}
float NativeDensity=0.0f;
if(NativeSurfaceDensityAt(X,Y,Z,NativeDensity))
{
++ThreadClassificationStats().NativeFloatFieldCalls;
return ApplyEditBrushes(ApplyResolvedStrateComposition(NativeDensity,X,Y,Z),X,Y,Z);
return ApplyEditBrushes(NativeDensity,X,Y,Z);
}
if(UsesLegacySurfaceField(X,Y,Z))
return LegacySurfaceDensityAt(X,Y,Z);
@@ -1415,32 +1052,6 @@ public:
return AnalyticDensityAt(X,Y,Z);
}
std::string DensityDispatchPathAt(float X,float Y,float Z) const
{
if(SharedDensitySource)return SharedDensitySource->DensityDispatchPathAt(X,Y,Z);
float Density=0.0f;
if(NativeFloatingIslandDensityAt(X,Y,Z,Density))return "FloatingIslands-native";
if(NativeSurfaceDensityAt(X,Y,Z,Density))return "SurfaceWorld-native";
if(UsesLegacySurfaceField(X,Y,Z))return "SurfaceWorld-legacy";
if(Owner&&Owner->Manager)
{
const int32 ChunkZ=FMath::FloorToInt(Z/static_cast<float>(GetResolvedLayoutChunkWidthVoxels()));
const ECaveGeneratorType Type=Owner->Manager->GetGeneratorTypeForChunk(FIntVector(0,0,ChunkZ));
switch(Type)
{
case ECaveGeneratorType::TunnelNetwork:return "compiled-analytic/TunnelNetwork";
case ECaveGeneratorType::FlatPlain:return "compiled-analytic/FlatPlain";
case ECaveGeneratorType::CrystalChamber:return "compiled-analytic/CrystalChamber";
case ECaveGeneratorType::Maze:return "compiled-analytic/Maze";
case ECaveGeneratorType::SurfaceWorld:return "compiled-analytic/SurfaceWorld";
case ECaveGeneratorType::VerticalShafts:return "compiled-analytic/VerticalShafts";
case ECaveGeneratorType::FloatingIslands:return "compiled-analytic/FloatingIslands";
case ECaveGeneratorType::Underwater:return "compiled-analytic/Underwater";
}
}
return "compiled-analytic/fallback";
}
float DensityAtLattice(int32 X,int32 Y,int32 Z) const
{
if(SharedDensitySource)return SharedDensitySource->DensityAtLattice(X,Y,Z);
@@ -1453,21 +1064,21 @@ public:
if(!NativeSurfaceDensityAt(static_cast<float>(X),static_cast<float>(Y),
static_cast<float>(Z),NativeDensity))
{RecordNativeOnlyViolation();return 0.0f;}
return ApplyEditBrushes(ApplyResolvedStrateComposition(NativeDensity,X,Y,Z),X,Y,Z);
return NativeDensity;
}
float IslandDensity=0.0f;
if(NativeFloatingIslandDensityAt(static_cast<float>(X),static_cast<float>(Y),
static_cast<float>(Z),IslandDensity))
{
++ThreadClassificationStats().NativeLatticeFieldCalls;
return ApplyEditBrushes(ApplyResolvedStrateComposition(IslandDensity,X,Y,Z),X,Y,Z);
return ApplyEditBrushes(IslandDensity,X,Y,Z);
}
float NativeDensity=0.0f;
if(NativeSurfaceDensityAt(static_cast<float>(X),static_cast<float>(Y),
static_cast<float>(Z),NativeDensity))
{
++ThreadClassificationStats().NativeLatticeFieldCalls;
return ApplyEditBrushes(ApplyResolvedStrateComposition(NativeDensity,X,Y,Z),X,Y,Z);
return ApplyEditBrushes(NativeDensity,X,Y,Z);
}
if(UsesLegacySurfaceField(static_cast<float>(X),static_cast<float>(Y),
static_cast<float>(Z)))
@@ -1491,19 +1102,19 @@ public:
float NativeDensity=0.0f;
if(!NativeSurfaceDensityAt(X,Y,Z,NativeDensity))
{RecordNativeOnlyViolation();return 0.0f;}
return ApplyEditBrushes(ApplyResolvedStrateComposition(NativeDensity,X,Y,Z),X,Y,Z);
return NativeDensity;
}
float IslandDensity=0.0f;
if(NativeFloatingIslandDensityAt(X,Y,Z,IslandDensity))
{
++ThreadClassificationStats().NativeUnclampedFieldCalls;
return ApplyEditBrushes(ApplyResolvedStrateComposition(IslandDensity,X,Y,Z),X,Y,Z);
return ApplyEditBrushes(IslandDensity,X,Y,Z);
}
float NativeDensity=0.0f;
if(NativeSurfaceDensityAt(X,Y,Z,NativeDensity))
{
++ThreadClassificationStats().NativeUnclampedFieldCalls;
return ApplyEditBrushes(ApplyResolvedStrateComposition(NativeDensity,X,Y,Z),X,Y,Z);
return ApplyEditBrushes(NativeDensity,X,Y,Z);
}
if(UsesLegacySurfaceField(X,Y,Z))
return LegacySurfaceDensityAt(X,Y,Z);
@@ -1544,12 +1155,6 @@ public:
OutDensity[Lane]=DensityAtLattice(XStart+Lane*XStep,Y,Z);
return;
}
if(IsInsideResolvedStrateBoundaryBand(static_cast<float>(Z)))
{
for(int32 Lane=0;Lane<Count;++Lane)
OutDensity[Lane]=DensityAtLattice(XStart+Lane*XStep,Y,Z);
return;
}
bool bHasLegacySurfaceSample=false;
bool bHasNativeIslandSample=false;
for(int32 Lane=0;Lane<Count;++Lane)
@@ -1633,14 +1238,13 @@ private:
float Density=static_cast<float>(Proxy)*(1.0f/256.0f);
if((Density<0.0f)!=bRock)
Density=(bRock?-1.0f:1.0f)*std::max(std::abs(Density),1.0f/256.0f);
return ApplyEditBrushes(ApplyResolvedStrateComposition(Density,FX,FY,FZ),FX,FY,FZ);
return ApplyEditBrushes(Density,FX,FY,FZ);
}
// Match the fixed fallback to the edge of the stored proxy band. The
// displacement is tapered to zero there, so this avoids a magnitude
// jump along the candidate bit-mask boundary.
constexpr float ProxyBandEdge=DetailSupremum+0.125f;
return ApplyEditBrushes(ApplyResolvedStrateComposition(
bRock?-ProxyBandEdge:ProxyBandEdge,FX,FY,FZ),FX,FY,FZ);
return ApplyEditBrushes(bRock?-ProxyBandEdge:ProxyBandEdge,FX,FY,FZ);
}
float AnalyticDensityAt(float X,float Y,float Z,bool bClampNearZero=true,
@@ -1656,21 +1260,14 @@ private:
if(OutFloorInfluence)*OutFloorInfluence=0.0f;
float IslandDensity=0.0f;
if(NativeFloatingIslandDensityAt(X,Y,Z,IslandDensity))
{
const float composed=ApplyResolvedStrateComposition(IslandDensity,X,Y,Z);
return bApplyEdits?ApplyEditBrushes(composed,X,Y,Z):composed;
}
return bApplyEdits?ApplyEditBrushes(IslandDensity,X,Y,Z):IslandDensity;
if(UsesLegacySurfaceField(X,Y,Z))
{
float NativeDensity=0.0f;
if(NativeSurfaceDensityAt(X,Y,Z,NativeDensity))
{
NativeDensity=ApplyResolvedStrateComposition(NativeDensity,X,Y,Z);
return bApplyEdits?ApplyEditBrushes(NativeDensity,X,Y,Z):NativeDensity;
}
const float Density=Owner->Generator->GetDensityAt(X,Y,Z);
const float composed=ApplyResolvedStrateComposition(Density,X,Y,Z);
return bApplyEdits?ApplyEditBrushes(composed,X,Y,Z):composed;
return bApplyEdits?ApplyEditBrushes(Density,X,Y,Z):Density;
}
const bool bInsideFine=X>=Min[0]&&X<=Max[0]&&Y>=Min[1]&&Y<=Max[1]
&&Z>=Min[2]&&Z<=Max[2];
@@ -1684,8 +1281,7 @@ private:
if((Density<0.0f)!=bRock||(bClampNearZero&&std::abs(Density)<0.05f))
Density=(bRock?-1.0f:1.0f)*std::max(std::abs(Density),
bClampNearZero?0.05f:1.0e-7f);
const float composed=ApplyResolvedStrateComposition(Density,X,Y,Z);
return bApplyEdits?ApplyEditBrushes(composed,X,Y,Z):composed;
return bApplyEdits?ApplyEditBrushes(Density,X,Y,Z):Density;
}
ESurfaceFamily SurfaceFamily=ESurfaceFamily::Strata;float SurfaceSDF=100000.0f;
bool bFloorSurface=false,bCriticalAir=false;float CaveInfluence=0.0f,FloorInfluence=0.0f;
@@ -1714,7 +1310,6 @@ private:
if((Density<0.0f)!=bRock||(bClampNearZero&&std::abs(Density)<0.05f))
Density=(bRock?-1.0f:1.0f)*std::max(std::abs(Density),
bClampNearZero?0.05f:1.0e-7f);
Density=ApplyResolvedStrateComposition(Density,X,Y,Z);
return bApplyEdits?ApplyEditBrushes(Density,X,Y,Z):Density;
}
@@ -1724,11 +1319,10 @@ public:
{
if(SharedDensitySource)
return SharedDensitySource->GetNativeSurfaceHeightsAt(X,Y,ChunkZ,OutGroundZ,OutCeilingZ);
if(!WorldAssembly||!ResolvedLayout||!Owner||!Owner->Manager||!Owner->Generator
if(!WorldAssembly||!Owner||!Owner->Manager||!Owner->Generator
||!std::isfinite(X)||!std::isfinite(Y))return false;
const double ChunkWidth=GetResolvedLayoutChunkWidthVoxels();
const std::int64_t chunkMinimum=static_cast<std::int64_t>(std::llround(ChunkZ*ChunkWidth));
const std::int64_t chunkMaximum=static_cast<std::int64_t>(std::llround((ChunkZ+1)*ChunkWidth));
const std::int64_t chunkMinimum=static_cast<std::int64_t>(ChunkZ)*CHUNK_SIZE;
const std::int64_t chunkMaximum=chunkMinimum+CHUNK_SIZE;
if(bNativeOnly&&(!NativeOnlyContainsColumn(X,Y)
||chunkMaximum<NativeOnlyMinimum.Z||chunkMinimum>NativeOnlyMaximum.Z
||Owner->Manager->GetGeneratorTypeForChunk(FIntVector(0,0,ChunkZ))
@@ -1737,8 +1331,7 @@ public:
if(Owner->Manager->GetGeneratorTypeForChunk(FIntVector(0,0,ChunkZ))
!=ECaveGeneratorType::SurfaceWorld)return false;
const int32 StrateIndex=Owner->Manager->GetStrateIndex(
static_cast<float>((static_cast<double>(ChunkZ)+0.5)
*ResolvedLayout->strateLayoutChunkSizeMicrometres/10000.0));
static_cast<float>((static_cast<double>(ChunkZ)*CHUNK_SIZE+CHUNK_SIZE/2)*VOXEL_SIZE));
const auto* Plan=FindWorldAssemblyStratum(StrateIndex,ChunkZ);
if(!Plan)return false;
constexpr double Scale=static_cast<double>(VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel);
@@ -1751,7 +1344,7 @@ public:
const VoxelForgeCore::Heightfield2D Block(WorldAssembly->recipe,*Plan);
if(!Block.isValid())return false;
const auto Column=Block.point(ToFixed(X),ToFixed(Y),
static_cast<int64>(ChunkZ)*ResolvedLayout->strateLayoutChunkWidthSubvoxels);
static_cast<int64>(ChunkZ)*CHUNK_SIZE*VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel);
OutGroundZ=static_cast<float>(Column.groundHeightSubvoxels/Scale);
OutCeilingZ=static_cast<float>(Column.capHeightSubvoxels/Scale);
return std::isfinite(OutGroundZ)&&std::isfinite(OutCeilingZ);
@@ -1767,9 +1360,10 @@ public:
const int32 Pad=std::max(Step,1);
const int32 BMin=Origin.Z-Pad;
const int32 BMax=Origin.Z+(Cells+1)*Step;
const float LayoutWidth=static_cast<float>(GetResolvedLayoutChunkWidthVoxels());
const int32 FirstChunk=FMath::FloorToInt(static_cast<float>(BMin)/LayoutWidth);
const int32 LastChunk=FMath::FloorToInt(static_cast<float>(BMax)/LayoutWidth);
const int32 FirstChunk=FMath::FloorToInt(static_cast<float>(BMin)
/static_cast<float>(CHUNK_SIZE));
const int32 LastChunk=FMath::FloorToInt(static_cast<float>(BMax)
/static_cast<float>(CHUNK_SIZE));
const VoxelForgeCore::WorldAssemblyStratumPlanV1* Plan=nullptr;
for(int32 ChunkZ=FirstChunk;ChunkZ<=LastChunk;++ChunkZ)
{
@@ -1811,32 +1405,53 @@ public:
const VoxelForgeCore::WorldAssemblyFloatingIslandPlanV1* IslandPlan=nullptr;
bool bSurfaceOverlap=false,bIslandOverlap=false,bOtherStrateOverlap=false;
bool bIslandOtherStrateOverlap=false,bBadPlan=false;
if(Owner&&Owner->Manager&&ResolvedLayout)
if(Owner&&Owner->Manager)
{
const float LayoutWidth=static_cast<float>(GetResolvedLayoutChunkWidthVoxels());
const int32 FirstChunk=FMath::FloorToInt(static_cast<float>(BMin[2])/LayoutWidth);
const int32 LastChunk=FMath::FloorToInt(static_cast<float>(BMax[2])/LayoutWidth);
// Keep the delivered SurfaceWorld chunk mapping unchanged.
// Conserver le mapping de chunks SurfaceWorld deja livre.
const int32 FirstChunk=FMath::FloorToInt(static_cast<float>(BMin[2])
/static_cast<float>(CHUNK_SIZE));
const int32 LastChunk=FMath::FloorToInt(static_cast<float>(BMax[2])
/static_cast<float>(CHUNK_SIZE));
for(int32 ChunkZ=FirstChunk;ChunkZ<=LastChunk;++ChunkZ)
{
const ECaveGeneratorType Type=Owner->Manager->GetGeneratorTypeForChunk(FIntVector(0,0,ChunkZ));
const int32 StrateIndex=Owner->Manager->GetStrateIndex(static_cast<float>(
(static_cast<double>(ChunkZ)+0.5)*ResolvedLayout->strateLayoutChunkSizeMicrometres/10000.0));
const ECaveGeneratorType Type=Owner->Manager->GetGeneratorTypeForChunk(
FIntVector(0,0,ChunkZ));
if(Type==ECaveGeneratorType::SurfaceWorld)
{
bSurfaceOverlap=true;bIslandOtherStrateOverlap=true;
bSurfaceOverlap=true;
const int32 StrateIndex=Owner->Manager->GetStrateIndex(
static_cast<float>((static_cast<double>(ChunkZ)*CHUNK_SIZE+CHUNK_SIZE/2)*VOXEL_SIZE));
const auto* Candidate=FindWorldAssemblyStratum(StrateIndex,ChunkZ);
if(!Candidate||(SurfacePlan&&SurfacePlan!=Candidate))bBadPlan=true;
if(!Candidate||(SurfacePlan&&SurfacePlan!=Candidate))
bBadPlan=true;
SurfacePlan=Candidate;
}
else if(Type==ECaveGeneratorType::FloatingIslands)
else if(Type!=ECaveGeneratorType::FloatingIslands)
bOtherStrateOverlap=true;
}
// Island strata preserve owner-authored physical bounds through the resolved scale ratio.
// Les strates d'iles conservent les bornes physiques owner via le rapport de resolution.
const double CoreVoxelsPerIslandChunk=GetCoreVoxelsPerOwnerChunk();
const int32 FirstIslandChunk=FMath::FloorToInt(static_cast<float>(BMin[2])
/static_cast<float>(CoreVoxelsPerIslandChunk));
const int32 LastIslandChunk=FMath::FloorToInt(static_cast<float>(BMax[2])
/static_cast<float>(CoreVoxelsPerIslandChunk));
for(int32 ChunkZ=FirstIslandChunk;ChunkZ<=LastIslandChunk;++ChunkZ)
{
const ECaveGeneratorType Type=Owner->Manager->GetGeneratorTypeForChunk(
FIntVector(0,0,ChunkZ));
if(Type==ECaveGeneratorType::FloatingIslands)
{
bIslandOverlap=true;bOtherStrateOverlap=true;
bIslandOverlap=true;
const int32 StrateIndex=Owner->Manager->GetStrateIndex(
static_cast<float>((static_cast<double>(ChunkZ)*CHUNK_SIZE+CHUNK_SIZE/2)*VOXEL_SIZE));
const auto* Candidate=FindWorldAssemblyFloatingIslandStratum(StrateIndex,ChunkZ);
if(!Candidate||(IslandPlan&&IslandPlan!=Candidate))bBadPlan=true;
IslandPlan=Candidate;
}
else
{bOtherStrateOverlap=true;bIslandOtherStrateOverlap=true;}
else bIslandOtherStrateOverlap=true;
}
}
const auto Finish=[&](EVoxelTileClass Verdict,bool bUnknown=false)
@@ -1852,27 +1467,6 @@ public:
else ++Counts.MixedBoxes;
return Result;
};
if(ResolvedPassageIntersectsBox(BMin,BMax))
return Finish(EVoxelTileClass::Mixed,true);
if(!EditBrushes.empty()&&EditBoundsMin.X<=BMax[0]&&EditBoundsMax.X>=BMin[0]
&&EditBoundsMin.Y<=BMax[1]&&EditBoundsMax.Y>=BMin[1]
&&EditBoundsMin.Z<=BMax[2]&&EditBoundsMax.Z>=BMin[2])
return Finish(EVoxelTileClass::Mixed,true);
if(ResolvedLayout&&Owner)
{
const double ZMinMicrometres=static_cast<double>(BMin[2])*Owner->CoreVoxelSizeMicrons;
const double ZMaxMicrometres=static_cast<double>(BMax[2])*Owner->CoreVoxelSizeMicrons;
for(const auto& Stratum:ResolvedLayout->strates)
for(const auto* Band:{&Stratum.ceiling,&Stratum.bedrock})
if(Band->presentInCurrentField&&ZMaxMicrometres>=Band->bottomMicrometres
&&ZMinMicrometres<Band->topMicrometres)
{
if(ZMinMicrometres>=Band->bottomMicrometres
&&ZMaxMicrometres<Band->topMicrometres)
return Finish(EVoxelTileClass::AllSolid);
return Finish(EVoxelTileClass::Mixed);
}
}
if(bNativeOnly)
{
const bool bInsideProofBox=BMin[0]>=NativeOnlyMinimum.X
@@ -1892,6 +1486,10 @@ public:
||(bIslandOverlap&&(bIslandOtherStrateOverlap
||(!bSurfaceOverlap&&bOtherStrateOverlap))))
return Finish(EVoxelTileClass::Mixed,true);
if(!EditBrushes.empty()&&EditBoundsMin.X<=BMax[0]&&EditBoundsMax.X>=BMin[0]
&&EditBoundsMin.Y<=BMax[1]&&EditBoundsMax.Y>=BMin[1]
&&EditBoundsMin.Z<=BMax[2]&&EditBoundsMax.Z>=BMin[2])
return Finish(EVoxelTileClass::Mixed,true);
// The native interval path below is the exact field selected first by DensityAtLattice
// for SurfaceWorld and FloatingIslands. Legacy analytic primitives/layer bounds cannot
// modify that field; only the explicit edit transaction above can. Keep their guards on
@@ -1951,18 +1549,13 @@ public:
const std::int64_t Seal=IslandPlan->manifest.recipe.boundarySealSubvoxels;
const std::int64_t BoxBottom=static_cast<std::int64_t>(BMin[2])*Scale;
const std::int64_t BoxTop=static_cast<std::int64_t>(BMax[2])*Scale;
const bool bSharedTopSealEnabled=IslandPlan->manifest.recipe.geometryVersion<3
||!VoxelDensityAblation::IsBoundarySealOff();
const bool bTopSealOverlap=bSharedTopSealEnabled
&&BoxBottom<=Top&&BoxTop>Top-Seal;
const bool bBottomSealOverlap=IslandPlan->manifest.recipe.geometryVersion<3
&&BoxBottom<Bottom+Seal&&BoxTop>=Bottom;
const bool bBottomSealOverlap=BoxBottom<Bottom+Seal&&BoxTop>=Bottom;
const bool bTopSealOverlap=BoxBottom<=Top&&BoxTop>Top-Seal;
if(bBottomSealOverlap)
return Finish(BoxBottom>=Bottom&&BoxTop<=Bottom+Seal
?EVoxelTileClass::AllSolid:EVoxelTileClass::Mixed);
if(bTopSealOverlap)
return Finish((IslandPlan->manifest.recipe.geometryVersion<3
?BoxBottom>=Top-Seal:BoxBottom>Top-Seal)&&BoxTop<=Top
return Finish(BoxBottom>=Top-Seal&&BoxTop<=Top
?EVoxelTileClass::AllSolid:EVoxelTileClass::Mixed);
const VoxelForgeCore::FloatingIslandFieldV1 Block(
IslandPlan->manifest.recipe,IslandPlan->manifest.plan);
@@ -2484,16 +2077,13 @@ private:
bool NativeSurfaceDensityAt(float X,float Y,float Z,float& OutDensity) const
{
if(!bUseNativeManifestFields||!WorldAssembly||!ResolvedLayout||!Owner||!Owner->Manager||!Owner->Generator
if(!bUseNativeManifestFields||!WorldAssembly||!Owner||!Owner->Manager||!Owner->Generator
||!std::isfinite(X)||!std::isfinite(Y)||!std::isfinite(Z))return false;
const float LayoutWidth=static_cast<float>(GetResolvedLayoutChunkWidthVoxels());
if(!(LayoutWidth>0.0f))return false;
const int32 ChunkZ=FMath::FloorToInt(Z/LayoutWidth);
const int32 ChunkZ=FMath::FloorToInt(Z/static_cast<float>(CHUNK_SIZE));
if(Owner->Manager->GetGeneratorTypeForChunk(FIntVector(0,0,ChunkZ))
!=ECaveGeneratorType::SurfaceWorld)return false;
const int32 StrateIndex=Owner->Manager->GetStrateIndex(
static_cast<float>((static_cast<double>(ChunkZ)+0.5)
*ResolvedLayout->strateLayoutChunkSizeMicrometres/10000.0));
static_cast<float>((static_cast<double>(ChunkZ)*CHUNK_SIZE+CHUNK_SIZE/2)*VOXEL_SIZE));
const auto* Plan=FindWorldAssemblyStratum(StrateIndex,ChunkZ);
if(!Plan)return false;
constexpr double Scale=static_cast<double>(VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel);
@@ -2513,18 +2103,16 @@ private:
bool NativeFloatingIslandDensityAt(float X,float Y,float Z,float& OutDensity) const
{
if(!bUseNativeManifestFields||!WorldAssembly||!Owner||!Owner->Manager||!Owner->Generator
||!ResolvedLayout||!std::isfinite(X)||!std::isfinite(Y)||!std::isfinite(Z))
||!std::isfinite(X)||!std::isfinite(Y)||!std::isfinite(Z))
return false;
// Convert Core query Z back to the owner's legacy chunk coordinate.
// Convertir Z du Core vers la coordonnee de chunk legacy du proprietaire.
const double LayoutChunkWidth=GetResolvedLayoutChunkWidthVoxels();
if(!(LayoutChunkWidth>0.0))return false;
const int32 ChunkZ=FMath::FloorToInt(Z/static_cast<float>(LayoutChunkWidth));
const double CoreVoxelsPerLegacyChunk=GetCoreVoxelsPerOwnerChunk();
const int32 ChunkZ=FMath::FloorToInt(Z/static_cast<float>(CoreVoxelsPerLegacyChunk));
if(Owner->Manager->GetGeneratorTypeForChunk(FIntVector(0,0,ChunkZ))
!=ECaveGeneratorType::FloatingIslands)return false;
const int32 StrateIndex=Owner->Manager->GetStrateIndex(
static_cast<float>((static_cast<double>(ChunkZ)+0.5)
*ResolvedLayout->strateLayoutChunkSizeMicrometres/10000.0));
static_cast<float>((static_cast<double>(ChunkZ)*CHUNK_SIZE+CHUNK_SIZE/2)*VOXEL_SIZE));
const auto* Plan=FindWorldAssemblyFloatingIslandStratum(StrateIndex,ChunkZ);
if(!Plan)return false;
constexpr double Scale=static_cast<double>(VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel);
@@ -2542,38 +2130,18 @@ private:
const std::int64_t Top=Plan->manifest.recipe.layoutMaximumZSubvoxels;
const std::int64_t Seal=Plan->manifest.recipe.boundarySealSubvoxels;
const std::int64_t Zq=ToFixed(Z);
if(Plan->manifest.recipe.geometryVersion<3)
{
if(Zq>=Bottom&&Zq<Bottom+Seal)
Density=std::min(Density,-std::max<std::int64_t>(1,Zq-Bottom));
if(Zq<=Top&&Zq>Top-Seal)
Density=std::min(Density,-std::max<std::int64_t>(1,Top-Zq));
OutDensity=static_cast<float>(static_cast<double>(Density)/Scale);
}
else if(Plan->manifest.recipe.geometryVersion<4)
{
OutDensity=static_cast<float>(static_cast<double>(Density)/Scale);
FResolvedStratumBounds Bounds;
if(!MakeResolvedStratumBounds(static_cast<double>(Bottom)/Scale,
static_cast<double>(Top)/Scale,static_cast<double>(Seal)/Scale,Bounds))
return false;
const FFloatingIslandParams Params=Owner->Manager->GetFloatingIslandParamsForChunk(
FIntVector(0,0,ChunkZ));
float InternalDensity=-OutDensity;
VF_ApplyUpperBoundarySeal(InternalDensity,Z,static_cast<float>(Bounds.TopZ),
static_cast<float>(Bounds.SealThickness),Params.BaseDensity);
OutDensity=-InternalDensity;
}
else OutDensity=static_cast<float>(static_cast<double>(Density)/Scale);
if(Zq>=Bottom&&Zq<Bottom+Seal)Density=std::min(Density,-std::max<std::int64_t>(1,Zq-Bottom));
if(Zq<=Top&&Zq>Top-Seal)Density=std::min(Density,-std::max<std::int64_t>(1,Top-Zq));
OutDensity=static_cast<float>(static_cast<double>(Density)/Scale);
return std::isfinite(OutDensity);
}
bool UsesLegacySurfaceField(float X,float Y,float Z) const
{
if(!Owner||!Owner->Manager||!Owner->Generator)return false;
const double LayoutChunkWidth=GetResolvedLayoutChunkWidthVoxels();
if(!(LayoutChunkWidth>0.0))return false;
const FIntVector ChunkCoord(0,0,FMath::FloorToInt(Z/static_cast<float>(LayoutChunkWidth)));
const FIntVector ChunkCoord(FMath::FloorToInt(X/static_cast<float>(CHUNK_SIZE)),
FMath::FloorToInt(Y/static_cast<float>(CHUNK_SIZE)),
FMath::FloorToInt(Z/static_cast<float>(CHUNK_SIZE)));
return Owner->Manager->GetGeneratorTypeForChunk(ChunkCoord)
==ECaveGeneratorType::SurfaceWorld;
}
@@ -2583,8 +2151,7 @@ private:
// SurfaceWorld consumes biome overrides, terrain ops, water level and its sky cap in
// the legacy stack. Reuse that immutable evaluator as an exact temporary bridge.
// SurfaceWorld lit biomes, ops de terrain, niveau d'eau et plafond; reutiliser ce champ.
const float density=ApplyResolvedStrateComposition(Owner->Generator->GetDensityAt(X,Y,Z),X,Y,Z);
return ApplyEditBrushes(density,X,Y,Z);
return ApplyEditBrushes(Owner->Generator->GetDensityAt(X,Y,Z),X,Y,Z);
}
float ApplyEditBrushes(float Density,double X,double Y,double Z) const
@@ -2784,23 +2351,19 @@ private:
int32 Top=MIN_int32,Bottom=MAX_int32;
for(const FStrateSlot& Slot:Layout)
{
FResolvedStratumBounds Bounds;
if(!GetResolvedStratumBounds(Slot,Bounds))continue;
const int32 ResolvedBottom=FMath::FloorToInt(static_cast<float>(Bounds.BottomZ));
const int32 ResolvedTop=FMath::CeilToInt(static_cast<float>(Bounds.TopZ));
Top=std::max(Top,ResolvedTop);Bottom=std::min(Bottom,ResolvedBottom);
Top=std::max(Top,Slot.TopChunkZ);Bottom=std::min(Bottom,Slot.BottomChunkZ);
if(!Slot.Definition)continue;
const int32 MidChunkZ=(Slot.TopChunkZ+Slot.BottomChunkZ)/2;
FLayerField Field;
Field.Lo=ResolvedBottom;
Field.Hi=ResolvedTop;
Field.Lo=Slot.BottomChunkZ*CHUNK_SIZE;
Field.Hi=(Slot.TopChunkZ+1)*CHUNK_SIZE;
Field.StrateIndex=Slot.StrateIndex;
Field.Params=Owner->Manager->GetGenerationParams(FIntVector(0,0,MidChunkZ));
LayerFields.push_back(std::move(Field));
}
if(Top>=Bottom)
{
LayerRanges.push_back({Bottom,Top});
LayerRanges.push_back({Bottom*CHUNK_SIZE,(Top+1)*CHUNK_SIZE});
}
}
@@ -3911,9 +3474,8 @@ private:
auto Unit=[&](uint32 H){return static_cast<double>(Hash(H)>>8)*(1.0/16777216.0);};
for(const FStrateSlot& Slot:Layout)
{
const double LayoutChunkWidth=GetResolvedLayoutChunkWidthVoxels();
const double ZBottom=static_cast<double>(Slot.BottomChunkZ)*LayoutChunkWidth;
const double ZTop=static_cast<double>(Slot.TopChunkZ+1)*LayoutChunkWidth;
const double ZBottom=static_cast<double>(Slot.BottomChunkZ)*CHUNK_SIZE;
const double ZTop=static_cast<double>(Slot.TopChunkZ+1)*CHUNK_SIZE;
for(int32 GY=GY0;GY<=GY1;++GY)for(int32 GX=GX0;GX<=GX1;++GX)
{
uint32 H=Hash(Seed^static_cast<uint32>(GX)*0x9E3779B9u
@@ -5294,16 +4856,6 @@ public:
OutDensity[Lane]=DensityAtLattice(X,Y,ZStart+Lane*ZStep);
return;
}
bool bHasResolvedBoundaryBand=false;
for(int32 Lane=0;Lane<Count&&!bHasResolvedBoundaryBand;++Lane)
bHasResolvedBoundaryBand=IsInsideResolvedStrateBoundaryBand(
static_cast<float>(ZStart+Lane*ZStep));
if(bHasResolvedBoundaryBand)
{
for(int32 Lane=0;Lane<Count;++Lane)
OutDensity[Lane]=DensityAtLattice(X,Y,ZStart+Lane*ZStep);
return;
}
bool bHasLegacySurfaceSample=false;
for(int32 Lane=0;Lane<Count;++Lane)
bHasLegacySurfaceSample|=UsesLegacySurfaceField(static_cast<float>(X),
+23 -86
View File
@@ -2,7 +2,6 @@
#include "StandaloneSnapshotAdapter.h"
#include "VoxelForgeCore/VoxelForgeCore.h"
#include "WorldAssemblerInternal.h"
#include "ResolvedLayoutInternal.h"
#include "FloatingIslandsInternal.h"
#include <shared_mutex>
@@ -34,7 +33,6 @@ namespace VoxelForgeCore
{
std::shared_ptr<FStandaloneOwnerWorld> owner;
std::shared_ptr<const WorldAssemblyManifest> worldAssembly;
std::shared_ptr<const ResolvedLayoutSnapshotV3> resolvedLayout;
WorldConfiguration configuration;
};
@@ -391,8 +389,8 @@ namespace VoxelForgeCore
{
const VoxelForgeCore::Heightfield2D Block(Manifest.recipe,Plan);
if(!Block.isValid())continue;
const int64 StratumMinZ=static_cast<int64>(Plan.bottomChunkZ)*Manifest.recipe.layoutChunkWidthSubvoxels*Scale;
const int64 StratumMaxZ=(static_cast<int64>(Plan.topChunkZ)+1)*Manifest.recipe.layoutChunkWidthSubvoxels*Scale;
const int64 StratumMinZ=static_cast<int64>(Plan.bottomChunkZ)*CHUNK_SIZE*Scale;
const int64 StratumMaxZ=(static_cast<int64>(Plan.topChunkZ)+1)*CHUNK_SIZE*Scale;
if(TileMaxZ<StratumMinZ||TileMinZ>StratumMaxZ)continue;
struct FGridSample
{
@@ -440,10 +438,8 @@ namespace VoxelForgeCore
FGroundProfile Profile;
Profile.GridStep=GridStepVoxels;Profile.Coordinates=GridCoordinates;
Profile.MinimumZ=static_cast<double>(std::min(Plan.bottomChunkZ,Plan.topChunkZ))
*Manifest.recipe.layoutChunkWidthSubvoxels/Scale;
Profile.MaximumZ=static_cast<double>(std::max(Plan.bottomChunkZ,Plan.topChunkZ)+1)
*Manifest.recipe.layoutChunkWidthSubvoxels/Scale;
Profile.MinimumZ=static_cast<double>(std::min(Plan.bottomChunkZ,Plan.topChunkZ))*CHUNK_SIZE;
Profile.MaximumZ=static_cast<double>(std::max(Plan.bottomChunkZ,Plan.topChunkZ)+1)*CHUNK_SIZE;
Profile.Ground.reserve(Grid.size());Profile.Cap.reserve(Grid.size());
for(const auto& Sample:Grid)
{Profile.Ground.push_back(Sample.Ground/Scale);Profile.Cap.push_back(Sample.Cap/Scale);}
@@ -868,15 +864,13 @@ namespace VoxelForgeCore
struct detail_StandaloneSnapshotAdapter
{
static ResolvedWorldSnapshot FromOwner(std::shared_ptr<FStandaloneOwnerWorld> owner,
std::shared_ptr<const WorldAssemblyManifest> worldAssembly = {},
std::shared_ptr<const ResolvedLayoutSnapshotV3> resolvedLayout = {})
std::shared_ptr<const WorldAssemblyManifest> worldAssembly = {})
{
if(!owner||!owner->Settings||!owner->Manager||!owner->Generator)return {};
auto data=std::make_shared<ResolvedWorldSnapshot::Data>();
data->configuration=MakeConfiguration(*owner);
data->owner=std::move(owner);
data->worldAssembly=std::move(worldAssembly);
data->resolvedLayout=std::move(resolvedLayout);
return ResolvedWorldSnapshot(std::move(data));
}
};
@@ -894,16 +888,6 @@ namespace VoxelForgeCore
if(!parsed)return {};
worldAssembly=std::make_shared<WorldAssemblyManifest>(std::move(*parsed));
}
std::shared_ptr<const ResolvedLayoutSnapshotV3> resolvedLayout;
if(jsonRoot.Get("resolved_layout_json").IsString())
{
auto parsed=ResolvedLayoutSnapshotV3::FromJson(jsonRoot.Get("resolved_layout_json").String(),error);
if(!parsed)return {};
std::vector<ResolvedLayoutIssueV2> issues;std::string strictError;
if(!parsed->validate(ResolvedLayoutValidationModeV3::strict,issues,strictError))
{error="strict resolved-layout validation failed: "+strictError;return {};}
resolvedLayout=std::make_shared<ResolvedLayoutSnapshotV3>(std::move(*parsed));
}
const bool seedChanged=owner->Seed!=seed;
owner->Settings->Seed=seed;
@@ -926,7 +910,7 @@ namespace VoxelForgeCore
owner->MaxClipLevel=maxLodOverride;
owner->Settings->MaxClipLevel=maxLodOverride;
}
return detail_StandaloneSnapshotAdapter::FromOwner(std::move(owner),std::move(worldAssembly),std::move(resolvedLayout));
return detail_StandaloneSnapshotAdapter::FromOwner(std::move(owner),std::move(worldAssembly));
}
std::optional<ResolvedWorldSnapshot> ResolvedWorldSnapshot::FromJson(
@@ -943,35 +927,11 @@ namespace VoxelForgeCore
if(!parsed)return std::nullopt;
worldAssembly=std::make_shared<WorldAssemblyManifest>(std::move(*parsed));
}
std::shared_ptr<const ResolvedLayoutSnapshotV3> resolvedLayout;
if(root.Get("resolved_layout_json").IsString())
{
auto parsed=ResolvedLayoutSnapshotV3::FromJson(root.Get("resolved_layout_json").String(),error);
if(!parsed)return std::nullopt;
std::vector<ResolvedLayoutIssueV2> issues;std::string strictError;
if(!parsed->validate(ResolvedLayoutValidationModeV3::strict,issues,strictError))
{error="strict resolved-layout validation failed: "+strictError;return std::nullopt;}
resolvedLayout=std::make_shared<ResolvedLayoutSnapshotV3>(std::move(*parsed));
}
return detail_StandaloneSnapshotAdapter::FromOwner(std::move(owner),std::move(worldAssembly),std::move(resolvedLayout));
return detail_StandaloneSnapshotAdapter::FromOwner(std::move(owner),std::move(worldAssembly));
}
const WorldAssemblyManifest* ResolvedWorldSnapshot::worldAssembly() const noexcept
{ return data_?data_->worldAssembly.get():nullptr; }
const ResolvedLayoutSnapshotV3* ResolvedWorldSnapshot::resolvedLayout() const noexcept
{ return data_?data_->resolvedLayout.get():nullptr; }
ResolvedWorldSnapshot ResolvedWorldSnapshot::withoutResolvedLayoutPassages() const
{
if(!data_||!data_->resolvedLayout)return {};
auto copy=std::make_shared<Data>(*data_);
auto layout=std::make_shared<ResolvedLayoutSnapshotV3>(*data_->resolvedLayout);
layout->passages.clear();
std::string error;
if(!layout->finalize(error))return {};
copy->resolvedLayout=std::move(layout);
return ResolvedWorldSnapshot(std::move(copy));
}
const WorldConfiguration& ResolvedWorldSnapshot::configuration() const
{
@@ -983,7 +943,6 @@ namespace VoxelForgeCore
{
std::shared_ptr<FStandaloneOwnerWorld> owner;
std::shared_ptr<const WorldAssemblyManifest> worldAssembly;
std::shared_ptr<const ResolvedLayoutSnapshotV3> resolvedLayout;
WorldConfiguration configuration;
std::unique_ptr<FStandaloneShapeWorld> shape;
std::atomic<bool> shapeReady{false};
@@ -1024,7 +983,6 @@ namespace VoxelForgeCore
{
impl_->owner=snapshot.data_->owner;
impl_->worldAssembly=snapshot.data_->worldAssembly;
impl_->resolvedLayout=snapshot.data_->resolvedLayout;
impl_->configuration=snapshot.data_->configuration;
if(impl_->worldAssembly)
{
@@ -1182,7 +1140,7 @@ namespace VoxelForgeCore
static_cast<int32>(std::clamp<std::uint32_t>(request.workerLimit,1,16)),ToNative(request.detail),
request.includeFarWorld,error,&scheduler,request.roundTunnels,request.profileDetailBand,
request.validatePassageRoutes,request.gpuVisualDetailTiles,
request.cpuVisualDetailTiles,impl_->worldAssembly.get(),impl_->resolvedLayout.get());
request.cpuVisualDetailTiles,impl_->worldAssembly.get());
if(ok)
{
impl_->shape=std::move(shape);
@@ -1197,25 +1155,23 @@ namespace VoxelForgeCore
bool World::isTileShapeFree(const TileKey& key) const
{
if(!impl_||!impl_->owner||!impl_->worldAssembly||!impl_->resolvedLayout||!impl_->owner->Manager
if(!impl_||!impl_->owner||!impl_->worldAssembly||!impl_->owner->Manager
||!impl_->owner->Generator||!impl_->editLog.empty())return false;
FIntVector boundsMin,boundsMax;
if(!NativeOnlyBoundsForTile(*impl_,key,boundsMin,boundsMax))return false;
const std::int64_t tileMinimum[3]={boundsMin.X,boundsMin.Y,boundsMin.Z};
const std::int64_t tileMaximum[3]={boundsMax.X,boundsMax.Y,boundsMax.Z};
const int32 LayoutChunkWidth=static_cast<int32>(std::max<std::int64_t>(1,
impl_->resolvedLayout->strateLayoutChunkWidthSubvoxels/WorldAssemblySubvoxelsPerVoxel));
const int32 firstSurfaceChunk=FloorDiv(boundsMin.Z,LayoutChunkWidth);
const int32 lastSurfaceChunk=FloorDiv(boundsMax.Z,LayoutChunkWidth);
const int32 firstSurfaceChunk=FloorDiv(boundsMin.Z,CHUNK_SIZE);
const int32 lastSurfaceChunk=FloorDiv(boundsMax.Z,CHUNK_SIZE);
const WorldAssemblyStratumPlanV1* selectedPlan=nullptr;
for(int32 chunkZ=firstSurfaceChunk;chunkZ<=lastSurfaceChunk;++chunkZ)
{
if(impl_->owner->Manager->GetGeneratorTypeForChunk(FIntVector(0,0,chunkZ))
!=ECaveGeneratorType::SurfaceWorld)return false;
const int32 strateIndex=impl_->owner->Manager->GetStrateIndex(
static_cast<float>((static_cast<double>(chunkZ)+0.5)
*impl_->resolvedLayout->strateLayoutChunkSizeMicrometres/10000.0));
static_cast<float>((static_cast<double>(chunkZ)*CHUNK_SIZE
+CHUNK_SIZE*0.5)*VOXEL_SIZE));
const auto found=std::find_if(impl_->worldAssembly->plan.strates.begin(),
impl_->worldAssembly->plan.strates.end(),[strateIndex,chunkZ](const auto& plan)
{return plan.strateIndex==strateIndex&&chunkZ<=plan.topChunkZ
@@ -1227,8 +1183,9 @@ namespace VoxelForgeCore
if(!selectedPlan||!Heightfield2D(impl_->worldAssembly->recipe,*selectedPlan).isValid())
return false;
const double coreVoxelsPerOwnerChunk=static_cast<double>(
impl_->resolvedLayout->strateLayoutChunkWidthSubvoxels)/WorldAssemblySubvoxelsPerVoxel;
const double coreVoxelsPerOwnerChunk=static_cast<double>(CHUNK_SIZE)
*static_cast<double>(impl_->owner->OwnerVoxelSizeMicrons)
/static_cast<double>(std::max(1u,impl_->owner->CoreVoxelSizeMicrons));
const int32 firstIslandChunk=FMath::FloorToInt(
static_cast<double>(boundsMin.Z)/coreVoxelsPerOwnerChunk);
const int32 lastIslandChunk=FMath::FloorToInt(
@@ -1249,7 +1206,7 @@ namespace VoxelForgeCore
if(OwnerPassageTouchesBox(*impl_->owner,boundsMin,boundsMax))return false;
FStandaloneShapeWorld proofGeometry;
if(!proofGeometry.BuildShapeDependencyProof(*impl_->owner,boundsMin,boundsMax,
impl_->owner->Generator->bStandaloneResearchRoundTunnels,impl_->resolvedLayout.get()))return false;
impl_->owner->Generator->bStandaloneResearchRoundTunnels))return false;
const FIntVector tileOrigin=ToNative(key).OriginVoxels();
if(proofGeometry.HasShapeDependencyInBox(tileOrigin,1,CHUNK_SIZE))return false;
return true;
@@ -1363,7 +1320,6 @@ namespace VoxelForgeCore
auto region=std::make_shared<FStandaloneShapeWorld>();
if(!region->BuildAnalyticRegion(*impl_->owner,fineMin,fineMax,regionMin,regionMax,
ToNative(base.detail),base.roundTunnels,impl_->worldAssembly.get(),
impl_->resolvedLayout.get(),
regionErrors[index]))return;
compiledRegions[index]=std::move(region);
};
@@ -1414,8 +1370,7 @@ namespace VoxelForgeCore
auto region=std::make_shared<FStandaloneShapeWorld>();
if(!region->Build(*impl_->owner,fineMin,fineMax,regionMin,regionMax,
static_cast<int32>(clampedWorkers),ToNative(base.detail),false,error,&scheduler,
base.roundTunnels,base.profileDetailBand,false,{}, {},impl_->worldAssembly.get(),
impl_->resolvedLayout.get()))return false;
base.roundTunnels,base.profileDetailBand,false,{}, {},impl_->worldAssembly.get()))return false;
if(!impl_->editLog.empty())region->SetEditTransaction(impl_->editLog);
const auto& build=region->GetStats();
++stats.regionsBuilt;
@@ -1502,10 +1457,6 @@ namespace VoxelForgeCore
float World::densityAt(Vec3d position) const
{ return impl_&&impl_->shapeReady.load(std::memory_order_acquire)&&impl_->shape?impl_->shape->DensityAt(static_cast<float>(position.x),static_cast<float>(position.y),static_cast<float>(position.z)):0.0f; }
std::string World::densityDispatchPathAt(Vec3d position) const
{ return impl_&&impl_->shapeReady.load(std::memory_order_acquire)&&impl_->shape
?impl_->shape->DensityDispatchPathAt(static_cast<float>(position.x),static_cast<float>(position.y),static_cast<float>(position.z))
:"uncompiled"; }
float World::unclampedDensityAt(Vec3d position) const
{ return impl_&&impl_->shapeReady.load(std::memory_order_acquire)&&impl_->shape?impl_->shape->DensityAtUnclamped(static_cast<float>(position.x),static_cast<float>(position.y),static_cast<float>(position.z)):0.0f; }
DetailFieldSample World::detailSampleAt(Vec3d position) const
@@ -1675,7 +1626,6 @@ namespace VoxelForgeCore
if(!options.diagnosticForceNativeOnly&&!isTileShapeFree(key))
{error="shape-free guard: tile failed the native-only readiness proof";return std::nullopt;}
nativeOnlyShape.InitializeNativeSurfaceOnly(*impl_->owner,impl_->worldAssembly.get(),
impl_->resolvedLayout.get(),
nativeOnlyMinimum,nativeOnlyMaximum);
}
else if(impl_->tileRegionCount.load(std::memory_order_acquire)!=0)
@@ -1832,19 +1782,15 @@ namespace VoxelForgeCore
const int64 TileMaximumZ=static_cast<int64>(origin.Z)+extent;
for(const auto& Plan:impl_->worldAssembly->plan.strates)
{
const int64 PlanMinimumZ=static_cast<int64>(std::min(Plan.bottomChunkZ,Plan.topChunkZ))
*impl_->resolvedLayout->strateLayoutChunkWidthSubvoxels/WorldAssemblySubvoxelsPerVoxel;
const int64 PlanMaximumZ=(static_cast<int64>(std::max(Plan.bottomChunkZ,Plan.topChunkZ)+1))
*impl_->resolvedLayout->strateLayoutChunkWidthSubvoxels/WorldAssemblySubvoxelsPerVoxel;
const int64 PlanMinimumZ=static_cast<int64>(std::min(Plan.bottomChunkZ,Plan.topChunkZ))*CHUNK_SIZE;
const int64 PlanMaximumZ=(static_cast<int64>(std::max(Plan.bottomChunkZ,Plan.topChunkZ))+1)*CHUNK_SIZE;
bHasNativeSurfaceHorizonPlan=bHasNativeSurfaceHorizonPlan
||(TileMinimumZ<=PlanMaximumZ&&TileMaximumZ>=PlanMinimumZ);
}
for(const auto& Entry:impl_->worldAssembly->floatingIslands)
{
const int64 PlanMinimumZ=static_cast<int64>(std::min(Entry.bottomChunkZ,Entry.topChunkZ))
*impl_->resolvedLayout->strateLayoutChunkWidthSubvoxels/WorldAssemblySubvoxelsPerVoxel;
const int64 PlanMaximumZ=(static_cast<int64>(std::max(Entry.bottomChunkZ,Entry.topChunkZ)+1))
*impl_->resolvedLayout->strateLayoutChunkWidthSubvoxels/WorldAssemblySubvoxelsPerVoxel;
const int64 PlanMinimumZ=static_cast<int64>(std::min(Entry.bottomChunkZ,Entry.topChunkZ))*CHUNK_SIZE;
const int64 PlanMaximumZ=(static_cast<int64>(std::max(Entry.bottomChunkZ,Entry.topChunkZ))+1)*CHUNK_SIZE;
bHasIslandPlanInTile=bHasIslandPlanInTile
||(TileMinimumZ<=PlanMaximumZ&&TileMaximumZ>=PlanMinimumZ);
}
@@ -1945,11 +1891,7 @@ namespace VoxelForgeCore
const double CoreVoxelSizeCm=static_cast<double>(impl_->configuration.voxelSizeMicrons)/10000.0;
const double OwnerVoxelSizeCm=impl_->owner!=nullptr&&impl_->owner->OwnerVoxelSizeMicrons>0
?static_cast<double>(impl_->owner->OwnerVoxelSizeMicrons)/10000.0:0.5*static_cast<double>(VOXEL_SIZE);
const double CoreVoxelsPerOwnerChunk=impl_->resolvedLayout
?static_cast<double>(impl_->resolvedLayout->strateLayoutChunkWidthSubvoxels)
/WorldAssemblySubvoxelsPerVoxel
:static_cast<double>(impl_->owner->StrateLayoutChunkWidthSubvoxels)
/WorldAssemblySubvoxelsPerVoxel;
const double CoreVoxelsPerOwnerChunk=static_cast<double>(CHUNK_SIZE)*OwnerVoxelSizeCm/CoreVoxelSizeCm;
const int32 CenterChunkZ=FMath::FloorToInt(TileCenterZ/CoreVoxelsPerOwnerChunk);
const int32 StrateIndex=world.Manager->GetStrateIndex(
static_cast<float>(TileCenterZ*CoreVoxelSizeCm));
@@ -2262,11 +2204,6 @@ namespace VoxelForgeCore
out.diagnostics.horizonGroundTrianglesRemoved=GroundStats.RemovedTriangles;
out.diagnostics.horizonCapTriangles=CapStats.Triangles;
}
if(impl_->worldAssembly&&!bOverlapsPlayerEdit)
{
AppendStratumBoundaryFloors(world,farShape,nativeKey,step,mesh);
AppendStratumBoundaryCeilings(world,farShape,nativeKey,step,mesh);
}
out.densitySampleCount=static_cast<std::uint64_t>(std::max<int64>(0,sampleCount));
if(bHasWorldAssembly)
+19 -25
View File
@@ -235,9 +235,6 @@ namespace world_assembly_detail
|| recipe.evaluatorVersion > WorldAssemblyEvaluatorVersion
|| recipe.unitsPerVoxel != WorldAssemblySubvoxelsPerVoxel)
{ error = "world assembly recipe version, evaluator or fixed scale is unsupported"; return false; }
if (recipe.layoutChunkWidthSubvoxels <= 0
|| recipe.layoutChunkWidthSubvoxels > 256ll * 512ll)
{ error = "resolved strate-layout chunk width is outside the supported physical range"; return false; }
if (recipe.biomes.empty() || recipe.biomes.size() > MaxBiomeCount)
{ error = "world assembly recipe must contain one to eight biome profiles"; return false; }
if (recipe.biomeCellSizeSubvoxels <= 0 || recipe.biomeCellSizeSubvoxels > 100000000ll
@@ -299,8 +296,7 @@ namespace world_assembly_detail
return true;
}
inline bool ValidateStratum(const WorldAssemblyStratumPlanV1& stratum,
std::int64_t layoutChunkWidthSubvoxels, std::string& error)
inline bool ValidateStratum(const WorldAssemblyStratumPlanV1& stratum, std::string& error)
{
if (stratum.strateIndex < 0 || stratum.topChunkZ < stratum.bottomChunkZ
|| stratum.capWavelengthSubvoxels <= 0 || stratum.capUndulationSubvoxels < 0
@@ -334,9 +330,9 @@ namespace world_assembly_detail
if (feature.type == 2 || feature.type == 4)
{
const std::int64_t stratumMinZ = static_cast<std::int64_t>(stratum.bottomChunkZ)
* layoutChunkWidthSubvoxels;
* 32 * WorldAssemblySubvoxelsPerVoxel;
const std::int64_t stratumMaxZ = (static_cast<std::int64_t>(stratum.topChunkZ) + 1)
* layoutChunkWidthSubvoxels;
* 32 * WorldAssemblySubvoxelsPerVoxel;
constexpr std::int64_t maximumExceptionExtent = 1024
* WorldAssemblySubvoxelsPerVoxel;
for (std::size_t axis = 0; axis < 3; ++axis)
@@ -424,7 +420,6 @@ namespace world_assembly_detail
std::uint64_t hash = StartHash();
HashWord(hash, recipe.schemaVersion, 4); HashWord(hash, recipe.evaluatorVersion, 4);
HashWord(hash, recipe.unitsPerVoxel, 4); HashWord(hash, recipe.seed, 4);
HashWord(hash, static_cast<std::uint64_t>(recipe.layoutChunkWidthSubvoxels), 8);
HashWord(hash, static_cast<std::uint64_t>(recipe.biomeCellSizeSubvoxels), 8);
HashWord(hash, static_cast<std::uint64_t>(recipe.biomeWarpSubvoxels), 8);
HashWord(hash, static_cast<std::uint64_t>(recipe.biomeWarpWavelengthSubvoxels), 8);
@@ -633,7 +628,6 @@ namespace world_assembly_detail
if (!value.IsObject() || !ReadU32(value.Get("schema_version"), recipe.schemaVersion)
|| !ReadU32(value.Get("evaluator_version"), recipe.evaluatorVersion)
|| !ReadU32(value.Get("units_per_voxel"), recipe.unitsPerVoxel)
|| !ReadInteger(value.Get("layout_chunk_width_q"), recipe.layoutChunkWidthSubvoxels)
|| !ReadU32(value.Get("seed"), recipe.seed)
|| !ReadInteger(value.Get("biome_cell_size_q"), recipe.biomeCellSizeSubvoxels)
|| !ReadInteger(value.Get("biome_warp_q"), recipe.biomeWarpSubvoxels)
@@ -699,7 +693,6 @@ namespace world_assembly_detail
out << "{\"schema_version\":" << recipe.schemaVersion
<< ",\"evaluator_version\":" << recipe.evaluatorVersion
<< ",\"units_per_voxel\":" << recipe.unitsPerVoxel
<< ",\"layout_chunk_width_q\":" << recipe.layoutChunkWidthSubvoxels
<< ",\"seed\":" << recipe.seed
<< ",\"biome_cell_size_q\":" << recipe.biomeCellSizeSubvoxels
<< ",\"biome_warp_q\":" << recipe.biomeWarpSubvoxels
@@ -868,8 +861,7 @@ namespace world_assembly_detail
|| !ReadI32(islandValue.Get("bottom_chunk_z"), entry.bottomChunkZ))
{ error = "world assembly floating-island slot is missing its resolved strate bounds"; return std::nullopt; }
const std::string nestedJson = JsonText(islandValue.Get("manifest"));
auto parsedIsland = FloatingIslandManifestV1::FromJson(
nestedJson, error, manifest.recipe.layoutChunkWidthSubvoxels);
auto parsedIsland = FloatingIslandManifestV1::FromJson(nestedJson, error);
if (!parsedIsland) return std::nullopt;
entry.manifest = std::move(*parsedIsland);
manifest.floatingIslands.push_back(std::move(entry));
@@ -1759,15 +1751,15 @@ bool WorldAssemblyManifest::finalize(std::string& error)
{ error = "SurfaceWorld stratum recipe seed does not match the world assembly season seed"; return false; }
stratum.recipeOverride.contentHash = world_assembly_detail::HashRecipe(stratum.recipeOverride);
}
if (!world_assembly_detail::ValidateStratum(stratum, recipe.layoutChunkWidthSubvoxels, error)) return false;
if (!world_assembly_detail::ValidateStratum(stratum, error)) return false;
if (recipe.evaluatorVersion >= 4)
{
if (stratum.routeConstraints.version != 1 || stratum.route.size() < 2)
{ error = "world assembly evaluator 4 requires a versioned entrance-to-exit route"; return false; }
const std::int64_t bottomZ = static_cast<std::int64_t>(stratum.bottomChunkZ)
* recipe.layoutChunkWidthSubvoxels;
* 32 * WorldAssemblySubvoxelsPerVoxel;
const std::int64_t topZ = (static_cast<std::int64_t>(stratum.topChunkZ) + 1)
* recipe.layoutChunkWidthSubvoxels;
* 32 * WorldAssemblySubvoxelsPerVoxel;
const std::int64_t halfHeight = stratum.routeConstraints.capsuleHeightSubvoxels / 2;
for (const auto& point : stratum.route)
{
@@ -1797,12 +1789,14 @@ bool WorldAssemblyManifest::finalize(std::string& error)
const auto& Scale = islands.manifest.recipe;
if (Scale.ownerToCoreScaleNumerator == 0 || Scale.ownerToCoreScaleDenominator == 0)
{ error = "floating-island owner-to-Core scale is invalid"; return false; }
if(Scale.layoutChunkWidthSubvoxels<=0)
{error="floating-island strate has no resolved layout chunk width";return false;}
const std::int64_t bottomQ = static_cast<std::int64_t>(islands.bottomChunkZ)
*Scale.layoutChunkWidthSubvoxels;
const std::int64_t topQ = (static_cast<std::int64_t>(islands.topChunkZ)+1)
*Scale.layoutChunkWidthSubvoxels;
const double CoreVoxelsPerOwnerChunk = static_cast<double>(CoreTileVoxelCount)
* Scale.ownerToCoreScaleNumerator / Scale.ownerToCoreScaleDenominator;
const std::int64_t bottomQ = static_cast<std::int64_t>(std::llround(
static_cast<double>(islands.bottomChunkZ) * CoreVoxelsPerOwnerChunk
* WorldAssemblySubvoxelsPerVoxel));
const std::int64_t topQ = static_cast<std::int64_t>(std::llround(
static_cast<double>(static_cast<std::int64_t>(islands.topChunkZ) + 1)
* CoreVoxelsPerOwnerChunk * WorldAssemblySubvoxelsPerVoxel));
if (islands.manifest.recipe.layoutMinimumZSubvoxels < bottomQ
|| islands.manifest.recipe.layoutMaximumZSubvoxels > topQ)
{ error = "floating-island recipe layout escapes the resolved owner strate bounds"; return false; }
@@ -2006,7 +2000,7 @@ std::array<std::int64_t,2> Heightfield2D::capHeightBounds() const noexcept
if(recipe_->evaluatorVersion>=5)
{
const long double TopSubvoxels=(static_cast<long double>(plan_->topChunkZ)+1.0L)
*recipe_->layoutChunkWidthSubvoxels;
*CoreTileVoxelCount*WorldAssemblySubvoxelsPerVoxel;
Minimum=std::min(Minimum,TopSubvoxels);
Maximum=std::min(Maximum,TopSubvoxels);
}
@@ -2025,7 +2019,7 @@ std::int64_t Heightfield2D::farSurfaceCapHeightSubvoxels(std::int64_t x,
// Clip only the far render surface. Keep the near density evaluator bit-identical.
// Borner uniquement le plafond lointain. L'evaluateur de densite proche reste identique.
const std::int64_t ownedUpperBoundary=(static_cast<std::int64_t>(plan_->topChunkZ)+1)
*recipe_->layoutChunkWidthSubvoxels;
*CoreTileVoxelCount*WorldAssemblySubvoxelsPerVoxel;
return std::min(column.capHeightSubvoxels,ownedUpperBoundary);
}
@@ -2304,8 +2298,8 @@ FieldInfluenceBounds Heightfield2D::influenceBounds() const noexcept
{
FieldInfluenceBounds out;
if (!isValid()) return out;
out.minimumZSubvoxels = static_cast<std::int64_t>(plan_->bottomChunkZ) * recipe_->layoutChunkWidthSubvoxels;
out.maximumZSubvoxels = (static_cast<std::int64_t>(plan_->topChunkZ) + 1) * recipe_->layoutChunkWidthSubvoxels;
out.minimumZSubvoxels = static_cast<std::int64_t>(plan_->bottomChunkZ) * 32 * WorldAssemblySubvoxelsPerVoxel;
out.maximumZSubvoxels = (static_cast<std::int64_t>(plan_->topChunkZ) + 1) * 32 * WorldAssemblySubvoxelsPerVoxel;
return out;
}
@@ -1,263 +0,0 @@
# VoxelForge strata, units, and generation layers
**Design round L20 — 2026-10-20**
## Summary
Author strate layout in metres and give each strate a voxel size. Keep Core's internal tile at 32³
voxels; its physical width follows that strate's voxel size and the tile's LOD. Use one director to
resolve the season, layout, seed, generator recipe, resolution, and interfaces before workers start.
Generators then evaluate an immutable, common field contract. A shared composition layer applies
strata boundaries, gaps, seals, edits, caches, and proofs. The mesher consumes that composed field
and generic surface hints; it should not branch on SurfaceWorld, FloatingIslands, or feature type IDs.
The code already has parts of this shape, but not the boundaries between them. In particular,
`FStandaloneShapeWorld` is both a dispatch layer and a collection of field adapters, while
`World::generateTile` contains generator-aware far-surface and feature refinement. The Unreal
adapter currently translates two different meanings of “chunk” into Core coordinates.
The L19 ledges are not explained by a different density recipe per LOD. The ring audit found
upward-facing terrain from the same lower SurfaceWorld field at different extracted heights on
adjacent LODs. At the default 25 cm Core voxel size, LOD1, LOD2, and LOD3 sample at 0.5 m, 1 m,
and 2 m. The maximum LOD1→2 ring difference is 1.49862 m; LOD2→3 reaches 7.73318 m, with 8
no-hit samples among 308. An explicit shared surface contract can give all LODs common boundary
geometry and a controlled transition band. A planar ceiling alone will not fix these ground ledges.
One conversion issue needs an explicit preservation target. The current Core path maps one
SurfaceWorld slot chunk to 32 Core voxels (8 m at 25 cm), but one FloatingIslands slot chunk to
32 owner voxels at 12.5 cm (4 m). Converting each current interpretation independently into metres
can preserve each field's current positions, but it does not make shared chunk indices one common
physical boundary. The converter must record the actual per-strate bounds and any resulting gap or
overlap before choosing a unified interface. Do not promise a no-movement migration from a single
global “metres per chunk” constant.
Metres are not a runtime cost concern. Resolution is. Halving voxel spacing in all three axes means
about eight times as many density samples for the same physical volume, plus more tiles, queue work,
and cache entries because each internal tile remains 32³ voxels. With 25 cm as the default for all
strates, the proposed starting resolution matches today's Core sampling resolution.
## 1. Current code mapped to the three layers
There is no single class called “director” today. The director work is split between Unreal's
season/layout code, the Core adapter, and Core's tile scheduler.
| Intended layer | Current location and symbols | Current responsibility and boundary issue |
|---|---|---|
| **Director / orchestrator** | `VoxelStrateComposer.cpp`; `VoxelSeasonManifest.cpp`; `VoxelStrateManager.cpp` (`Initialize`, `GetGeneratorTypeForChunk`, `GetGenerationParams`); `VoxelWorld.cpp` (`BuildDesiredTiles`, tile scheduling, epochs); `VoxelForgeCoreAdapter.cpp` (`BuildSurfaceStratumPlan`, `BuildFloatingIslandStratumPlan`, `AttachValidatedWorldAssembly`) | Composes season params and stacked slots, resolves generator kind and seed, and serializes the Core snapshot. `WorldAssemblyManifest`, `WorldAssemblyPlanV1`, and their `FromJson`/`finalize`/`validate` functions in `WorldAssemblerInternal.h` are the current plan/manifest format. Resolution and bounds are not fully resolved here: Core re-derives them using generator-specific conversions. `TopWorldZ`, `BottomWorldZ`, `HeightInChunks`, and `InterStrateGapChunks` remain chunk/voxel-coordinate based in owner-facing data. |
| **Generators** | SurfaceWorld: `Heightfield2D` in `VoxelForgeCore.h` and `WorldAssemblerInternal.h`; plan construction in `VoxelForgeCoreAdapter.cpp`. FloatingIslands: `FloatingIslandFieldV1` in `VoxelForgeCore.h` and `FloatingIslandsInternal.h`; plan construction in the adapter. Legacy: `UVoxelGenerator::GetDensityAt` in `VoxelGenerator.cpp`, `VoxelDensityOpStack.cpp`, and `VoxelCaveMorphology.cpp`. | SurfaceWorld and FloatingIslands have distinct plan and evaluator APIs. Legacy generation still asks the manager for the current chunk's params and generator type. In Core, the “generator” boundary is obscured by `FStandaloneShapeWorld`, which selects native fields or falls back to the copied owner generator. |
| **Shared field / composition library** | Noise and fixed-point evaluation: `WorldAssemblerInternal.h`, `FloatingIslandsInternal.h`. CPU/HLSL far-field math: `VoxelForgeFieldShared.h`. FP contract: `CoreNamespacePreamble.h`. Feature culling and caches: `BuildWorldAssemblyFeatureTileListV1`, `ScopedWorldAssemblyFeatureQueriesV1`, `SharedColumnCache.h`, `ThreadLocalStorage.h`. Field bounds/proofs: `Heightfield2D::interval`, FloatingIslands bounds, `FStandaloneShapeWorld::ClassifyBoxDetailed` and `BuildShapeDependencyProof`. Density seals: `VoxelDensityPrimitives.h`. | Useful shared pieces exist, but only for subsets of recipes. Noise is not one library used by every legacy and native generator. Bounds, density, and output identity still use subvoxels of a Core voxel. The canonical stratum bounds descriptor `FResolvedStratumBounds` is private to `ShapeWorldInternal.h`, not part of the plan contract. `AppendStratumBoundaryCeilings` is under far-shell/meshing code, even though the boundary meaning is shared composition policy. |
| **Mesher** | `UVoxelMarchingCubesMesher::GenerateMesh` in `VoxelMarchingCubesMesher.cpp`; dispatch and mesh assembly in `World::generateTile` in `VoxelForgeCore.cpp`; `FarShellsInternal.h`; hybrid sharp support in `VoxelHybridSharpMesher.h` and `VoxelMarchingCubesMesher.cpp`. | MC, skirts, far shells, connector repair panels, LOD refinement, and cap repair are spread across the production mesher and Core tile builder. `World::generateTile` scans recipe feature type IDs, refines type-4 shelves only at LOD0–2, selects a native SurfaceWorld horizon, and invokes separate ground/cap repair. `FStandaloneShapeWorld::BuildFarFieldTileInput` constructs FloatingIslands connector panels. These are recipe-aware mesh paths. |
### What crosses a boundary today that should not
- `FStandaloneShapeWorld` reads `UVoxelStrateManager`, `FStrateSlot`, `WorldAssemblyManifest`, legacy
generator params, and generator type. It selects a recipe, evaluates a field, resolves its bounds,
applies a seal, and builds GPU far-field input. That combines director, generator adapter, shared
field, and renderer responsibilities.
- `World::generateTile` knows `WorldAssemblyPlanV1`, SurfaceWorld heightfields, feature numeric IDs,
and FloatingIslands presence. The generic mesher should receive capabilities and surface data,
not know those recipe identities.
- The adapter exports one layout but encodes physical positions in `WorldAssemblySubvoxelsPerVoxel`.
That makes a physical length's fixed integer depend on the selected Core voxel size.
- Core `WorldAssemblyStratumPlanV1` carries `topChunkZ`/`bottomChunkZ`; validation in
`WorldAssemblerInternal.h` multiplies those values by `32`. FloatingIslands additionally stores
its own owner-to-Core size ratio and metric-equivalent bounds in Core-voxel units.
- The Core boundary path calls `GetResolvedStratumBounds` differently for SurfaceWorld and
FloatingIslands. The director should resolve a single physical boundary record once.
- Legacy density still reaches into manager-owned params and operations. It must become a generator
adapter that consumes the same resolved request as a native recipe, or remain explicitly marked as
a compatibility route until it can be ported.
## 2. Violations, ranked by risk
Rank 1 is the highest risk to correct physical layout and cross-LOD output.
| Rank | Risk | Violation and evidence | Why it matters |
|---:|---|---|---|
| 1 | **Critical** | **No single physical bounds/interface contract.** `FResolvedStratumBounds` in `ShapeWorldInternal.h` derives SurfaceWorld bounds from `Slot.*ChunkZ × 32`, but derives native FloatingIslands bounds from `layout*ZSubvoxels` and an owner/Core scale ratio. `GetResolvedStratumBounds` is then reused by field classification, far-field protection, and far ceiling generation. | A shared logical slot boundary can map to different metre positions depending on generator. This can make an apparent seam a gap, overlap, or misplaced terrain surface before the mesher samples it. It also makes “preserve the old heights” ambiguous unless the old per-field physical bounds are recorded. |
| 2 | **Critical** | **LOD extraction has no required shared surface representation.** `World::generateTile` uses normal MC sampling for LOD1–3; native SurfaceWorld ground refinement is only invoked at LOD4+. L19's strict ring probe excludes skirts and masked triangles and measured 149.862 cm max at LOD1→2 and 773.318 cm max at LOD2→3. | A coordinate-stable density function does not guarantee equal extracted surfaces when sample grids differ. Thin seals can be skipped, and a heightfield root can shift with coarse XY/Z samples. This is the measured ledge failure. |
| 3 | **High** | **Chunk, owner-voxel, Core-voxel, and fixed-point units are mixed.** `WorldAssemblyFixed` in the Unreal adapter serializes lengths as 1/256 Core voxel. SurfaceWorld plan bounds use `Slot.BottomChunkZ * 32` and `(TopChunkZ-BottomChunkZ+1)*32`. FloatingIslands uses `32 × ownerToCoreScaleNumerator / denominator`. `ShapeWorldInternal.h` reverses Core Z to legacy chunk coordinates with `/ GetCoreVoxelsPerOwnerChunk()`. | A parameter's physical interpretation depends on generator and runtime Core size. `/32`, `*32`, and scale-ratio logic are reasonable only in a single boundary adapter or for the internal fixed tile; they are incorrect as the authored layout contract. |
| 4 | **High** | **The Unreal adapter and manager both resolve the same layout.** `VoxelStrateManager.cpp` creates chunk slots and per-generator runtime params; `VoxelForgeCoreAdapter.cpp` re-reads those params and builds distinct native plans; `ShapeWorldInternal.h` maps Core samples back through the manager again. `WorldAssemblyStratumPlanV1::topChunkZ/bottomChunkZ` are checked against the manager in `AttachValidatedWorldAssembly`. | The runtime can validate matching integer slots without validating that the resulting physical bounds mean the same thing for both generators. The future adapter should serialize already-resolved metres and per-strate resolution. |
| 5 | **High** | **Generators read director state.** Legacy `UVoxelGenerator::GetDensityAt` asks the manager for type/params and builds/refetches operator stacks. Core native lookup also asks the manager which generator applies at a Core sample. | The generator cannot be a pure evaluator of a resolved recipe. It is hard to cache, audit, or replay independently, and unit conversion is repeated in worker code. |
| 6 | **High** | **Boundary behavior is split between recipe and shared paths.** FloatingIslands geometry v3 special-cases top seal evaluation in `NativeFloatingIslandDensityAt`; older geometry versions retain two-sided seals. `VF_ApplyBoundarySeal`/`VF_ApplyUpperBoundarySeal` provide shared density math, while `AppendStratumBoundaryCeilings` separately patches missing mesh coverage. SurfaceWorld also owns a heightfield cap. | Density closure, boundary ownership, and visible cap geometry can disagree. A shared operator alone does not guarantee a shared, LOD-stable surface. Preserve versioned historical fields during migration, then route new plans through one contract. |
| 7 | **Medium-high** | **Mesher contains recipe policy.** `World::generateTile` has SurfaceWorld native-horizon selection, a SurfaceWorld-only far skip condition, type-2 sharp boxes, type-4 shelf refinement, separate native ground/cap refinement, and a `farHorizonVersion` identity. `ShapeWorldInternal.h` creates connector panel repairs from FloatingIslands. | A new recipe requires mesher edits and generator details leak into extraction. The mesher should consume explicit surfaces, generic feature constraints, and a requested error/refinement hint. |
| 8 | **Medium-high** | **Legacy paths do not share the new generator format.** `UVoxelGenerator`, operator stacks, morphology caches, Core's native `Heightfield2D`, and `FloatingIslandFieldV1` have separate recipe/parameter routes. | “One generator format” is not yet true. A migration wrapper is needed so behavior can be ported in small, hash-checked steps instead of reimplementing all legacy archetypes at once. |
| 9 | **Medium** | **Shared helpers and numeric policies are partial.** Core's FP preamble/self-test applies to Core translation units; fixed-point noise is implemented in assembler code, island noise is in a separate implementation, and far CPU/HLSL math has its own shared header. Feature bounds/caches are more reusable than the field interfaces. | Keep the tested Core determinism contract, but promote the shared numeric/noise primitives only where their exact semantics can be versioned. “Shared” code is not automatically cross-platform identical if separate float evaluators remain. |
### Unit measurements relevant to migration
`CHUNK_SIZE` is 32 and `VOXEL_SIZE` is 12.5 cm, so the owner's legacy chunk is 4 m
([`VoxelTypes.h`](../Source/VoxelForge/Public/VoxelTypes.h), [`Round5`](Research/WorldAssemblerM3/Round5/REPORT.md)). The current default Core voxel is 25 cm. In the current native Core routes:
| Route | Current conversion | Physical chunk width at default | Evidence |
|---|---|---:|---|
| SurfaceWorld | `32` Core voxels per slot chunk | 8 m | `BuildSurfaceStratumPlan` uses chunk bounds directly in Core voxel units; L18 records the preserved `topChunkZ × 32` mapping. |
| FloatingIslands | `32 × 125000/250000 = 16` Core voxels per owner chunk | 4 m | `BuildFloatingIslandStratumPlan` serializes the ratio and applies it to layout bounds; `GetCoreVoxelsPerOwnerChunk` uses the same ratio. |
This confirms the claimed factor of two. It does **not** prove that this conversion alone caused
the L19 ring delta. L19 isolated the observed step to coarse extraction of lower SurfaceWorld
terrain, and the reported LOD4+ horizon refiner cannot affect those LOD1→2 and LOD2→3 values.
## 3. Generator contract and one-time interface handling
### What the director resolves before generation
The director should publish an immutable `ResolvedWorld` (exact type/schema is an implementation
choice) containing:
- a stable world/season identity and seed;
- an ordered list of strates with a stable ID, generator kind and recipe version;
- each strate's physical minimum and maximum bounds in metres, including height as their difference;
- a voxel size in metres per strate (25 cm default for every strate);
- route points, island anchors/connectors, and all top/bottom/ceiling positions in the same physical
coordinate space;
- one resolved interface record per adjacent pair, including any explicit void, bedrock gap,
sealed contact, upper cap, passage, or open boundary;
- any season-level values that affect world output, such as routes, islands, water datum, or biome
selection, already attached to their owning strate or interface;
- a canonical identity over the sorted resolved layout, seed, resolution map, recipes, and interface
records.
Do not make generators ask the director for the active `FStrateSlot`, chunk number, season, or
neighbour generator while evaluating a point.
### Request to every generator
A worker request should give the generator:
1. The immutable resolved recipe and stable stratum ID.
2. Physical query/tile bounds in metres, including the exact halo requested by the mesher.
3. The canonical sample coordinates or a clearly defined lattice origin and step. Voxel coordinates
are useful as an internal derived lattice, but metres/physical fixed units are the identity space.
4. The resolved per-strate voxel size and seed. LOD can be included as a sampling hint; the canonical
field value itself must not change just because the caller chose another LOD.
5. Read-only interface descriptors that touch the request bounds. Pass boundary records, not a
pointer back to the neighbour's manager or mutable generator.
### Result from every generator
The common result should provide a deterministic field evaluator and its declared capabilities:
- signed density using one documented solid/air sign convention;
- optional material or surface-class data;
- conservative interval/classification proofs and conservative feature/influence bounds, or an
explicit “unknown, evaluate” result;
- optional semantic 2D surfaces such as a ground heightfield or a cap, in physical coordinates;
- a detail envelope / maximum safe sample spacing hint. It is a hint to generic LOD/refinement
policy, not permission for a recipe to choose its own mesh path;
- generator/schema/evaluator versions for stable plan and output identity.
Keep the established fail-open behavior: an unknown interval or influence bound causes evaluation,
not a solid/air skip. Existing feature candidate lists and worker caches fit this contract as
optimizations beneath the evaluator.
### Interfaces, seals, caps, and voids belong to shared composition
The director resolves the meaning and exact physical location of each interface once. The shared
composition layer then combines generator fields and applies boundary semantics in a fixed order:
1. Evaluate each generator only for its declared physical domain, retaining its ordinary
field/feature behavior.
2. Apply the interface contract once: for example, a physically measured seal band, a cap surface,
open void, bedrock gap, or permitted passage. The contract declares ownership, sidedness, material
class, collision/support policy, and whether player edits may cut it. A gap is data, not an
accidental “no generator found” branch.
3. Apply world edits through the canonical composed field, so both sides see the same edit in
physical space.
4. Give the resulting field, proofs, and any explicit surfaces to the mesher.
This centralizes the semantics currently spread across generator density wrappers,
`FResolvedStratumBounds`, and `AppendStratumBoundaryCeilings`. Existing versioned manifests still
need compatibility adapters: do not silently reinterpret old `boundarySealSubvoxels` values.
For two different generator kinds that meet at a plane, both should reference the same stable
interface ID and exact physical boundary. Their density fields can remain independent; shared
composition owns the boundary rule. If the plan intentionally has open space between them, the
resolved layout records that metre-valued interval explicitly.
## 4. Why LOD changes thin features, and the interface surface contract
MC samples density at lattice corners. A thin seal or cap can be narrower than one coarse cell, so
the coarse grid may see no sign change at all. If it does see a crossing, interpolation uses the
coarse cell's endpoint values; its root can differ from the finer grid's root. A shared analytic
density function guarantees the same values at the same physical coordinates, not the same triangles
from different sample grids.
For a physical strate boundary, use an explicit surface descriptor with exact height/shape in metres
and a globally stable sample phase. Every LOD must use common anchors along tile and LOD transition
edges. The mesher can fill the interior at its chosen rate, then build a deterministic transition
band from those common anchors into its coarser interior. A seal/cap should not rely on a sub-cell
thin density strip surviving arbitrary MC sampling.
For the L19 lower-ground ledge, the same rule needs a SurfaceWorld ground profile available to the
mesher as semantic surface data. A shared planar boundary cap would only close the strate ceiling;
it would not align these upward-facing ground triangles. The surface can be band-limited by LOD, but
the adjacent LODs must share their transition samples and be checked against a physical error
tolerance. If that cannot be met with a transition band, refine only the affected boundary tiles.
The costs are extra boundary vertices/triangles and some CPU work to construct common transition
strips. Collision/support must consume the same interface representation where that surface is
collision-relevant. The owner would see caps and ledges hold one physical height as the camera moves
between LODs, instead of steps or holes appearing at the ring. Authoring remains in metres; internal
tile and transition details stay hidden.
This is not free geometry, but it is bounded to boundaries and LOD transition bands. L19 has already
shown why “add a thin density seal and sample it normally” is not a sufficient all-LOD guarantee.
## 5. Keep the per-strate resolution door open
Yes. A 25 cm per-strate default preserves the current Core sample spacing, and the common physical
field coordinate contract leaves room for later different sizes. Do not enable mixed resolutions
until the Round5 boundary contract is met:
1. Canonical physical-space field queries and explicit ownership at a shared boundary.
2. Deterministic transition meshes with common LOD ancestry on both resolutions.
3. Physical-space edit rasterization/replay that reaches both grids exactly once, with no holes or
double application.
4. A stable, canonically sorted strate-ID-to-size map included in plan/season identity and border
hashes.
5. Streaming and collision rules for tiles that touch or span two resolutions.
At today's one-size setting, the size map has one value (250,000 microns) for every strate. It adds
no mixed-resolution mesh, edit, or streaming cost. Tile width remains `32 × voxel size × 2^LOD`;
different future sizes change physical tile width and workload, but never change the 32³ internal
tile format.
## 6. Migration plan with “worlds don't move” checks
The checkpoints distinguish expected equality from a deliberately changed interface mesh. A plan
or schema identity can change even when field output remains equal; record both identities and mesh
hashes separately.
| Step | Work | Expected equality / check | Changes output? / Unreal PC? |
|---:|---|---|---|
| 0 | Freeze the L19 evidence as the baseline: W12, Clang with FP contraction off; retain the whole-view hashes, full-detail hashes, strict ceiling audit, captures, and FI/SW ring tables. | Baseline hashes recorded below; pin the protected SW LOD0–2 hashes too. Capture byte/pixel comparisons and ring samples must retain location, LOD, and skirt exclusion. | No. No new build needed for this design round. |
| 1 | Add a versioned resolved-metre layout representation and a read-only conversion/audit path. The audit reports, per strate, old input units, resolved old physical bounds, new metre bounds, voxel size, interfaces, and identity. Keep the old evaluator active. | Exact old-vs-new resolved positions at all authored top, bottom, height, route, island, and cap anchors. Old Core density/mesh/payload/topology hashes remain equal where the conversion is exactly representable; otherwise list the precise quantization delta before accepting a new baseline. | No. Core parser/audit can be Linux-only; adapter export needs Unreal BuildHost on the owner's PC. |
| 2 | Change owner-facing layout authoring and season serialization to metres. Convert each old slot using its **current resolved physical bounds**, not one global chunk multiplier. Represent any historical gap/overlap explicitly. Default each strate's voxel size to 25 cm. | Same physical top/bottom/height values and field anchors before/after. Run default W12 hashes and matched captures. The report must call out any interface whose two old generator bounds disagree instead of silently forcing them together. | Intended no. Touches `VoxelForgeCoreAdapter.cpp`, `VoxelStrateManager`, season manifest/composer and likely `VoxelWorld`; compile and actor validation require the owner's Unreal PC. |
| 3 | Add the common generator request/result contract and adapt `Heightfield2D` and `FloatingIslandFieldV1`; wrap the legacy `UVoxelGenerator` route without moving it yet. Move manager lookups out of evaluator calls in stages. | Per-strate exact density queries, proof classifications, full-detail hashes, whole-view hashes, W1/W8/W12 determinism, and generator-to-legacy route parity. Existing current output hashes remain equal for adapters that preserve their exact physical recipe. | No intended visual change. Unreal adapter/legacy wrappers need owner-PC UHT/build and actor validation; native Core pieces can be audited on Linux. |
| 4 | Resolve interface records once in the director; route new seal, cap, void, bedrock-gap, and passage behavior through shared composition. Keep old manifest versions on compatibility adapters. | Preserve density hashes where only a mesh closure was missing. Run the strict LOD0–8 ceiling interior/perimeter audit, edge pairing, same-LOD border hashes, matched captures, and field proofs. Any newly closed boundary is a named expected mesh/payload/topology delta. | Affected boundary mesh may change. Adapter serialization needs owner-PC validation; Core audit can run here. This step fixes thin seals/caps, not the L19 ground ledges. |
| 5 | Add the generic explicit-surface and LOD-transition contract. Feed SurfaceWorld ground-profile data into common transition bands; prototype on the measured FI/SW interface. | Produce before/after matched readable captures and full ring tables. Require zero no-hit interface samples and a chosen physical seam-error limit; retain L19 hash equality for unaffected tiles/LODs. For intended changes, list changed mesh/payload/topology hashes and keep density unchanged if the field itself is unchanged. | **This is the step that fixes the L19 ledges.** It changes protected SurfaceWorld LOD2 output, so implement only after the owner approves that specific output change. Unreal capture/collision review is on the owner's PC. |
| 6 | Enable a per-strate size map behind the already-resolved contract, initially set to 25 cm on all strates. Add one non-default diagnostic size case only after the default remains green. | At all-25-cm map, reproduce the approved default hashes and captures. Include sorted size-map identity in a negative control; boundary/transition hashes must change when one size changes. Re-run edit-across-boundary, collision, streaming, and W1/W8/W12 checks. | No default change; non-default diagnostic intentionally changes sampling. Touches Unreal reflected settings, snapshot adapter, and world identity; full compile/run requires the owner's PC. |
### L19 reference hashes
Representative W12 Clang `-ffp-contract=off`, density / mesh / payload / topology:
| Whole view | L19 hash |
|---|---|
| SurfaceWorld | `c10697a8f48380c7 / 4197fc1072f0ff58 / 7b3e616ec9459851 / c879e35592bf33e5` |
| FloatingIslands | `00bc3607a7839854 / 4baa66127c2b0892 / e11ef05e851a1517 / 1278bc4b1fffb869` |
Protected SurfaceWorld LOD0–2 hashes are in the L19 report and should be retained through steps
1–4 except for explicitly approved boundary geometry. The whole-view hash gate alone cannot prove
that a ring improved; step 5 needs the strict ring table and readable captures as well.
### Owner decisions this design needs
1. **Preservation target:** confirm that migration snapshots each current generator's resolved
physical bounds (including any current overlap or gap) before later tuning them into a single
authored metre layout. If instead the initial migration should force currently different bounds
to meet, that is a deliberate world change and needs its own baseline/capture review.
2. **Ledge output:** approve the specific SurfaceWorld LOD2/transition change before step 5
implementation, as required by the existing protected-output rule.
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Per-tile zstd CLI comparison over the pristine L1 records from this round."""
from pathlib import Path
import shutil
import struct
import subprocess
import time
import zlib
REPO = Path.cwd().resolve()
CACHE = REPO / "Saved/Linux/cache/l16-prototype"
CAPTURE_LOG = REPO / "Saved/Linux/l16-cache-l1-q24-full-write.log"
TEMP = CACHE / "codec-zstd"
RESULT = REPO / "Saved/Linux/l16-zstd-codec.txt"
assert CACHE.is_dir() and not CACHE.is_symlink()
assert CACHE.resolve().parent == (REPO / "Saved/Linux/cache").resolve()
assert CAPTURE_LOG.is_file()
assert not TEMP.exists()
cutoff_ns = CAPTURE_LOG.stat().st_mtime_ns
records = [
path for world in CACHE.glob("world_*")
for path in world.glob("*.vftile")
if "_s0_d0000000000000000_" in path.name and path.stat().st_mtime_ns <= cutoff_ns
]
records.sort()
assert len(records) == 2553, f"expected 2553 L1 pristine records, found {len(records)}"
codec = shutil.which("zstd")
assert codec, "zstd CLI is not available"
TEMP.mkdir()
per_lod = {}
try:
for source in records:
record = source.read_bytes()
assert record[:8] == b"VFTILE16"
raw_size, compressed_size = struct.unpack_from("<QQ", record, 124)
raw = zlib.decompress(record[144:144 + compressed_size])
assert len(raw) == raw_size
lod = int(source.name.split("_", 1)[0][3:])
entry = per_lod.setdefault(lod, {"raw": 0, "files": [], "encode_ns": 0, "decode_ns": 0, "zstd": 0})
raw_file = TEMP / (source.stem + ".raw")
raw_file.write_bytes(raw)
entry["raw"] += len(raw)
entry["files"].append(raw_file)
for lod in sorted(per_lod):
entry = per_lod[lod]
start = time.perf_counter_ns()
subprocess.run([codec, "-q", "-1", "-f", "--", *map(str, entry["files"])], check=True)
entry["encode_ns"] = time.perf_counter_ns() - start
compressed_files = [Path(str(path) + ".zst") for path in entry["files"]]
entry["zstd"] = sum(path.stat().st_size for path in compressed_files)
start = time.perf_counter_ns()
subprocess.run([codec, "-q", "-d", "-f", "--", *map(str, compressed_files)], check=True)
entry["decode_ns"] = time.perf_counter_ns() - start
# Verify each decoded output byte-for-byte against the zlib payload again.
# The filename is the tile stem, so a deterministic source lookup is sufficient.
source_by_stem = {path.stem: path for path in records}
for entry in per_lod.values():
for raw_file in entry["files"]:
source = source_by_stem[raw_file.stem]
data = source.read_bytes()
_, compressed_size = struct.unpack_from("<QQ", data, 124)
assert raw_file.read_bytes() == zlib.decompress(data[144:144 + compressed_size])
lines = ["lod tiles raw_total_B zstd1_total_B zstd1_avg_B encode_us_per_tile decode_us_per_tile status"]
for lod in sorted(per_lod):
entry = per_lod[lod]
count = len(entry["files"])
lines.append(
f"{lod} {count} {entry['raw']} {entry['zstd']} {entry['zstd'] / count:.1f} "
f"{entry['encode_ns'] / count / 1000:.2f} {entry['decode_ns'] / count / 1000:.2f} PASS"
)
raw_total = sum(entry["raw"] for entry in per_lod.values())
zstd_total = sum(entry["zstd"] for entry in per_lod.values())
lines.append(f"total_tiles={len(records)} raw_bytes={raw_total} zstd1_bytes={zstd_total} ratio={zstd_total / raw_total:.6f}")
lines.append("decode=byte-exact; timing includes zstd CLI process startup once per LOD")
RESULT.write_text("\n".join(lines) + "\n")
print("\n".join(lines))
finally:
resolved = TEMP.resolve()
assert resolved.parent == CACHE.resolve()
shutil.rmtree(TEMP)
File diff suppressed because it is too large. Load diff
@@ -1,26 +0,0 @@
# Owner note — L17 FloatingIslands steps
The ledges were real generated mesh geometry caused by two boundary mistakes that made empty space
look like flat ground: the FloatingIslands seal was applied as a solid cap across XY, and owner
chunks were treated as 8 m of Core voxels instead of their actual 4 m. At the measured flat square,
the native island field is air and cave/floor influence is zero. The point is about 100 m from the
four islands.
I removed the false cap and corrected the shared owner/Core coordinate conversion. Evaluator version
is 7. The before/after captures show the false sheet disappear and the actual island shape remain.
SurfaceWorld’s L1 hash changes because it now selects its intended `Heightfield2D` route; its route,
readiness and proof audits pass.
The export has nonempty meshes at LOD0–8, and the standalone viewer enables and draws all levels by
default. I cannot identify the screenshot’s dark square as a whole missing LOD from the Linux data;
it may be a specific tile or viewer draw/upload issue. I did not change the Windows viewer. Please
capture the view below and, if the square remains, repeat with `--capture-only-lod=0` through `8`.
The low-view camera is `(-22,-19,-22.8) m`, yaw 0°, pitch −4°, matching the Linux island pair.
```bat
VoxelForgeCoreStandalone.exe --world-assembler-prototype --recipe=floating-islands --clip-radius=3 --max-clip-level=8 --workers=12 --camera=-22,-19,-22.8,0,-4 --capture=Standalone\Research\WorldAssemblerM3\Linux17\captures\floating-islands-windows.png --frame-limit=60
```
Use a different `--capture=` filename for each isolated LOD. Send the all-level image plus the
isolated image that corresponds to the square.
@@ -1,182 +0,0 @@
# VoxelForge L17 — FloatingIslands boundary report
Branch `assembler/world`, starting HEAD `9a7c87e`. No cache code was changed. The shared evaluator
version is now 7; the recipe schema stays at 1.
## Cause and fix
FloatingIslands uses the sparse `FloatingIslandFieldV1` manifest field. SurfaceWorld uses the
separate planar `Heightfield2D` field. The owner voxel is 12.5 cm and the Core voxel is 25 cm, so
one 32-voxel owner chunk is **16 Core voxels / 4 m**. Several shared paths divided Core positions
by 32 directly, treating that chunk as 8 m. That doubled stratum bounds, selected the wrong
generator route near the SurfaceWorld boundary, and made the legacy layer envelope extend over
empty FloatingIslands space.
The FloatingIslands `boundarySeal` also had been applied as a solid cap over all XY. At the owner’s
flat-square probe `(-11.612444,-118.221237) m`, the raw island field is air: at Z=3.25 m it was
`+81,809` subvoxels. The old seal added `−82,065`, yielding `−256` (`−1` Core voxel, or −25 cm);
at Z=3.50 m it yielded `−1` subvoxel (−0.098 cm), then air again at Z=3.75 m. The wrong 8 m
legacy layer bound produced a second false top near Z=8 m (old world density at 7.75 m was
−0.743 Core voxels; at 8 m it was +0.073). The owner’s 4.5 m LOD0 jump is real mesh geometry
created by those bad boundaries, often inside a tile; it is not a renderer artifact or island relief.
Nested clipmap rectangles made its placement look like a tile-boundary-only issue.
The fix uses the resolved owner/Core scale for manager lookups, layer bounds, readiness, and
adjacent native strata; removes the XY-wide FloatingIslands seal cap and its all-solid proof; and
clips adjacent native FI/SW signed-distance fields at their shared physical boundary. This is in
Core and applies to every generator route. SurfaceWorld still uses `Heightfield2D`.
The cave-floor lead does not match the samples. Cave and floor influence were exactly zero at the
flat square, the island center, and the sampled ledge/ring point. The native FI field and its island
or connector bounds account for the surface. The owner world compiled 70 rooms, 69 tunnels and 2
passages in this run; those legacy primitives do not contribute to the measured FI ledge.
## Before/after measurements
`RingProbe.py` samples upward-facing mesh surfaces on adjacent XY tile edges only when the tiles’
vertical bands overlap. Values are median / p95 / maximum absolute height difference, in cm. `n/a`
means this sparse-island export had no same-band LOD0↔1 surface pair after removing the false cap;
it is not a zero-error result. Higher rings include the deep SurfaceWorld boundary and other deep
surfaces, so those rows are not all FloatingIslands ground.
| LOD edge | Before (cm) | After (cm) |
|---|---:|---:|
| 0→1 | 3.451 / 8.920 / 449.158 (266 samples) | n/a (no same-band pair) |
| 1→2 | 26.642 / 148.262 / 149.862 (514) | 0 / 0 / 0 (234) |
| 2→3 | 0.134 / 198.730 / 773.318 (596) | 0 / 0 / 0 (207) |
| 3→4 | 3.269 / 47.875 / 188.531 (277) | 0 / 0 / 0 (288) |
| 4→5 | 29.975 / 130.496 / 445.444 (544) | 0 / 0 / 30.957 (258) |
| 5→6 | 12.234 / 127.224 / 536.573 (266) | 12.234 / 127.224 / 536.573 (266) |
| 6→7 | 29.013 / 301.752 / 42,624.479 (264) | 28.892 / 291.861 / 945.477 (264) |
| 7→8 | 83.843 / 1,225.416 / 3,755.407 (275) | 83.843 / 1,225.416 / 3,755.407 (275) |
The valid worst pre-fix LOD0↔1 sample is the false cap: 3.500 m vs 7.992 m, a 449.158 cm
difference. Upward-face within-tile span p95 / maximum changed from 4.490 / 4.491 m to 1.186 /
1.927 m on LOD0. The remaining LOD0 span is the actual island shape. LOD1–3 after-fix upward
faces at the measured lower boundary are exactly at −60 m. The island tops around the matched
camera are roughly −30 to −25 m.
A separate exploratory column comparison initially reported a 34.7 m difference by pairing an
island top near −25 m with a −60 m SurfaceWorld surface from a vertically disjoint tile. That
comparison was rejected: it is not a same-band ring seam. The saved `RingProbe.py` output is the
cross-LOD evidence used above.
## History, viewer and SurfaceWorld
Prebuilt L7, L9, L12, L13 and L14 binaries/logs all have the same legacy hashes: whole-view D/M/P/T
`92ba6a57a8690c00 / 9c6b56dfab6241c9 / 82394dd7c368a061 / 445e40bdb69b0bdb`; full-detail
`93ee3b6fb6b446f3 / 3ebc72d2027ab80b / cd5f55a96de12458 / 2f61c29af247b547`. The pattern
predates L7; these measurements show no output change at L9 or L13. S9 `e7586a1`, S12 `212814a`
and S14 `ec2afe9` do not contain the headless pipeline source, so they cannot be measured this way.
No old commit was rebuilt: `git worktree add` failed because `.git/worktrees` is read-only, and the
available old binaries were used as-is.
The headless mesh export has nonempty tiles at **all** LODs 0–8 (matched view counts:
15, 64, 40, 48, 48, 96, 48, 48, 153). The standalone viewer initializes all nine `bShowLevel`
flags to true and its draw loop visits all streaming batches. There is no evidence that a whole LOD
is absent from generated data or globally filtered by the viewer. The screenshot’s dark square
cannot be mapped to a particular tile/LOD from this Linux export; a localized viewer draw/upload
or camera issue remains unconfirmed. No viewer change was made because the Windows D3D11 build and
capture are unavailable here. The Unreal comparison does not identify the cause of that square.
SurfaceWorld L1 hashes changed for the shared coordinate fix. Old L14 LOD1 D/M/P/T was
`5043975b1e5b5a3d / 1c2a5658f10fdeaa / 23b6779ef35c3a0a / 1a6d2e2d152b4f84`; L17 is
`393ad79fd8c07132 / 47c9ba17e9f5ceaa / d5d6a948ac880e17 / 8b85ea08b2c440c4`. Before, readiness
was 0/27; now it is 27/27 on the near ring. The old mapping selected the wrong route at the
SurfaceWorld stratum; the corrected mapping selects its manifest `Heightfield2D` plan. Page/native
route parity and exact queries pass, so this is the intended shared-route output change.
## Gates, captures and limits
All 28 determinism rows passed: FI and SW, Clang 19 `-ffp-contract=off` and GCC 14 default,
W1/W8/W12 with five W12 repeats. Each recipe had one unique full, whole, nine-LOD and exact-query
hash tuple across all configurations. FI whole-view D/M/P/T is
`8339509b4d5ec231 / 70e5b2b9085b517c / 4e72e53745f20ed0 / 1a2643e5138e0407`; SW whole-view is
`b286ee4f4c38b7fc / 6862deb8ab9c2af9 / f23480a4953457f9 / 62977edfd04b3afe`.
FI route parity: 8 page pairs, 14 higher-LOD exact pairs, 782,026 exact samples, zero mismatches;
uniform proof: 19,288 blocks / 25,672,328 samples / zero violations. SW: 5 page and 9 native-only
pairs, 814,625 exact samples, zero mismatches; uniform proof: 13,297 blocks / 17,698,307 samples /
zero violations. Readiness negative controls were caught. The Clang FP-contraction-off and GCC
default builds passed; the Core startup FP self-test did not reject either. No async/MPSC/Epoch
code changed; `FLazy`, shared column caches, L9/L12 proof paths and L13 route binding remain in the
tested build.
Readable Linux capture mode adds directional light with soft ambient, gentle height tint, and an
optional faint tile-edge overlay. Five 1600×900 JPEGs, all below 300 KB, are in `captures/`:
- `floating-islands-flat-square-before.jpg` / `floating-islands-flat-square-after.jpg`: same owner
probe camera `(-11.6124,-118.2212,-19.8452) m`, yaw 0, pitch 0, before/after.
- `floating-islands-island-view-before.jpg` / `floating-islands-island-view-after.jpg`: same low
island camera `(-22,-19,-22.8) m`, yaw 0, pitch −4°, before/after.
- `surface-world-l1-readable-tiles.jpg`: SurfaceWorld L1 sanity view, camera `(0,-35,30) m`, yaw 0,
pitch −60°.
All are 1600×900 JPEGs; SHA256 is included for byte-level review.
| Capture | Bytes | SHA256 |
|---|---:|---|
| `floating-islands-flat-square-before.jpg` | 70,166 | `c41ed7645735ebefea97fbc1aed167b66a3e06c019c25b1c7d8cae9449713999` |
| `floating-islands-flat-square-after.jpg` | 47,612 | `f8fb5f937ac65be9db70a41473c7a10d7f35943ba6ef5c94ab03fde9ded5c544` |
| `floating-islands-island-view-before.jpg` | 70,813 | `5c7a8eda446f51a51ab22e45ed7286bf4180e69d8e3b2180780349facadacd32` |
| `floating-islands-island-view-after.jpg` | 51,429 | `3aeedef903fce62e81ea1f07bb460dd2beb42b893bbd9bf29220973951295b4c` |
| `surface-world-l1-readable-tiles.jpg` | 53,351 | `23f1753ed100c87607e22d2adc4f8e8a2856b8af3f1d37aa4f4cec9420a92b93` |
Clang/GCC compile peak RSS was 435,588 / 902,000 KiB. Determinism peak was 538,140 KiB; FI/SW
route-audit peaks were 621,404 / 763,112 KiB. The governor remained `powersave`; runs were limited
to CPUs 0–11, at most 12 workers, 6 GiB address space; llvmpipe used 12 threads.
## Failed or retried attempts
- The first headless invocation omitted the explicit owner-world input; it was rerun with
`Standalone/data/owner_world.json`.
- An initial SurfaceWorld export failed the native-only readiness guard; corrected owner/Core
mapping and rerun passed.
- A SurfaceWorld `--max-clip-level=1` attempt expanded to 35,435,983 tiles and failed the bounded
compiler (20.985 s, 3,988,160 KiB peak RSS). Retried with `--max-level=1` (960 tiles), which
passed.
- `BoundaryProbe.py` was first called with unsupported named Z arguments; rerun with positional
bounds passed.
- The first XY-only ring comparison mixed vertically disjoint surfaces; replaced by the
overlapping-band `RingProbe.py` used above. The exploratory column probe was also rejected for
pairing different vertical bands.
- The first offscreen SurfaceWorld command reversed scene/output arguments and failed to open the
mesh; rerun with the documented order passed.
- The first density-probe invocation used `Standalone/data/owner_world.json` without a resolved FI
manifest and failed. It was rerun with `Saved/Linux/l17-fi-owner-snapshot.json` and passed.
- `/usr/bin/time` was unavailable and an early process monitor mishandled a zombie child; the
process-tree monitor in `MeasureBuild.py` replaced both attempts.
- `git worktree add` could not write `.git/worktrees`; no worktree was created and no old commit was
built outside the repository.
- Mesa could not create `/home/jahni/.cache` in the read-only environment, disabled shader caching,
and completed all captures. No file was written outside the repository.
## Windows confirmation
Run from the repository root on Windows to capture the low island view:
```bat
VoxelForgeCoreStandalone.exe --world-assembler-prototype --recipe=floating-islands --clip-radius=3 --max-clip-level=8 --workers=12 --camera=-22,-19,-22.8,0,-4 --capture=Standalone\Research\WorldAssemblerM3\Linux17\captures\floating-islands-windows.png --frame-limit=60
```
For isolation, repeat with `--capture-only-lod=0` through `--capture-only-lod=8`, changing the
capture filename each time. Please send the all-level image and the isolated image matching the
dark square; those will identify whether it is a per-tile draw gap or a particular LOD payload.
## Orchestrator review (Claude) — NOT MERGED
- **The fix breaks SurfaceWorld.** I exported the L1 view (camera `0,-35,-487.94`) from L14 and from
L17 and rendered both in the new readable mode (`Saved/Linux/claude/sw/{before,after}-{l1,hz}.jpg`).
After L17, the ground under the spawn camera is gone (black void below), the terrain sits far
away, and the mesh export shrank from 58.7 MB to 31.7 MB. Halving the strate chunk size (8 m → 4 m)
moves and squashes every stratum: a world change, not a fix.
- **What the approved world uses:** the Core world the owner played and approved places strata
with 8 m chunks (32 Core voxels of 25 cm). The "owner chunk = 4 m" claim must be checked against
what the Unreal Core route actually does (`AVoxelWorld::CoreVoxelSizeCm`, the Core bridge,
`ResolvedWorldSnapshot`), not assumed.
- **Probably real and separable:** the FloatingIslands `boundarySeal` applied as a solid cap over all
XY (the false floors at 3.5/8 m). That needs its own minimal fix with SurfaceWorld unchanged.
- **Still open in FloatingIslands after the fix:** dark tile-aligned rectangles on the ground (the L17
"after" captures, lower left).
- Kept on side branch `wip/l17-fi-scale`. Only the capture tool's readable shading
(`LinuxOffscreenCapture.cpp`) is taken into `assembler/world`.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

@@ -1,9 +0,0 @@
# L18 build resources
Limits: CPUs 0–11, `-j12`, normal priority, 6 GiB address-space cap. Governor stayed `powersave`.
These are the final builds after the cell-coverage and owner ceiling corrections.
- Clang 19, `-ffp-contract=off`: exit 0, 31.689 s, peak process RSS 436,088 KiB, peak VMS 586,240 KiB.
- GCC 14, default FP contraction: exit 0, 48.648 s, peak process RSS 903,168 KiB, peak VMS 1,014,716 KiB.
- Largest measured runtime process was the final Clang gate run at 897,276 KiB RSS. The determinism matrix peaked at 603,172 KiB and the crossing matrix at 548,664 KiB.
- An earlier GCC build was interrupted by owner steering before producing a binary; the final GCC build above completed successfully.
@@ -1,52 +0,0 @@
#!/usr/bin/env python3
"""Render the matched L18 review views as small readable JPEGs."""
import os
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[4]
CAPTURE = ROOT / "Standalone/bin/linux/VoxelForgeOffscreenCapture-linux18-clang"
EXPORTS = ROOT / "Standalone/Research/WorldAssemblerM3/Linux18/exports"
OUT = ROOT / "Standalone/Research/WorldAssemblerM3/Linux18/captures"
LOGS = ROOT / "Saved/Linux"
OUT.mkdir(parents=True, exist_ok=True)
env = os.environ.copy()
env["LP_NUM_THREADS"] = "12"
env["XDG_CACHE_HOME"] = str(ROOT / "Saved/Linux/mesa-cache")
views = [
("floating-islands-flat-square-after", "floating-islands-flat-square.vfmesh",
(-11.612444, -118.221237, -19.8452), 0, 0, True),
("floating-islands-flat-square-no-edges", "floating-islands-flat-square.vfmesh",
(-11.612444, -118.221237, -19.8452), 0, 0, False),
("floating-islands-island-view-after", "floating-islands-island-view.vfmesh",
(-22, -19, -22.8), 0, -4, True),
("floating-islands-ceiling-up", "floating-islands-island-view.vfmesh",
(-22, -19, -22.8), 0, 80, True),
("surface-world-l1-spawn-after", "surface-world-l1-spawn.vfmesh",
(0, -35, -487.94), 0, -22, False),
("surface-world-horizon-after", "surface-world-l1-spawn.vfmesh",
(0, -35, -487.94), 0, 0, False),
]
for name, scene_name, camera, yaw, pitch, tile_edges in views:
scene = EXPORTS / scene_name
png = LOGS / f"l18-{name}.png"
jpg = OUT / f"{name}.jpg"
render_log = LOGS / f"l18-{name}-render.log"
convert_log = LOGS / f"l18-{name}-jpeg.log"
command = [str(CAPTURE), str(scene), str(png), "--size=1600x900",
"--shade=readable", f"--tile-edges={'on' if tile_edges else 'off'}",
"--tile-edge-width-m=0.15", "--camera-m="+",".join(map(str, camera)),
f"--yaw-deg={yaw}", f"--pitch-deg={pitch}"]
with render_log.open("w", encoding="utf-8") as stream:
subprocess.run(command, cwd=ROOT, env=env, stdout=stream,
stderr=subprocess.STDOUT, check=True)
ffmpeg = ["ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error", "-y",
"-i", str(png), "-frames:v", "1", "-q:v", "4", str(jpg)]
with convert_log.open("w", encoding="utf-8") as stream:
subprocess.run(ffmpeg, cwd=ROOT, env=env, stdout=stream,
stderr=subprocess.STDOUT, check=True)
if jpg.stat().st_size > 300_000:
raise SystemExit(f"{jpg.name} exceeds the 300 KB review limit")
print(f"[Capture] {jpg.relative_to(ROOT)} bytes={jpg.stat().st_size} status=PASS")
@@ -1,165 +0,0 @@
#!/usr/bin/env python3
"""Audit the emitted FloatingIslands roof faces and same-LOD tile-edge continuity."""
import array
import collections
import math
import struct
import sys
def read_exact(stream, size):
data = stream.read(size)
if len(data) != size:
raise EOFError(f"wanted {size} bytes, got {len(data)}")
return data
def height_at(triangles, x, y, preferred_z):
best = None
for (x0, y0, z0), (x1, y1, z1), (x2, y2, z2) in triangles:
den = (y1-y2)*(x0-x2)+(x2-x1)*(y0-y2)
if abs(den) < 1.0e-10:
continue
a = ((y1-y2)*(x-x2)+(x2-x1)*(y-y2))/den
b = ((y2-y0)*(x-x2)+(x0-x2)*(y-y2))/den
c = 1.0-a-b
if min(a,b,c) >= -1.0e-5:
z = a*z0+b*z1+c*z2
if best is None or abs(z-preferred_z) < abs(best-preferred_z):
best = z
return best
def quantile(values, fraction):
if not values:
return math.nan
ordered = sorted(values)
return ordered[math.floor(fraction*(len(ordered)-1))]
if len(sys.argv) != 3:
raise SystemExit("usage: CeilingContinuity.py scene.vfmesh expected-cap-plane-metres")
scene_path = sys.argv[1]
root_z = float(sys.argv[2])
tiles = {}
voxel_size_m = None
with open(scene_path, "rb") as stream:
if read_exact(stream, 8) != b"VFMSH001":
raise SystemExit("invalid VFMSH001 scene")
version, voxel_um, tile_count = struct.unpack("<3I", read_exact(stream, 12))
camera = struct.unpack("<3d", read_exact(stream, 24))
yaw, pitch = struct.unpack("<2d", read_exact(stream, 16))
voxel_size_m = voxel_um/1_000_000.0
for _ in range(tile_count):
key = struct.unpack("<4i", read_exact(stream, 16))
surface_vertices, skirt_count, vertex_count, index_count, mask_count = struct.unpack(
"<5I", read_exact(stream, 20))
positions = array.array("f")
positions.frombytes(read_exact(stream, vertex_count*12))
normals = array.array("f")
normals.frombytes(read_exact(stream, vertex_count*12))
indices = array.array("I")
indices.frombytes(read_exact(stream, index_count*4))
masks = read_exact(stream, mask_count)
if sys.byteorder != "little":
positions.byteswap()
normals.byteswap()
indices.byteswap()
extent = 32*(1 << key[3])*voxel_size_m
z0, z1 = key[2]*extent, (key[2]+1)*extent
ceiling = []
for triangle in range(index_count//3):
if masks and masks[triangle] != 0:
continue
a,b,c = indices[triangle*3:triangle*3+3]
if max(a,b,c) >= surface_vertices:
continue
nz = (normals[a*3+2]+normals[b*3+2]+normals[c*3+2])/3.0
if nz > -0.65:
continue
points = tuple((positions[v*3],positions[v*3+1],positions[v*3+2])
for v in (a,b,c))
center_z = sum(point[2] for point in points)/3.0
if abs(center_z-root_z) <= 1.0:
ceiling.append(points)
tiles[key] = {
"extent": extent, "x0": key[0]*extent, "y0": key[1]*extent,
"x1": (key[0]+1)*extent, "y1": (key[1]+1)*extent,
"z0": z0, "z1": z1, "ceiling": ceiling,
}
by_lod = collections.defaultdict(dict)
for key, tile in tiles.items():
if tile["z0"] <= root_z+1.0 and tile["z1"] >= root_z-1.0:
by_lod[key[3]][key] = tile
print(f"scene={scene_path} version={version} voxel_um={voxel_um} tiles={tile_count} "
f"camera_m={camera} yaw={yaw} pitch={pitch} expected_cap_m={root_z:.9f}")
print("lod zband_tiles cap_tiles missing_tiles cap_triangles face_z_m_p05/median/p95 "
"tile_samples hit_samples max_abs_root_delta_cm shared_edges shared_hits edge_gaps "
"edge_delta_cm_median/p95/max")
all_pass = True
for lod in range(9):
target = by_lod[lod]
cap_tiles = {key: tile for key,tile in target.items() if tile["ceiling"]}
face_z = [point[2] for tile in cap_tiles.values() for tri in tile["ceiling"]
for point in tri]
deltas = []
sample_count = 0
hit_count = 0
for key,tile in target.items():
if not tile["ceiling"]:
continue
for iy in range(16):
for ix in range(16):
x = tile["x0"]+(ix+0.5)*tile["extent"]/16
y = tile["y0"]+(iy+0.5)*tile["extent"]/16
sample_count += 1
height = height_at(tile["ceiling"],x,y,root_z)
if height is not None:
hit_count += 1
deltas.append(abs(height-root_z)*100.0)
edge_deltas = []
edge_count = 0
edge_gaps = 0
for key,a in cap_tiles.items():
x,y,z,level = key
for neighbor_key,axis in (((x+1,y,z,level),"x"),((x,y+1,z,level),"y")):
b = cap_tiles.get(neighbor_key)
if b is None:
continue
edge_count += 1
epsilon = min(0.02,a["extent"]*1.0e-4)
matched = 0
for index in range(33):
t = (index+0.5)/33
if axis == "x":
fixed = a["x1"]
varying = a["y0"]+(a["y1"]-a["y0"])*t
za = height_at(a["ceiling"],fixed-epsilon,varying,root_z)
zb = height_at(b["ceiling"],fixed+epsilon,varying,root_z)
else:
fixed = a["y1"]
varying = a["x0"]+(a["x1"]-a["x0"])*t
za = height_at(a["ceiling"],varying,fixed-epsilon,root_z)
zb = height_at(b["ceiling"],varying,fixed+epsilon,root_z)
if za is not None and zb is not None:
edge_deltas.append(abs(za-zb)*100.0)
matched += 1
if matched == 0:
edge_gaps += 1
missing = len(target)-len(cap_tiles)
max_root = max(deltas) if deltas else math.nan
print(f"{lod} {len(target)} {len(cap_tiles)} {missing} "
f"{sum(len(tile['ceiling']) for tile in cap_tiles.values())} "
f"{quantile(face_z,.05):.6f}/{quantile(face_z,.5):.6f}/{quantile(face_z,.95):.6f} "
f"{sample_count} {hit_count} {max_root:.3f} {edge_count} {len(edge_deltas)} "
f"{edge_gaps} {quantile(edge_deltas,.5):.3f}/{quantile(edge_deltas,.95):.3f}/"
f"{max(edge_deltas) if edge_deltas else math.nan:.3f}")
if lod >= 4 and target and (missing or hit_count != sample_count or edge_gaps):
all_pass = False
print(f"[CeilingContinuity] result={'PASS' if all_pass else 'FAIL'} "
"criteria=LOD4-8 requested z-band tiles emit an upper-boundary ceiling; 16x16 ray samples hit; "
"shared same-LOD tile edges have paired hits")
raise SystemExit(0 if all_pass else 1)
@@ -1,25 +0,0 @@
#!/usr/bin/env python3
"""Compare all L18 crossing configurations to the L14 24 m crossing hashes."""
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[4]
RUNS = ROOT / "Saved/Linux/l18-crossing"
PATTERN = re.compile(
r"^\[Pipeline(?:FullDetailHash|WholeViewHash|LODHash|ExactQueryHash)\].*$", re.M)
failed = []
logs = sorted(RUNS.glob("*-w*-r*.log"))
for path in logs:
parts = path.stem.split("-")
compiler = parts[0]
reference_compiler = "clang" if compiler == "clang" else "gcc"
reference_path = ROOT / f"Saved/Linux/l14-final-crossing-24m-{reference_compiler}-w12.log"
expected = PATTERN.findall(reference_path.read_text(encoding="utf-8"))
actual = PATTERN.findall(path.read_text(encoding="utf-8", errors="replace"))
if actual != expected:
failed.append(path.name)
print(f"[CrossingReferenceMismatch] {path.name} expected_rows={len(expected)} "
f"actual_rows={len(actual)}")
print(f"[CrossingSurfaceHashGate] reference=L14-final-crossing-24m-W12 rows={len(logs)} "
f"result={'FAIL' if failed else 'PASS'}")
raise SystemExit(1 if failed or len(logs) != 14 else 0)
@@ -1,25 +0,0 @@
#!/usr/bin/env python3
"""Compare every L18 SurfaceWorld matrix hash row with the approved L14 reference."""
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[4]
RUNS = ROOT / "Saved/Linux/l18-matrix"
REFERENCE = ROOT / "Saved/Linux/l14-final-hash-sw-clang-off-w12-r5.log"
PATTERN = re.compile(r"^\[Pipeline(?:FullDetailHash|WholeViewHash|LODHash|ExactQueryHash)\].*$", re.M)
expected = PATTERN.findall(REFERENCE.read_text(encoding="utf-8"))
if not expected or len(expected) != 12:
raise SystemExit(f"invalid L14 reference hash rows: {len(expected)}")
logs = sorted(RUNS.glob("surface-world-*.log"))
if len(logs) != 14:
raise SystemExit(f"expected 14 SurfaceWorld matrix logs, found {len(logs)}")
failed = []
for path in logs:
actual = PATTERN.findall(path.read_text(encoding="utf-8", errors="replace"))
if actual != expected:
failed.append(path.name)
print(f"[SurfaceHashMismatch] {path.name} expected={len(expected)} actual={len(actual)}")
print(f"[SurfaceHashGate] reference={REFERENCE.name} rows={len(logs)} expected_rows=14 "
f"result={'FAIL' if failed else 'PASS'}")
raise SystemExit(1 if failed else 0)
@@ -1,149 +0,0 @@
#include "Json.h"
#include "OwnerWorldLoader.h"
#include "StandaloneCoreScheduler.h"
#include "WorldAssemblyPrototype.h"
#include "StandaloneSnapshotAdapter.h"
#include <cmath>
#include <cstdio>
#include <fstream>
#include <iterator>
#include <memory>
#include <string>
namespace
{
constexpr double CoreVoxelsPerMeter=4.0;
constexpr std::int64_t SubvoxelsPerCoreVoxel=
VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel;
void PrintDensity(VoxelForgeCore::World& World,const char* Label,double X,double Y,double Z)
{
const VoxelForgeCore::Vec3d Point{X*CoreVoxelsPerMeter,Y*CoreVoxelsPerMeter,
Z*CoreVoxelsPerMeter};
const double Density=World.densityAt(Point);
const double Raw=World.unclampedDensityAt(Point);
std::printf("[DensitySample] label=%s xyz_m=%.6f,%.6f,%.6f density_core_vox=%.9f "
"density_cm=%.4f unclamped_core_vox=%.9f sign=%s\n",Label,X,Y,Z,Density,
Density*25.0,Raw,Density<0.0?"solid":"air");
}
void PrintCrossing(VoxelForgeCore::World& World,const char* Label,double X,double Y,
double BottomM,double TopM)
{
const auto DensityAt=[&](double Z)
{
return World.densityAt({X*CoreVoxelsPerMeter,Y*CoreVoxelsPerMeter,
Z*CoreVoxelsPerMeter});
};
double Lo=BottomM,Hi=TopM;
double LoDensity=DensityAt(Lo),HiDensity=DensityAt(Hi);
if((LoDensity<0.0)==(HiDensity<0.0))
{
std::printf("[DensityCrossing] label=%s bracket_m=%.6f..%.6f signs=%s/%s result=none\n",
Label,Lo,Hi,LoDensity<0.0?"solid":"air",HiDensity<0.0?"solid":"air");
return;
}
for(int Iteration=0;Iteration<64;++Iteration)
{
const double Mid=(Lo+Hi)*0.5;
const double MidDensity=DensityAt(Mid);
if((MidDensity<0.0)==(LoDensity<0.0))
{Lo=Mid;LoDensity=MidDensity;}
else
{Hi=Mid;HiDensity=MidDensity;}
}
std::printf("[DensityCrossing] label=%s z_m=%.9f bracket_m=%.6f..%.6f "
"density_core_vox=%.9f/%.9f\n",Label,(Lo+Hi)*0.5,BottomM,TopM,
LoDensity,HiDensity);
}
}
int main(int argc,char** argv)
{
if(argc!=2)
{
std::fprintf(stderr,"usage: %s owner-world.json\n",argv[0]);
return 2;
}
VFJson::Value Root;
std::string Error;
{
std::ifstream Input(argv[1],std::ios::binary);
if(!Input){std::fprintf(stderr,"owner JSON open failed\n");return 2;}
std::string Text{std::istreambuf_iterator<char>(Input),std::istreambuf_iterator<char>{}};
if(!VFJson::Parser(std::move(Text)).Parse(Root,Error))
{std::fprintf(stderr,"owner JSON parse failed: %s\n",Error.c_str());return 2;}
}
if(!StandaloneWorldAssemblyPrototype::SelectTopStrateAsFloatingIslands(Root,Error))
{std::fprintf(stderr,"FI selection failed: %s\n",Error.c_str());return 2;}
auto Owner=std::make_shared<FStandaloneOwnerWorld>();
if(!StandaloneOwnerLoader::Resolve(Root,*Owner,Error))
{std::fprintf(stderr,"owner resolve failed: %s\n",Error.c_str());return 2;}
VoxelForgeCore::WorldAssemblyManifest Assembly;
if(!StandaloneWorldAssemblyPrototype::AttachRound1WorldAssemblyPrototype(
*Owner,Root,Error,{},&Assembly)
||!StandaloneWorldAssemblyPrototype::AttachFloatingIslandWorldAssembly(
*Owner,Root,Assembly,Error))
{std::fprintf(stderr,"plan construction failed: %s\n",Error.c_str());return 2;}
auto Snapshot=VoxelForgeCore::MakeStandaloneSnapshotFromParsedJson(Root,Owner->Seed,3,8,
false,false,Error);
if(!Snapshot)
{std::fprintf(stderr,"snapshot resolve failed: %s\n",Error.c_str());return 2;}
const auto* ResolvedAssembly=Snapshot.worldAssembly();
if(!ResolvedAssembly||ResolvedAssembly->floatingIslands.empty())
{std::fprintf(stderr,"resolved FloatingIslands plan missing\n");return 2;}
VoxelForgeCore::World World(std::move(Snapshot));
VoxelForgeCore::ShapeBuildRequest Request;
Request.minVoxel={-96,-512,-288};
Request.maxVoxel={96,96,64};
Request.clipMinVoxel=Request.minVoxel;
Request.clipMaxVoxel=Request.maxVoxel;
Request.workerLimit=12;
Request.includeFarWorld=false;
FStandaloneCoreScheduler Scheduler;
if(!World.compile(Request,Scheduler,Error))
{std::fprintf(stderr,"shape compile failed: %s\n",Error.c_str());return 2;}
const auto& Plan=ResolvedAssembly->floatingIslands.front();
const auto& Recipe=Plan.manifest.recipe;
std::printf("[FloatingIslandBounds] geometry_version=%u owner_voxel_um=%u core_voxel_um=%u "
"owner_to_core=%u/%u chunks=%d..%d layout_z_m=%.6f..%.6f ceiling_start_m=%.6f "
"seal_m=%.6f bottom_cap=%s\n",Recipe.geometryVersion,Recipe.ownerVoxelSizeMicrons,
Recipe.coreVoxelSizeMicrons,Recipe.ownerToCoreScaleNumerator,
Recipe.ownerToCoreScaleDenominator,Plan.topChunkZ,Plan.bottomChunkZ,
static_cast<double>(Recipe.layoutMinimumZSubvoxels)/SubvoxelsPerCoreVoxel/4.0,
static_cast<double>(Recipe.layoutMaximumZSubvoxels)/SubvoxelsPerCoreVoxel/4.0,
static_cast<double>(Recipe.layoutMaximumZSubvoxels-Recipe.boundarySealSubvoxels)
/SubvoxelsPerCoreVoxel/4.0,
static_cast<double>(Recipe.boundarySealSubvoxels)/SubvoxelsPerCoreVoxel/4.0,
Recipe.geometryVersion<3?"legacy":"removed");
std::printf("[DensityProbe] flat_square_xy_m=-11.612444,-118.221237 "
"compiled=%d core_voxel_size_cm=25\n",World.isCompiled()?1:0);
constexpr double X=-11.612443923950195;
constexpr double Y=-118.22123718261719;
for(double Z:{2.75,2.99,3.00,3.01,3.25,3.49,3.50,3.51,3.75,3.99,4.00,4.01,
4.05,4.125,4.25,4.50,5.00,
7.75,8.00,8.25,-60.25,-60.00,-59.75,-59.50,-59.25})
PrintDensity(World,"flat-square",X,Y,Z);
PrintCrossing(World,"shared-upper-ceiling",X,Y,3.50,3.75);
PrintCrossing(World,"upper-boundary-cap",X,Y,4.00,4.25);
PrintCrossing(World,"old-eight-metre-wrapper",X,Y,7.75,8.25);
PrintCrossing(World,"removed-lower-boundary-seal",X,Y,-60.25,-59.75);
for(const auto& Probe:std::array<std::array<double,2>,3>{{
{{-66.3,-38.7}},{{-62.3,-54.6}},{{-53.34,-22.84}}}})
{
std::printf("[DensityProbeXY] xy_m=%.3f,%.3f\n",Probe[0],Probe[1]);
for(double Z:{3.49,3.50,3.51,3.75,3.875,3.99,4.00,4.01,4.05,4.125})
PrintDensity(World,"boundary-ray",Probe[0],Probe[1],Z);
PrintCrossing(World,"boundary-ray",Probe[0],Probe[1],3.49,4.125);
}
for(const auto& Probe:std::array<std::array<double,2>,4>{{
{{-67.0,-39.0}},{{-66.0,-39.0}},{{-67.0,-38.0}},{{-66.0,-38.0}}}})
{
PrintDensity(World,"boundary-grid-node",Probe[0],Probe[1],3.875);
PrintDensity(World,"boundary-grid-node",Probe[0],Probe[1],4.125);
}
return 0;
}
@@ -1,67 +0,0 @@
#!/usr/bin/env python3
"""Measure peak per-process RSS for a build process tree under the L17 limits."""
import os
import subprocess
import sys
import time
from pathlib import Path
def descendants(root):
pending = [root]
seen = set()
while pending:
pid = pending.pop()
if pid in seen:
continue
seen.add(pid)
try:
children = Path(f"/proc/{pid}/task/{pid}/children").read_text().split()
pending.extend(int(child) for child in children)
except (FileNotFoundError, PermissionError, ProcessLookupError):
pass
return seen
def status(pid):
try:
fields = {}
for line in Path(f"/proc/{pid}/status").read_text().splitlines():
if line.startswith(("Name:", "VmRSS:", "VmSize:")):
key, *value = line.split()
fields[key[:-1]] = value[0] if value else ""
return (int(fields.get("VmRSS", "0")), int(fields.get("VmSize", "0")),
fields.get("Name", ""))
except (FileNotFoundError, PermissionError, ProcessLookupError, ValueError):
return None
if len(sys.argv) < 2:
raise SystemExit("usage: MeasureBuild.py command [arguments ...]")
if not os.sched_getaffinity(0).issubset(set(range(12))):
raise SystemExit("run under taskset -c 0-11")
started = time.monotonic()
process = subprocess.Popen(sys.argv[1:], start_new_session=True)
peak_rss = (0, 0, "")
peak_vms = (0, 0, "")
while process.poll() is None:
for pid in descendants(process.pid):
measured = status(pid)
if measured is None:
continue
rss, vms, name = measured
if rss > peak_rss[0]:
peak_rss = (rss, pid, name)
if vms > peak_vms[0]:
peak_vms = (vms, pid, name)
time.sleep(0.1)
exit_code = process.wait()
elapsed = time.monotonic() - started
print(f"[BuildTreeResources] exit_code={exit_code} wall_s={elapsed:.3f} "
f"peak_process_rss_kib={peak_rss[0]} peak_rss_pid={peak_rss[1]} "
f"peak_rss_name={peak_rss[2]} peak_process_vms_kib={peak_vms[0]} "
f"peak_vms_pid={peak_vms[1]} peak_vms_name={peak_vms[2]} "
"monitor_interval_s=0.1", flush=True)
raise SystemExit(exit_code)
@@ -1,100 +0,0 @@
#!/usr/bin/env python3
"""Summarize exported tile geometry and upward-facing ground for L17."""
import array
import collections
import math
import struct
import sys
def read_exact(stream, size):
data = stream.read(size)
if len(data) != size:
raise EOFError(f"wanted {size} bytes, got {len(data)}")
return data
path = sys.argv[1]
with open(path, "rb") as stream:
if read_exact(stream, 8) != b"VFMSH001":
raise SystemExit("bad VFMSH001 header")
version, voxel_um, tile_count = struct.unpack("<3I", read_exact(stream, 12))
camera = struct.unpack("<3d", read_exact(stream, 24))
yaw, pitch = struct.unpack("<2d", read_exact(stream, 16))
per_lod = collections.defaultdict(lambda: {"tiles": 0, "vertices": 0,
"triangles": 0, "surface_triangles": 0, "up_triangles": 0,
"up_centroids": [], "tile_spans": [], "empty": 0})
tile_rows = []
for _ in range(tile_count):
key = struct.unpack("<4i", read_exact(stream, 16))
surf_vertices, skirt_count, vertex_count, index_count, mask_count = struct.unpack(
"<5I", read_exact(stream, 20))
p = array.array("f")
p.frombytes(read_exact(stream, vertex_count * 12))
n = array.array("f")
n.frombytes(read_exact(stream, vertex_count * 12))
if sys.byteorder != "little":
p.byteswap(); n.byteswap()
indices = array.array("I")
indices.frombytes(read_exact(stream, index_count * 4))
masks = read_exact(stream, mask_count)
if sys.byteorder != "little":
indices.byteswap()
lod = key[3]
row = per_lod[lod]
row["tiles"] += 1
row["vertices"] += vertex_count
row["triangles"] += index_count // 3
row["surface_triangles"] += index_count // 3 - skirt_count
up = []
for tri in range(index_count // 3):
if masks and masks[tri] != 0:
continue
a, b, c = indices[tri * 3:tri * 3 + 3]
if max(a, b, c) >= surf_vertices:
continue
if (n[a * 3 + 2] + n[b * 3 + 2] + n[c * 3 + 2]) / 3.0 < 0.65:
continue
up.append((p[a * 3 + 2] + p[b * 3 + 2] + p[c * 3 + 2]) / 3.0)
row["up_triangles"] += len(up)
row["up_centroids"].extend(up)
if up:
up.sort()
span = up[math.floor(0.95 * (len(up) - 1))] - up[math.floor(0.05 * (len(up) - 1))]
row["tile_spans"].append(span)
tile_rows.append((key, vertex_count, index_count // 3, skirt_count,
len(up), up[0], up[len(up) // 2], up[-1], span))
else:
row["empty"] += 1
tile_rows.append((key, vertex_count, index_count // 3, skirt_count,
0, math.nan, math.nan, math.nan, math.nan))
print(f"version={version} voxel_um={voxel_um} tiles={tile_count} camera_m={camera} yaw={yaw} pitch={pitch}")
print("lod tiles mesh_tiles vertices triangles skirt_triangles upward_surface_triangles "
"upward_centroid_z_m_p05/median/p95 tile_up_z_span_m_p50/p95/max")
for lod in sorted(per_lod):
r = per_lod[lod]
z = sorted(r["up_centroids"])
s = sorted(r["tile_spans"])
def q(values, fraction):
return values[math.floor(fraction * (len(values) - 1))] if values else math.nan
print(f"{lod} {r['tiles']} {r['tiles']-r['empty']} {r['vertices']} {r['triangles']} "
f"{sum(row[3] for row in tile_rows if row[0][3] == lod)} {r['up_triangles']} "
f"{q(z,.05):.4f}/{q(z,.5):.4f}/{q(z,.95):.4f} "
f"{q(s,.5):.4f}/{q(s,.95):.4f}/{max(s) if s else math.nan:.4f}")
print("near_camera_up_tiles (sorted by XY tile-centre distance):")
near = []
for row in tile_rows:
key = row[0]
lod = key[3]
extent = 32 * (1 << lod) * voxel_um / 1_000_000.0
cx = (key[0] + 0.5) * extent
cy = (key[1] + 0.5) * extent
near.append((math.hypot(cx-camera[0], cy-camera[1]), row))
for distance, row in sorted(near)[:30]:
key, verts, tris, skirts, ups, lo, med, hi, span = row
if ups:
print(f"key={key} xy_distance_m={distance:.2f} vertices={verts} triangles={tris} "
f"skirt_triangles={skirts} upward_triangles={ups} z_m={lo:.3f}/{med:.3f}/{hi:.3f} "
f"tile_span_p05_p95_m={span:.3f}")
@@ -1,152 +0,0 @@
#!/usr/bin/env python3
"""Trace review-image pixels through the exported clipmap mesh."""
import array
import math
import struct
import sys
def read_exact(f, count):
data = f.read(count)
if len(data) != count:
raise EOFError((len(data), count))
return data
def floor_div(n, d):
q, r = divmod(n, d)
return q - (r < 0)
def visible_mask(key, desired):
x, y, z, lod = key
extent = 32 << lod
origin = (x * extent, y * extent, z * extent)
mask = 0
for axis in range(3):
for side in range(2):
probe = [origin[i] + extent // 2 for i in range(3)]
probe[axis] = origin[axis] + (extent if side else -1)
neighbor = None
for level in range(9):
neighbor_extent = 32 << level
coord = tuple(floor_div(probe[i], neighbor_extent) for i in range(3)) + (level,)
if coord in desired:
neighbor = level
break
if neighbor is None or neighbor != lod:
mask |= 1 << (axis * 2 + side)
return mask
def ray_box(origin, direction, low, high):
lo, hi = 0.1, 20000.0
for axis in range(3):
if abs(direction[axis]) < 1e-12:
if origin[axis] < low[axis] or origin[axis] > high[axis]:
return None
else:
a = (low[axis] - origin[axis]) / direction[axis]
b = (high[axis] - origin[axis]) / direction[axis]
if a > b:
a, b = b, a
lo, hi = max(lo, a), min(hi, b)
if lo > hi:
return None
return lo, hi
def ray_tri(origin, direction, a, b, c):
e1 = tuple(b[i] - a[i] for i in range(3))
e2 = tuple(c[i] - a[i] for i in range(3))
p = (direction[1]*e2[2]-direction[2]*e2[1],
direction[2]*e2[0]-direction[0]*e2[2],
direction[0]*e2[1]-direction[1]*e2[0])
det = sum(e1[i]*p[i] for i in range(3))
if abs(det) < 1e-10:
return None
inv = 1.0/det
tvec = tuple(origin[i]-a[i] for i in range(3))
u = sum(tvec[i]*p[i] for i in range(3))*inv
if u < 0 or u > 1:
return None
q = (tvec[1]*e1[2]-tvec[2]*e1[1],
tvec[2]*e1[0]-tvec[0]*e1[2],
tvec[0]*e1[1]-tvec[1]*e1[0])
v = sum(direction[i]*q[i] for i in range(3))*inv
if v < 0 or u+v > 1:
return None
t = sum(e2[i]*q[i] for i in range(3))*inv
return t if t >= 0.1 else None
if len(sys.argv) < 8 or len(sys.argv) % 2 != 1:
raise SystemExit("usage: ProbeCaptureRays.py scene.vfmesh camX camY camZ yaw pitch pixelX pixelY [pixelX pixelY ...]")
scene_path = sys.argv[1]
cam = tuple(map(float, sys.argv[2:5]))
yaw, pitch = map(math.radians, map(float, sys.argv[5:7]))
pixels = [(int(sys.argv[i]), int(sys.argv[i+1])) for i in range(7, len(sys.argv), 2)]
width, height, fov = 1600, 900, math.radians(90)
tan_h = math.tan(fov/2)
tan_v = tan_h / (width/height)
forward = (math.sin(yaw)*math.cos(pitch), math.cos(yaw)*math.cos(pitch), math.sin(pitch))
right = (math.cos(yaw), -math.sin(yaw), 0.0)
up = (right[1]*forward[2]-right[2]*forward[1], right[2]*forward[0]-right[0]*forward[2], right[0]*forward[1]-right[1]*forward[0])
with open(scene_path, "rb") as f:
if read_exact(f, 8) != b"VFMSH001":
raise SystemExit("bad scene")
version, voxel_um, count = struct.unpack("<3I", read_exact(f, 12))
scene_cam = struct.unpack("<3d", read_exact(f, 24))
scene_yaw, scene_pitch = struct.unpack("<2d", read_exact(f, 16))
voxel_m = voxel_um / 1_000_000.0
tiles = []
desired = set()
for _ in range(count):
key = struct.unpack("<4i", read_exact(f, 16))
surface_vertices, skirt_count, vertex_count, index_count, mask_count = struct.unpack("<5I", read_exact(f, 20))
positions = array.array("f"); positions.frombytes(read_exact(f, vertex_count*12))
normals = array.array("f"); normals.frombytes(read_exact(f, vertex_count*12))
indices = array.array("I"); indices.frombytes(read_exact(f, index_count*4))
masks = read_exact(f, mask_count)
if sys.byteorder != "little":
positions.byteswap(); normals.byteswap(); indices.byteswap()
desired.add(key)
tiles.append((key, surface_vertices, skirt_count, positions, normals, indices, masks))
print(f"scene={scene_path} tiles={count} camera={cam} yaw={math.degrees(yaw):.3f} pitch={math.degrees(pitch):.3f}")
for px, py in pixels:
nx = 2*px/width - 1
ny = 1 - 2*py/height
direction0 = tuple(forward[i] + nx*tan_h*right[i] + ny*tan_v*up[i] for i in range(3))
length = math.sqrt(sum(v*v for v in direction0))
direction = tuple(v/length for v in direction0)
hits = []
candidate_tiles = 0
for key, surface_vertices, skirt_count, positions, normals, indices, masks in tiles:
x,y,z,lod = key
extent = 32*(1<<lod)*voxel_m
low = (x*extent, y*extent, z*extent)
high = tuple(v+extent for v in low)
if ray_box(cam, direction, low, high) is None:
continue
candidate_tiles += 1
show_mask = visible_mask(key, desired)
for tri in range(len(indices)//3):
m = masks[tri] if masks else 0
if m and (m & show_mask) == 0:
continue
ia,ib,ic = indices[tri*3:tri*3+3]
a,b,c = [],[],[]
for idx, out in ((ia,a),(ib,b),(ic,c)):
base=idx*3
out.extend((positions[base],positions[base+1],positions[base+2]))
t=ray_tri(cam,direction,a,b,c)
if t is None: continue
p=tuple(cam[i]+t*direction[i] for i in range(3))
nz=(normals[ia*3+2]+normals[ib*3+2]+normals[ic*3+2])/3
hits.append((t,key,tri,m,p,nz,ia>=surface_vertices or ib>=surface_vertices or ic>=surface_vertices))
hits.sort(key=lambda h:h[0])
print(f"pixel=({px},{py}) ray={direction} candidate_tiles={candidate_tiles} hits={len(hits)}")
for t,key,tri,m,p,nz,skirt in hits[:12]:
print(f" t={t:.3f}m key={key} tri={tri} mask={m} skirt={skirt} z={p[2]:.3f} normal_z={nz:.3f} xyz=({p[0]:.3f},{p[1]:.3f},{p[2]:.3f})")
@@ -1,132 +0,0 @@
# Linux18 — FloatingIslands stratum boundaries
**Result:** FloatingIslands geometry v3 removes its false lower all-XY seal, keeps the ceiling from the shared upper-boundary seal, and projects missing ceiling cells for every generator. SurfaceWorld hashes match the approved L14 baseline at `8704129` in every checked configuration.
## Scale in the Unreal route
`AVoxelWorld::CoreVoxelSizeCm` defaults to 25 cm, and `GetActiveVoxelSizeCm()` resolves the runtime value ([VoxelWorld.h:300](../../../../Source/VoxelForge/Public/VoxelWorld.h), [VoxelWorld.cpp:7495](../../../../Source/VoxelForge/Private/VoxelWorld.cpp)). The adapter writes the resolved size to the snapshot ([VoxelForgeCoreAdapter.cpp:1019](../../../../Source/VoxelForge/Private/VoxelForgeCoreAdapter.cpp)); `AVoxelWorld` imports it with `ResolvedWorldSnapshot::FromJson` ([VoxelWorld.cpp:7597](../../../../Source/VoxelForge/Private/VoxelWorld.cpp), [VoxelForgeCore.cpp:916](../../../../Standalone/Core/src/VoxelForgeCore.cpp)). S1 records this single active size source and the 32-Core-voxel tile rule ([Round5 REPORT.md](../Round5/REPORT.md#1-one-core-voxel-size-source)).
At the current 25 cm setting, **SurfaceWorld strata use 8 m per slot chunk**: the Unreal surface plan multiplies the slot range by 32 Core voxels ([VoxelForgeCoreAdapter.cpp:280](../../../../Source/VoxelForge/Private/VoxelForgeCoreAdapter.cpp); `CHUNK_SIZE=32` in [VoxelTypes.h:211](../../../../Source/VoxelForge/Public/VoxelTypes.h)). **FloatingIslands uses 4 m per owner-authored chunk**: the adapter’s owner size is `VOXEL_SIZE` ([VoxelForgeCoreAdapter.cpp:33](../../../../Source/VoxelForge/Private/VoxelForgeCoreAdapter.cpp); 12.5 cm in [VoxelTypes.h:213](../../../../Source/VoxelForge/Public/VoxelTypes.h)), and its plan multiplies 32 owner voxels by the serialized owner/Core ratio, currently 12.5/25 = 1/2, or 16 Core voxels ([VoxelForgeCoreAdapter.cpp:441](../../../../Source/VoxelForge/Private/VoxelForgeCoreAdapter.cpp)). For chunks 0…−15 that gives z bounds −60…+4 m. This is the two explicit coordinate conventions in the game route, not a global change from 8 m to 4 m.
Standalone uses the same owner/Core ratio and chunk formula ([OwnerWorldLoader.h:302](../../../../Standalone/Source/OwnerWorldLoader.h), [WorldAssemblyPrototype.h:488](../../../../Standalone/Source/WorldAssemblyPrototype.h)); no current Unreal/standalone scale disagreement was found. L18 also removed the standalone-only two-Core-voxel bounds inset so recipe bounds match the Unreal plan. The owner decides whether either authored scale changes.
## Fix and ceiling
Geometry version 3 preserves the island shapes and removes only the lower all-XY seal. The upper seal calls the shared `VF_ApplyUpperBoundarySeal` density primitive; the shared two-sided seal uses the same upper-band math ([VoxelDensityPrimitives.h:44](../../../../Source/VoxelForge/Public/VoxelDensityPrimitives.h)). Resolved bounds come from each strate’s own range. The shared `AppendStratumBoundaryCeilings` mesh path runs for every generator and LOD, adding a plane at the resolved upper boundary where the mesh lacks coverage. It suppresses an existing plane only when nine probes show full cell coverage ([ShapeWorldInternal.h:36](../../../../Standalone/Core/src/ShapeWorldInternal.h), [FarShellsInternal.h:894](../../../../Standalone/Core/src/FarShellsInternal.h), [VoxelForgeCore.cpp:2207](../../../../Standalone/Core/src/VoxelForgeCore.cpp)). The underside normal points into the room, so the existing material lighting renders the interior face. This adds no FloatingIslands-specific height.
For the captured FloatingIslands strate, the upper bound is **z=+4 m** and its configured 0.5 m seal gives an interior-facing ceiling surface beginning around **z=+3.5 m**. The density probe crosses into the seal at 3.5 m and exits at z=4.019 m; z=7.75, 8.0, and 8.25 m remain air with no crossing. The lower all-XY seal is removed; remaining geometry below −60 m belongs to the lower world and is visible in the ray traces. Thus the apparent 3.5 m “floor” is the retained ceiling when viewed from inside; the 8 m floor is absent. No chunk size changed.
The owner’s decision and version-3 recipe say an underground strate has a ceiling at its configured upper boundary. “Farther to breathe” comes from a taller configured range. I updated the stale architecture-table wording “open void” to say the islands sit beneath the shared ceiling.
## Ceiling continuity
The final audit used 16×16 interior samples per tile and paired samples along same-LOD tile edges. Far LODs pass continuously:
| LOD | Tiles with cap | Interior hits | Max root delta | Edge gaps |
|---:|---:|---:|---:|---:|
| 4 | 48/48 | 12,288/12,288 | 0 cm | 0 |
| 5 | 48/48 | 12,288/12,288 | 0 cm | 0 |
| 6 | 48/48 | 12,288/12,288 | 0 cm | 0 |
| 7 | 48/48 | 12,288/12,288 | 0 cm | 0 |
| 8 | 153/153 | 39,168/39,168 | 0 cm | 0 |
LOD0, 2, and 3 also hit all tested samples. LOD1 missed 3 of 12,288 interior samples (0.387 cm maximum root delta) and had no shared-edge gaps. The readable upward view is `captures/floating-islands-ceiling-up.jpg`.
## Dark tile-aligned patches
They are lower SurfaceWorld triangles visible below the removed false lower cap, not empty rays and not a viewer dark-square overlay. Traces in the final island export found:
- Pixel (700,720): first hit at 104.924 m on non-skirt LOD2 tile `(-2,2,-2,2)`, z=−62.925 m, normal-z 0.266; another LOD2 tile hits z=−69.942 m.
- Pixel (1050,650): first hit at 168.051 m on non-skirt LOD3 tile `(0,2,-2,3)`, z=−72.594 m, normal-z 0.895; lower LOD4 geometry is also hit at z=−112.229 m and −120 m.
The ring probe measures real LOD height steps on those lower surfaces. I left them visible: suppressing those triangles would hide valid lower-stratum geometry, while changing the lower strata or SurfaceWorld would exceed this local fix. The sampled rectangles are not missing tiles or floor holes.
## Cross-LOD ring steps
Entries are median / p95 / maximum absolute edge-height difference in centimetres, then gap count. The L18 column is the final matched island camera. The large remaining steps are lower-stratum terrain, not the upper ceiling.
| LOD edge | L17 before | L17 after | L18 final |
|---|---:|---:|---:|
| 0→1 | 3.451 / 8.920 / 449.158; 14 | —; 0 samples | —; 0 samples |
| 1→2 | 26.642 / 148.262 / 149.862; 0 | 0 / 0 / 0; 0 | 147.141 / 148.403 / 149.862; 0 |
| 2→3 | 0.134 / 198.730 / 773.318; 8 | 0 / 0 / 0; 0 | 128.603 / 200.789 / 773.318; 8 |
| 3→4 | 3.269 / 47.875 / 188.531; 27 | 0 / 0 / 0; 0 | 3.269 / 47.774 / 188.531; 27 |
| 4→5 | 29.975 / 130.496 / 445.444; 6 | 0 / 0 / 30.957; 1 | 29.992 / 124.373 / 443.482; 6 |
| 5→6 | 12.234 / 127.224 / 536.573; 32 | 12.234 / 127.224 / 536.573; 32 | 12.234 / 127.224 / 536.573; 21 |
| 6→7 | 29.013 / 301.752 / 42,624.479; 0 | 28.892 / 291.861 / 945.477; 0 | 29.013 / 301.752 / 42,624.479; 0 |
| 7→8 | 83.843 / 1,225.416 / 3,755.407; 32 | 83.843 / 1,225.416 / 3,755.407; 0 | 83.843 / 1,225.416 / 3,755.407; 0 |
## SurfaceWorld regression hashes
The 14-run check compared each final output to `Saved/Linux/l14-final-hash-sw-clang-off-w12-r5.log` from the L14/`8704129` baseline: Clang `-ffp-contract=off` and GCC default, W1/W8/W12, with five W12 repeats. All 14 matched the whole-view, full-detail, LOD0–8, and exact-query rows. The 24 m crossing check likewise passed all 14 compiler/worker configurations against their L14 compiler-specific references.
Whole view D/M/P/T: `c10697a8f48380c7 / e75c9119a1498cd5 / 49a9a8d1835a6c8c / edcb23288b5e8724`.
Full detail D/M/P/T: `0ee0579bd15cbbe4 / 32e5d4964d610fee / 1932b96ee4b1d910 / 69743c6bad3447dc`.
| LOD | Density | Mesh | Payload | Topology |
|---:|---|---|---|---|
| 0 | `769f2a706d585a72` | `33eeeb39fa443816` | `645621a1d968983f` | `c2457ed905036c9d` |
| 1 | `69cc5a5c0a2c60af` | `b48335f5410c57d5` | `d15c5480162ab8ba` | `feca1bd025823604` |
| 2 | `85deed5683a77202` | `53469895987aeea2` | `e55f8ae7e1532033` | `d5feb12a0e85c09b` |
| 3 | `6518caefb3be7e7f` | `ec513c90b853a614` | `f62fa1137ff17f82` | `ccf1dcf681965816` |
| 4 | `62d4be96021992f4` | `f1e4c6efcc2615a9` | `9dc5f9c88be02f33` | `fe6f55125a07c3bf` |
| 5 | `5e4a8c38b8cea6fc` | `08ee56998aaf21e5` | `541eea8558f26cc8` | `6539374a8b3336d8` |
| 6 | `e036e95b9006945b` | `624a33f941a99b02` | `81b73e14f68bdf86` | `4de4c63ce1f80a56` |
| 7 | `8ee358af56a30d8d` | `46ab3c6184048b7c` | `0a6164b7e68e80c5` | `0c26b85bb03bc831` |
| 8 | `c3458e1cbdb9c471` | `46c03d0994d75192` | `8f89fc5bde12d230` | `d16dc0cf62031898` |
Exact query: 9 probes; density/unclamped `e4d4a8eb95b35933`, detail `efcba20c0c70c415`, collision `e604823a249029bf`.
The 24 m crossing W12×5 hashes match those same aggregate whole-view, full-detail, and exact-query values on both compiler references; the full check compared all 12 rows per run.
FloatingIslands’ representative W12×5 whole-view D/M/P/T is `ca7f375cded78f1d / da003331c554f8f3 / 0d2e74862b4ee500 / b7a7177af8915a21`; full-detail is `fc71abf85f5b9373 / e139b32d42ecfa29 / 28a2414e41de59bd / d61ca68ca64f74ca`. Exact query is `4ef614485815ee30` density/unclamped, `efcba20c0c70c415` detail, `e604823a249029bf` collision. Clang and GCC representative hashes agree, and all nine LOD rows stayed stable across the 28-run matrix.
## Other invariants and Unreal edits
- Final matrix: 28/28 rows passed; repeated runs were stable within each compiler. Route parity had 0 mismatches across 782,026 FI and 910,651 SurfaceWorld exact samples. Proof audits had 0 violations: FI 9,048 blocks / 12,042,888 samples; SurfaceWorld 27,479 / 36,574,549. Readiness negative controls were caught; walkability passed 4,000/4,000 FI and 5,642/5,642 SurfaceWorld samples.
- L3 FP-contract preamble/self-test, L4 `FLazy`, L7 shared cache, L9/L12 proofs, L11 readiness/crash handling, L13 route binding, ARCHITECTURE §8.10, and async/MPSC/Epoch paths remain intact. Both final compiler runs started without the Core FP-contract self-test refusing the build. No async route was added.
- Unreal-side edits are limited to [VoxelForgeCoreAdapter.cpp](../../../../Source/VoxelForge/Private/VoxelForgeCoreAdapter.cpp:453), bumping FI geometry version 2→3 so serialized recipes pick up the lower-seal removal, and the shared [VoxelDensityPrimitives.h](../../../../Source/VoxelForge/Public/VoxelDensityPrimitives.h:44), extracting the common upper-seal math used by v3. The Unreal target could not be compiled on this Linux host.
## Captures
All JPEGs are below 300 KB. Before/after pairs use matched cameras: FI flat square `(-11.6124,-118.2212,-19.8452), yaw/pitch 0/0`; FI island `(-22,-19,-22.8), 0/−4`; SurfaceWorld spawn `(0,-35,-487.94), 0/−22`; horizon uses the same spawn camera with pitch 0. The ceiling view uses the island camera with pitch 80. The SurfaceWorld pairs look the same; the exact hash checks certify its output bit-for-bit.
- FI flat square: `captures/floating-islands-flat-square-before.jpg`, `captures/floating-islands-flat-square-after.jpg`.
- FI low island: `captures/floating-islands-island-view-before.jpg`, `captures/floating-islands-island-view-after.jpg`.
- FI upward ceiling: `captures/floating-islands-ceiling-up.jpg`.
- SurfaceWorld L1 spawn: `captures/surface-world-l1-spawn-before.jpg`, `captures/surface-world-l1-spawn-after.jpg`.
- SurfaceWorld horizon: `captures/surface-world-horizon-before.jpg`, `captures/surface-world-horizon-after.jpg`.
- Flat-square diagnostic without tile edges: `captures/floating-islands-flat-square-no-edges.jpg`.
## Failed or retried runs
- The first density-probe link omitted legacy compatibility objects and failed with undefined references. Relinking with the legacy implementation objects succeeded; both boundary probes then ran.
- The initial 4×4 continuity audit failed at far LODs 4–6 and found edge gaps. The shared all-LOD boundary cap and final full-cell coverage check replaced the center-only deduplication; final 16×16 LOD4–8 continuity passed with zero edge gaps.
- An early matrix checker compared Clang contraction-off hashes directly with GCC default hashes and reported FI mismatches. The checker was corrected to test repeated runs within each compiler and the L14 compiler-specific references; the final 28-row matrix passed.
- An early offscreen capture drew all skirts and showed an artificial slab. The capture now applies the viewer’s hidden-skirt mask; final matched captures were regenerated.
- A GCC build interrupted by owner steering produced no binary and was rerun. A pre-correction Clang build was superseded by the final build. No final build or matrix run failed or exceeded the runtime limits.
## Resources and owner note
Final builds: Clang 19 exit 0 in 31.689 s, peak RSS 436,088 KiB; GCC 14 exit 0 in 48.648 s, peak RSS 903,168 KiB. The largest measured runtime process was 897,276 KiB RSS. All processes stayed below the 6 GiB address-space cap; CPU affinity was 0–11, worker maximum 12, normal priority, and governor `powersave`. No run exceeded 30 minutes or stalled for 15 minutes. See [BuildResources.md](BuildResources.md).
**Owner note:** SurfaceWorld stayed bit-identical to L14. FloatingIslands now retains a ceiling at its configured upper strate boundary while removing the false lower all-XY floor. At the current plan that is a z=+4 m boundary with a 0.5 m seal; its distance above the islands comes from the configured range. The small Unreal edits are listed above and need an owner-machine UBT compile.
## Orchestrator review (Claude)
- **Merged.** SurfaceWorld is bit-identical (14 configs plus the 24 m crossing); the FI false all-XY lower seal
is removed; the ceiling comes from the shared, strate-parameter upper-boundary seal and ceiling path
(owner rule: every strate has a ceiling, height from its own parameters). The Unreal edits are a pure
extraction of the existing upper-seal math plus the FI `geometryVersion` 2→3; they need a UBT compile on
the owner PC.
- **The scale answer:** both conventions are deliberate and agree between Unreal and the standalone
(SurfaceWorld 32 Core voxels per chunk; FloatingIslands 32 owner voxels = 16 Core voxels). Nothing
rescaled.
- **Still open (L19):**
1. Small black holes in the FI ceiling, visible near the top of `floating-islands-flat-square-after.jpg`;
compare LOD1 missing 3/12,288 continuity samples.
2. The owner's ledges are most likely the LOWER stratum's terrain seen through the floorless FI void:
ring steps of 147 cm median at LOD1→2 and 129 cm at 2→3 remain in that terrain. "Valid lower-stratum
geometry" with metre-scale cross-LOD steps is still a bug the owner can see.
- Exports (229 MB `.vfmesh`) are not committed.
@@ -1,151 +0,0 @@
#!/usr/bin/env python3
"""Compare upward mesh heights on shared XY edges between adjacent LOD rings."""
import array
import collections
import math
import struct
import sys
def read_scene(path):
tiles = []
with open(path, "rb") as f:
if f.read(8) != b"VFMSH001":
raise SystemExit(f"{path}: invalid mesh header")
version, voxel_um, count = struct.unpack("<3I", f.read(12))
camera = struct.unpack("<3d", f.read(24))
yaw, pitch = struct.unpack("<2d", f.read(16))
voxel_m = voxel_um / 1_000_000.0
for _ in range(count):
key = struct.unpack("<4i", f.read(16))
surface_vertices, skirt_count, vertex_count, index_count, mask_count = struct.unpack(
"<5I", f.read(20))
positions = array.array("f")
positions.frombytes(f.read(vertex_count * 12))
normals = array.array("f")
normals.frombytes(f.read(vertex_count * 12))
indices = array.array("I")
indices.frombytes(f.read(index_count * 4))
masks = f.read(mask_count)
if sys.byteorder != "little":
positions.byteswap(); normals.byteswap(); indices.byteswap()
triangles = []
for i in range(0, index_count, 3):
if masks and masks[i // 3] != 0:
continue
a, b, c = indices[i:i + 3]
if max(a, b, c) >= surface_vertices:
continue
nz = (normals[a * 3 + 2] + normals[b * 3 + 2] + normals[c * 3 + 2]) / 3.0
if nz < 0.65:
continue
tri = tuple((positions[j * 3], positions[j * 3 + 1], positions[j * 3 + 2])
for j in (a, b, c))
triangles.append(tri)
if triangles:
lod = key[3]
extent = 32 * (1 << lod) * voxel_m
tiles.append({"key": key, "lod": lod, "extent": extent,
"x0": key[0] * extent, "y0": key[1] * extent,
"x1": (key[0] + 1) * extent, "y1": (key[1] + 1) * extent,
"z0": key[2] * extent, "z1": (key[2] + 1) * extent,
"triangles": triangles})
return camera, yaw, pitch, tiles
def height_at(tile, x, y):
best = None
for tri in tile["triangles"]:
(x0, y0, z0), (x1, y1, z1), (x2, y2, z2) = tri
den = (y1 - y2) * (x0 - x2) + (x2 - x1) * (y0 - y2)
if abs(den) < 1.0e-10:
continue
a = ((y1 - y2) * (x - x2) + (x2 - x1) * (y - y2)) / den
b = ((y2 - y0) * (x - x2) + (x0 - x2) * (y - y2)) / den
c = 1.0 - a - b
if min(a, b, c) >= -1.0e-5:
z = a * z0 + b * z1 + c * z2
if best is None or z > best:
best = z
return best
path = sys.argv[1]
camera, yaw, pitch, tiles = read_scene(path)
by_lod = collections.defaultdict(list)
for tile in tiles:
by_lod[tile["lod"]].append(tile)
print(f"scene={path} camera_m={camera} yaw={yaw} pitch={pitch} nonempty_mesh_tiles={len(tiles)}")
print("lod_pair shared_edges samples_both median_abs_cm p95_abs_cm max_abs_cm median_delta_cm gaps")
for lod in range(8):
fine = by_lod[lod]
coarse = by_lod[lod + 1]
deltas = []
edge_rows = []
edge_count = 0
gap_count = 0
# Shared XY edges occur only where tile extents touch and overlap on the other axis.
for a in fine:
for b in coarse:
zlo, zhi = max(a["z0"], b["z0"]), min(a["z1"], b["z1"])
if zhi - zlo <= 1.0e-4:
continue
edge = None
if abs(a["x1"] - b["x0"]) < 1.0e-4 or abs(b["x1"] - a["x0"]) < 1.0e-4:
lo, hi = max(a["y0"], b["y0"]), min(a["y1"], b["y1"])
if hi - lo > 1.0e-4:
edge = ("x", a["x1"] if abs(a["x1"] - b["x0"]) < 1.0e-4 else a["x0"], lo, hi)
if edge is None and (abs(a["y1"] - b["y0"]) < 1.0e-4 or abs(b["y1"] - a["y0"]) < 1.0e-4):
lo, hi = max(a["x0"], b["x0"]), min(a["x1"], b["x1"])
if hi - lo > 1.0e-4:
edge = ("y", a["y1"] if abs(a["y1"] - b["y0"]) < 1.0e-4 else a["y0"], lo, hi)
if edge is None:
continue
edge_count += 1
axis, fixed, lo, hi = edge
epsilon = min(0.02, a["extent"] * 0.001, b["extent"] * 0.001)
samples = 9
matched = 0
edge_deltas = []
for i in range(samples):
t = (i + 0.5) / samples
varying = lo + (hi - lo) * t
if axis == "x":
side_a = 1.0 if abs(a["x1"] - fixed) < 1.0e-4 else -1.0
side_b = 1.0 if abs(b["x1"] - fixed) < 1.0e-4 else -1.0
za = height_at(a, fixed - side_a * epsilon, varying)
zb = height_at(b, fixed - side_b * epsilon, varying)
else:
side_a = 1.0 if abs(a["y1"] - fixed) < 1.0e-4 else -1.0
side_b = 1.0 if abs(b["y1"] - fixed) < 1.0e-4 else -1.0
za = height_at(a, varying, fixed - side_a * epsilon)
zb = height_at(b, varying, fixed - side_b * epsilon)
if za is not None and not zlo - 1.0e-3 <= za <= zhi + 1.0e-3:
za = None
if zb is not None and not zlo - 1.0e-3 <= zb <= zhi + 1.0e-3:
zb = None
if za is not None and zb is not None:
delta = (za - zb) * 100.0
deltas.append(delta)
edge_deltas.append((delta, za, zb, varying))
matched += 1
if matched == 0:
gap_count += 1
elif edge_deltas:
edge_rows.append((max(abs(row[0]) for row in edge_deltas),
a["key"], b["key"], edge, edge_deltas))
if deltas:
absolute = sorted(abs(x) for x in deltas)
signed = sorted(deltas)
p95 = absolute[math.floor(0.95 * (len(absolute) - 1))]
median_abs = absolute[len(absolute) // 2]
median_delta = signed[len(signed) // 2]
print(f"{lod}->{lod+1} {edge_count} {len(deltas)} {median_abs:.3f} {p95:.3f} {max(absolute):.3f} {median_delta:.3f} {gap_count}")
for worst, fine_key, coarse_key, edge, rows in sorted(edge_rows, reverse=True)[:2]:
row = max(rows, key=lambda item: abs(item[0]))
print(f" worst_edge max_abs_cm={worst:.3f} fine={fine_key} coarse={coarse_key} "
f"axis={edge[0]} fixed_m={edge[1]:.3f} span_m={edge[2]:.3f}..{edge[3]:.3f} "
f"sample_v_m={row[3]:.3f} fine_z_m={row[1]:.3f} "
f"coarse_z_m={row[2]:.3f} delta_cm={row[0]:.3f}")
else:
print(f"{lod}->{lod+1} {edge_count} 0 n/a n/a n/a n/a {gap_count}")
@@ -1,82 +0,0 @@
#!/usr/bin/env python3
"""Run the L18 24 m SurfaceWorld crossing hash matrix."""
import os
import re
import signal
import subprocess
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[4]
OUT = ROOT / "Saved/Linux/l18-crossing"
OUT.mkdir(parents=True, exist_ok=True)
if not os.sched_getaffinity(0).issubset(set(range(12))):
raise SystemExit("run under taskset -c 0-11")
BINARIES = {
"clang-off": ROOT / "Standalone/bin/linux/VoxelForgeCoreHeadless-linux18-clang",
"gcc-default": ROOT / "Standalone/bin/linux/VoxelForgeCoreHeadless-linux18-gcc",
}
PATTERN = re.compile(r"^\[Pipeline(?:FullDetailHash|WholeViewHash|LODHash|ExactQueryHash)\].*$", re.M)
rows = []
passed = True
for compiler, binary in BINARIES.items():
for workers, repeat in [(1, 1), (8, 1), (12, 1), (12, 2), (12, 3), (12, 4), (12, 5)]:
name = f"{compiler}-w{workers}-r{repeat}"
logfile = OUT / f"{name}.log"
command = ["prlimit", "--as=6442450944", "--", str(binary),
str(ROOT / "Standalone/data/owner_world.json"),
"--world-assembler-prototype", "--stream-benchmark", "--stream-pipeline",
"--stream-hash", "--force-generate", "--clip-radius=3", "--max-clip-level=8",
f"--workers={workers}", "--camera=0,-35,-487.94,0,-22",
"--camera-step=24,0,0", "--region-crossing", "--recipe=surface-world"]
started = time.monotonic()
peak_rss = 0
with logfile.open("w", encoding="utf-8") as stream:
process = subprocess.Popen(command, stdout=stream, stderr=subprocess.STDOUT,
start_new_session=True)
while process.poll() is None:
pending = [process.pid]
seen = set()
while pending:
pid = pending.pop()
if pid in seen:
continue
seen.add(pid)
try:
pending.extend(int(value) for value in
Path(f"/proc/{pid}/task/{pid}/children").read_text().split())
for line in Path(f"/proc/{pid}/status").read_text().splitlines():
if line.startswith("VmRSS:"):
peak_rss = max(peak_rss, int(line.split()[1]))
break
except (FileNotFoundError, PermissionError, ProcessLookupError, ValueError):
pass
if time.monotonic() - started > 900:
os.killpg(process.pid, signal.SIGTERM)
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
passed = False
break
time.sleep(0.1)
code = process.wait()
elapsed = time.monotonic() - started
actual = PATTERN.findall(logfile.read_text(encoding="utf-8", errors="replace"))
ok = code == 0 and len(actual) == 12
passed &= ok
rows.append((compiler, workers, repeat, code, elapsed, peak_rss, ok, actual))
print(f"[CrossingRun] {name} exit={code} seconds={elapsed:.3f} "
f"peak_rss_kib={peak_rss} hash_rows={len(actual)} status={'PASS' if ok else 'FAIL'}",
flush=True)
reference = None
for compiler, workers, repeat, code, elapsed, peak_rss, ok, hashes in rows:
if reference is None:
reference = hashes
elif hashes != reference:
passed = False
print(f"[CrossingHashMismatch] {compiler} workers={workers} repeat={repeat}", flush=True)
print(f"[CrossingSummary] rows={len(rows)} expected=14 result={'PASS' if passed else 'FAIL'} "
f"path={OUT}", flush=True)
raise SystemExit(0 if passed and len(rows) == 14 else 1)
@@ -1,132 +0,0 @@
#!/usr/bin/env python3
"""Run the L18 deterministic W1/W8/W12 x5 matrix on both supported Linux builds."""
import os
import re
import signal
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[4]
OUT = ROOT / "Saved/Linux/l18-matrix"
OUT.mkdir(parents=True, exist_ok=True)
if not os.sched_getaffinity(0).issubset(set(range(12))):
raise SystemExit("run under taskset -c 0-11")
BINARIES = {
"clang-off": ROOT / "Standalone/bin/linux/VoxelForgeCoreHeadless-linux18-clang",
"gcc-default": ROOT / "Standalone/bin/linux/VoxelForgeCoreHeadless-linux18-gcc",
}
RECIPES = {
"floating-islands": "-10,-31,-22,0,-8",
"surface-world": "0,-35,-487.94,0,-22",
}
HASH_PATTERNS = {
"full": re.compile(r"^\[PipelineFullDetailHash\].*$", re.M),
"whole": re.compile(r"^\[PipelineWholeViewHash\].*$", re.M),
"lod": re.compile(r"^\[PipelineLODHash\].*$", re.M),
"exact": re.compile(r"^\[PipelineExactQueryHash\].*$", re.M),
}
rows = []
all_pass = True
for recipe, camera in RECIPES.items():
for compiler, binary in BINARIES.items():
if not binary.exists():
raise SystemExit(f"missing binary: {binary}")
for workers, repeat in [(1, 1), (8, 1), (12, 1), (12, 2), (12, 3), (12, 4), (12, 5)]:
name = f"{recipe}-{compiler}-w{workers}-r{repeat}"
logfile = OUT / f"{name}.log"
command = ["prlimit", "--as=6442450944", "--", str(binary),
str(ROOT / "Standalone/data/owner_world.json"),
"--world-assembler-prototype", "--stream-benchmark", "--stream-pipeline",
"--stream-hash", "--force-generate", "--clip-radius=3",
"--max-clip-level=8", f"--workers={workers}", f"--camera={camera}",
f"--recipe={recipe}"]
started = time.monotonic()
peak_rss_kib = 0
with logfile.open("w", encoding="utf-8") as stream:
process = subprocess.Popen(command, stdout=stream, stderr=subprocess.STDOUT,
start_new_session=True)
while process.poll() is None:
pending = [process.pid]
seen = set()
while pending:
pid = pending.pop()
if pid in seen:
continue
seen.add(pid)
try:
children = Path(f"/proc/{pid}/task/{pid}/children").read_text().split()
pending.extend(int(value) for value in children)
for line in Path(f"/proc/{pid}/status").read_text().splitlines():
if line.startswith("VmRSS:"):
peak_rss_kib = max(peak_rss_kib, int(line.split()[1]))
break
except (FileNotFoundError, PermissionError, ProcessLookupError, ValueError):
pass
if time.monotonic() - started > 900:
os.killpg(process.pid, signal.SIGTERM)
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
all_pass = False
break
time.sleep(0.1)
code = process.wait()
elapsed = time.monotonic() - started
output = logfile.read_text(encoding="utf-8", errors="replace")
matched = {key: pattern.findall(output) for key, pattern in HASH_PATTERNS.items()}
ok = code == 0 and all(matched.values()) and len(matched["lod"]) == 9
if not ok:
all_pass = False
row = {"recipe": recipe, "compiler": compiler, "workers": workers,
"repeat": repeat, "exit": code, "seconds": elapsed,
"peak_rss_kib": peak_rss_kib, "ok": ok,
"full": matched["full"][-1] if matched["full"] else "",
"whole": matched["whole"][-1] if matched["whole"] else "",
"lod": " || ".join(matched["lod"]),
"exact": matched["exact"][-1] if matched["exact"] else ""}
rows.append(row)
print(f"[MatrixRun] {name} exit={code} seconds={elapsed:.3f} "
f"peak_rss_kib={peak_rss_kib} hash_rows={sum(map(len,matched.values()))} "
f"status={'PASS' if ok else 'FAIL'}", flush=True)
summary = OUT / "summary.tsv"
columns = ["recipe", "compiler", "workers", "repeat", "exit", "seconds", "peak_rss_kib",
"ok", "full", "whole", "lod", "exact"]
with summary.open("w", encoding="utf-8") as f:
f.write("\t".join(columns) + "\n")
for row in rows:
f.write("\t".join(str(row[key]) for key in columns) + "\n")
for recipe in RECIPES:
for compiler in BINARIES:
reference = None
for row in rows:
if row["recipe"] != recipe or row["compiler"] != compiler:
continue
signature = (row["full"], row["whole"], row["lod"], row["exact"])
if reference is None:
reference = signature
elif signature != reference:
print(f"[MatrixMismatch] recipe={recipe} workers={row['workers']} "
f"compiler={compiler} repeat={row['repeat']}", flush=True)
all_pass = False
# Compiler defaults are intentionally recorded separately: Clang uses contraction off,
# while GCC default is the owner-requested control. Report rather than hide any cross-build
# difference; worker/repeat determinism is asserted within each compiler above.
compiler_signatures = {}
for row in rows:
if row["recipe"] == recipe:
compiler_signatures.setdefault(row["compiler"],
(row["full"], row["whole"], row["lod"], row["exact"]))
if len(set(compiler_signatures.values())) > 1:
print(f"[MatrixCompilerDifference] recipe={recipe} compilers="
f"{','.join(compiler_signatures)}", flush=True)
print(f"[MatrixSummary] rows={len(rows)} expected=28 result={'PASS' if all_pass else 'FAIL'} "
f"path={summary}", flush=True)
raise SystemExit(0 if all_pass and len(rows) == 28 else 1)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

@@ -1,70 +0,0 @@
#!/usr/bin/env python3
"""Render matched L19 review captures from the L18 and L19 scene exports."""
import os
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[4]
CAPTURE = ROOT / "Standalone/bin/linux/VoxelForgeOffscreenCapture-linux19-clang"
BEFORE = ROOT / "Standalone/Research/WorldAssemblerM3/Linux18/exports"
AFTER = ROOT / "Saved/Linux/l19-diagnostics"
OUT = ROOT / "Standalone/Research/WorldAssemblerM3/Linux19/captures"
PNG_OUT = ROOT / "Saved/Linux/l19-captures-temp"
LOGS = ROOT / "Saved/Linux/l19-diagnostics"
OUT.mkdir(parents=True, exist_ok=True)
PNG_OUT.mkdir(parents=True, exist_ok=True)
env = os.environ.copy()
env["LP_NUM_THREADS"] = "12"
env["XDG_CACHE_HOME"] = str(ROOT / "Saved/Linux/mesa-cache")
views = [
("floating-islands-flat-square-before", BEFORE / "floating-islands-flat-square.vfmesh",
(-11.612444, -118.221237, -19.8452), 0, 0, True),
("floating-islands-flat-square-after", AFTER / "floating-islands-flat-square-after.vfmesh",
(-11.612444, -118.221237, -19.8452), 0, 0, True),
("floating-islands-owner-angle-before", BEFORE / "floating-islands-island-view.vfmesh",
(-22, -19, -22.8), 0, -4, True),
("floating-islands-owner-angle-after", AFTER / "floating-islands-island-view-after.vfmesh",
(-22, -19, -22.8), 0, -4, True),
("floating-islands-owner-ground-before", AFTER / "floating-islands-owner-ground-before.vfmesh",
(-6.3, -19.06, -21.0), 0, -4, True),
("floating-islands-owner-ground-after", AFTER / "floating-islands-owner-ground-after.vfmesh",
(-6.3, -19.06, -21.0), 0, -4, True),
("floating-islands-ceiling-up-after", AFTER / "floating-islands-island-view-after.vfmesh",
(-22, -19, -22.8), 0, 80, True),
("surface-world-l1-spawn-before", BEFORE / "surface-world-l1-spawn.vfmesh",
(0, -35, -487.94), 0, -22, False),
("surface-world-l1-spawn-after", AFTER / "surface-world-l1-spawn-after.vfmesh",
(0, -35, -487.94), 0, -22, False),
("surface-world-horizon-before", BEFORE / "surface-world-l1-spawn.vfmesh",
(0, -35, -487.94), 0, 0, False),
("surface-world-horizon-after", AFTER / "surface-world-l1-spawn-after.vfmesh",
(0, -35, -487.94), 0, 0, False),
("surface-world-rings-above-before", BEFORE / "surface-world-l1-spawn.vfmesh",
(0, -35, -280), 0, -90, True),
("surface-world-rings-above-after", AFTER / "surface-world-l1-spawn-after.vfmesh",
(0, -35, -280), 0, -90, True),
]
for name, scene, camera, yaw, pitch, tile_edges in views:
if not scene.exists():
raise SystemExit(f"missing scene: {scene}")
png = PNG_OUT / f"{name}.png"
jpg = OUT / f"{name}.jpg"
render_log = LOGS / f"{name}-render.log"
convert_log = LOGS / f"{name}-jpeg.log"
command = [str(CAPTURE), str(scene), str(png), "--size=1600x900",
"--shade=readable", f"--tile-edges={'on' if tile_edges else 'off'}",
"--tile-edge-width-m=0.15", "--camera-m="+",".join(map(str, camera)),
f"--yaw-deg={yaw}", f"--pitch-deg={pitch}"]
with render_log.open("w", encoding="utf-8") as stream:
subprocess.run(command, cwd=ROOT, env=env, stdout=stream,
stderr=subprocess.STDOUT, check=True)
ffmpeg = ["ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error", "-y",
"-i", str(png), "-frames:v", "1", "-q:v", "4", str(jpg)]
with convert_log.open("w", encoding="utf-8") as stream:
subprocess.run(ffmpeg, cwd=ROOT, env=env, stdout=stream,
stderr=subprocess.STDOUT, check=True)
if jpg.stat().st_size > 300_000:
raise SystemExit(f"{jpg.name} exceeds the 300 KB review limit")
print(f"[Capture] {jpg.relative_to(ROOT)} bytes={jpg.stat().st_size} status=PASS", flush=True)
@@ -1,172 +0,0 @@
#!/usr/bin/env python3
"""Strict L19 audit of FloatingIslands roof coverage at every LOD."""
import array
import collections
import math
import struct
import sys
def read_exact(stream, size):
data = stream.read(size)
if len(data) != size:
raise EOFError(f"wanted {size} bytes, got {len(data)}")
return data
def height_at(triangles, x, y, preferred_z):
best = None
for (x0, y0, z0), (x1, y1, z1), (x2, y2, z2) in triangles:
den = (y1-y2)*(x0-x2)+(x2-x1)*(y0-y2)
if abs(den) < 1.0e-10:
continue
a = ((y1-y2)*(x-x2)+(x2-x1)*(y-y2))/den
b = ((y2-y0)*(x-x2)+(x0-x2)*(y-y2))/den
c = 1.0-a-b
if min(a,b,c) >= -1.0e-5:
z = a*z0+b*z1+c*z2
if best is None or abs(z-preferred_z) < abs(best-preferred_z):
best = z
return best
def quantile(values, fraction):
if not values:
return math.nan
ordered = sorted(values)
return ordered[math.floor(fraction*(len(ordered)-1))]
if len(sys.argv) != 3:
raise SystemExit("usage: CeilingContinuity.py scene.vfmesh expected-cap-plane-metres")
scene_path = sys.argv[1]
root_z = float(sys.argv[2])
tiles = {}
voxel_size_m = None
with open(scene_path, "rb") as stream:
if read_exact(stream, 8) != b"VFMSH001":
raise SystemExit("invalid VFMSH001 scene")
version, voxel_um, tile_count = struct.unpack("<3I", read_exact(stream, 12))
camera = struct.unpack("<3d", read_exact(stream, 24))
yaw, pitch = struct.unpack("<2d", read_exact(stream, 16))
voxel_size_m = voxel_um/1_000_000.0
for _ in range(tile_count):
key = struct.unpack("<4i", read_exact(stream, 16))
surface_vertices, skirt_count, vertex_count, index_count, mask_count = struct.unpack(
"<5I", read_exact(stream, 20))
positions = array.array("f")
positions.frombytes(read_exact(stream, vertex_count*12))
normals = array.array("f")
normals.frombytes(read_exact(stream, vertex_count*12))
indices = array.array("I")
indices.frombytes(read_exact(stream, index_count*4))
masks = read_exact(stream, mask_count)
if sys.byteorder != "little":
positions.byteswap()
normals.byteswap()
indices.byteswap()
extent = 32*(1 << key[3])*voxel_size_m
z0, z1 = key[2]*extent, (key[2]+1)*extent
ceiling = []
for triangle in range(index_count//3):
if masks and masks[triangle] != 0:
continue
a,b,c = indices[triangle*3:triangle*3+3]
if max(a,b,c) >= surface_vertices:
continue
nz = (normals[a*3+2]+normals[b*3+2]+normals[c*3+2])/3.0
if nz > -0.65:
continue
points = tuple((positions[v*3],positions[v*3+1],positions[v*3+2])
for v in (a,b,c))
center_z = sum(point[2] for point in points)/3.0
if abs(center_z-root_z) <= 1.0:
ceiling.append(points)
tiles[key] = {
"extent": extent, "x0": key[0]*extent, "y0": key[1]*extent,
"x1": (key[0]+1)*extent, "y1": (key[1]+1)*extent,
"z0": z0, "z1": z1, "ceiling": ceiling,
}
by_lod = collections.defaultdict(dict)
for key, tile in tiles.items():
if tile["z0"] <= root_z+1.0 and tile["z1"] >= root_z-1.0:
by_lod[key[3]][key] = tile
print(f"scene={scene_path} version={version} voxel_um={voxel_um} tiles={tile_count} "
f"camera_m={camera} yaw={yaw} pitch={pitch} expected_cap_m={root_z:.9f}")
print("lod zband_tiles cap_tiles missing_tiles cap_triangles face_z_m_p05/median/p95 "
"tile_samples hit_samples max_abs_root_delta_cm shared_edges expected_edge_samples "
"paired_edge_samples edge_gaps edge_delta_cm_median/p95/max")
all_pass = True
all_misses = []
for lod in range(9):
target = by_lod[lod]
cap_tiles = {key: tile for key,tile in target.items() if tile["ceiling"]}
face_z = [point[2] for tile in cap_tiles.values() for tri in tile["ceiling"]
for point in tri]
deltas = []
sample_count = 0
hit_count = 0
for key,tile in target.items():
if not tile["ceiling"]:
continue
for iy in range(16):
for ix in range(16):
x = tile["x0"]+(ix+0.5)*tile["extent"]/16
y = tile["y0"]+(iy+0.5)*tile["extent"]/16
sample_count += 1
height = height_at(tile["ceiling"],x,y,root_z)
if height is not None:
hit_count += 1
deltas.append(abs(height-root_z)*100.0)
else:
all_misses.append((lod,key,ix,iy,x,y))
edge_deltas = []
edge_count = 0
edge_gaps = 0
edge_gap_samples = 0
for key,a in cap_tiles.items():
x,y,z,level = key
for neighbor_key,axis in (((x+1,y,z,level),"x"),((x,y+1,z,level),"y")):
b = cap_tiles.get(neighbor_key)
if b is None:
continue
edge_count += 1
epsilon = min(0.02,a["extent"]*1.0e-4)
matched = 0
for index in range(33):
t = (index+0.5)/33
if axis == "x":
fixed = a["x1"]
varying = a["y0"]+(a["y1"]-a["y0"])*t
za = height_at(a["ceiling"],fixed-epsilon,varying,root_z)
zb = height_at(b["ceiling"],fixed+epsilon,varying,root_z)
else:
fixed = a["y1"]
varying = a["x0"]+(a["x1"]-a["x0"])*t
za = height_at(a["ceiling"],varying,fixed-epsilon,root_z)
zb = height_at(b["ceiling"],varying,fixed+epsilon,root_z)
if za is not None and zb is not None:
edge_deltas.append(abs(za-zb)*100.0)
matched += 1
edge_gap_samples += 33-matched
if matched != 33:
edge_gaps += 1
missing = len(target)-len(cap_tiles)
max_root = max(deltas) if deltas else math.nan
print(f"{lod} {len(target)} {len(cap_tiles)} {missing} "
f"{sum(len(tile['ceiling']) for tile in cap_tiles.values())} "
f"{quantile(face_z,.05):.6f}/{quantile(face_z,.5):.6f}/{quantile(face_z,.95):.6f} "
f"{sample_count} {hit_count} {max_root:.3f} {edge_count} {edge_count*33} {len(edge_deltas)} "
f"{edge_gaps} {quantile(edge_deltas,.5):.3f}/{quantile(edge_deltas,.95):.3f}/"
f"{max(edge_deltas) if edge_deltas else math.nan:.3f}")
if target and (missing or hit_count != sample_count or edge_gap_samples):
all_pass = False
for lod,key,ix,iy,x,y in all_misses:
print(f" miss lod={lod} key={key} sample=({ix},{iy}) xy_m=({x:.6f},{y:.6f})")
print(f"[CeilingContinuityL19] total_misses={len(all_misses)} "
f"result={'PASS' if all_pass else 'FAIL'} criteria=LOD0-8 every 16x16 interior ray hits; "
"every shared same-LOD edge sample has paired hits")
raise SystemExit(0 if all_pass else 1)
@@ -1,50 +0,0 @@
#!/usr/bin/env python3
"""Check deterministic matrices and protected SurfaceWorld identities against L14."""
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[4]
MATRIX = ROOT / "Saved/Linux/l19-matrix"
CROSSING = ROOT / "Saved/Linux/l19-crossing"
ROW = re.compile(r"^\[Pipeline(?:FullDetailHash|WholeViewHash|LODHash|ExactQueryHash)\].*$", re.M)
LOD = re.compile(r"^\[PipelineLODHash\] lod=(\d+) .*$", re.M)
failed = []
def stable_rows(path):
rows = ROW.findall(path.read_text(encoding="utf-8", errors="replace"))
full = next((row for row in rows if row.startswith("[PipelineFullDetailHash]")), None)
exact = next((row for row in rows if row.startswith("[PipelineExactQueryHash]")), None)
lods = {int(match.group(1)): match.group(0) for match in LOD.finditer(
path.read_text(encoding="utf-8", errors="replace"))}
return rows, full, exact, {level: lods.get(level) for level in range(3)}
for compiler in ("clang-off", "gcc-default"):
baseline_name = "clang-off" if compiler == "clang-off" else "gcc-default"
baseline = ROOT / f"Saved/Linux/l14-final-hash-sw-{baseline_name}-w12-r5.log"
expected = stable_rows(baseline)
logs = sorted(MATRIX.glob(f"surface-world-{compiler}-w*-r*.log"))
if len(logs) != 7:
failed.append(f"matrix {compiler}: expected 7 rows, found {len(logs)}")
for path in logs:
actual = stable_rows(path)
if len(actual[0]) != 12 or actual[1:] != expected[1:]:
failed.append(f"protected SurfaceWorld mismatch: {path.name}")
crossing_baseline_name = "clang" if compiler == "clang-off" else "gcc"
crossing_baseline = ROOT / f"Saved/Linux/l14-final-crossing-24m-{crossing_baseline_name}-w12.log"
expected_crossing = stable_rows(crossing_baseline)
crossing_logs = sorted(CROSSING.glob(f"{compiler}-w*-r*.log"))
if len(crossing_logs) != 7:
failed.append(f"crossing {compiler}: expected 7 rows, found {len(crossing_logs)}")
for path in crossing_logs:
actual = stable_rows(path)
if len(actual[0]) != 12 or actual[1:] != expected_crossing[1:]:
failed.append(f"protected crossing identity mismatch: {path.name}")
print(f"[L19ProtectedHashGate] SurfaceWorld LOD0-2, full-detail, and exact query hashes "
f"result={'FAIL' if failed else 'PASS'}")
for failure in failed:
print(f"[L19HashMismatch] {failure}")
raise SystemExit(1 if failed else 0)
@@ -1,123 +0,0 @@
# Linux19 — FloatingIslands ceiling and LOD ledges
**Status:** The ceiling is now closed at every LOD. The lower-terrain ledges are diagnosed but remain visible: the required change affects protected SurfaceWorld LOD2 output, so I stopped before changing it and asked for your decision.
## Findings and changes
The ceiling holes came from two checks in the shared boundary-cap path. It required density to cross from solid just below a strate's configured top to air just above it. Some of the field remains solid above that top, so the old test omitted those cap cells. The duplicate-cap check also sampled only inside each cell and could miss partial perimeter coverage. The path now emits a cap wherever the field is solid just below the configured top, and checks a 5×5 grid including the perimeter before suppressing a fallback cap.
The ledges are real upward-facing, non-skirt terrain triangles from the lower SurfaceWorld stratum visible below the FloatingIslands stratum. The combined recipe log identifies the SurfaceWorld field as strate index 1, chunks −16…−79, built from the owner surface parameters and biome map; the FloatingIslands plan is index 0, chunks 0…−15. At the worst LOD1→2 sample, the fine mesh is at z=−60.497 m and the coarse mesh at z=−61.996 m (149.862 cm apart). The LOD2→3 maximum is 773.318 cm, at z=−73.080 m versus −65.347 m.
The ring probe excludes skirts and masked triangles. The far-ground refinement routine only runs at LOD4 and above, so it cannot cause the LOD1→2 or LOD2→3 steps. Density dispatch is coordinate-based rather than LOD-based; the meshes sample that field on progressively coarser grids (0.5 m, 1 m, and 2 m at LOD1–3). The evidence points to resolution-dependent surface extraction of the lower SurfaceWorld terrain near the strate transition, not a different LOD recipe or a ceiling triangle. The L13 route audit also found no page/native or exact-query mismatches. The owner’s lower-stratum reading is supported.
SurfaceWorld at its L1 spawn has small L1→2 and L2→3 median differences, but it has larger outliers at farther rings: L3→4 reaches 1,190.974 cm, and L4→5 reaches 491.570 cm. Those high far-ring values are in the table below; the matched spawn, horizon, and above-ring captures are byte-identical before and after.
I did not change the ledge geometry. The most direct fix needs to change SurfaceWorld LOD2, which your rule protects pending an owner decision. The pending question is whether to allow that change.
The shared Core fix changes the recipe output identity version from `farHorizonVersion` 3 to 4. It changes no density query, stratum position, scale, or async route. No Unreal files were edited.
## Ring tables
Values are median / p95 / maximum absolute edge-height difference in cm, then the probe's no-hit edge count. `Before → after` is identical for every row because this round changed the ceiling path, not the lower upward-facing terrain.
### FloatingIslands camera
| LOD edge | Edges / samples | Before (cm; gaps) | After (cm; gaps) |
|---|---:|---:|---:|
| 0→1 | 0 / 0 | — | — |
| 1→2 | 33 / 231 | 147.141 / 148.403 / 149.862; 0 | 147.141 / 148.403 / 149.862; 0 |
| 2→3 | 49 / 308 | 128.603 / 200.789 / 773.318; 8 | 128.603 / 200.789 / 773.318; 8 |
| 3→4 | 64 / 277 | 3.269 / 47.774 / 188.531; 27 | 3.269 / 47.774 / 188.531; 27 |
| 4→5 | 72 / 544 | 29.992 / 124.373 / 443.482; 6 | 29.992 / 124.373 / 443.482; 6 |
| 5→6 | 64 / 266 | 12.234 / 127.224 / 536.573; 32 | 12.234 / 127.224 / 536.573; 32 |
| 6→7 | 32 / 264 | 29.013 / 301.752 / 42,624.479; 0 | 29.013 / 301.752 / 42,624.479; 0 |
| 7→8 | 64 / 275 | 83.843 / 1,225.416 / 3,755.407; 32 | 83.843 / 1,225.416 / 3,755.407; 32 |
### SurfaceWorld L1 spawn camera
| LOD edge | Edges / samples | Before (cm; gaps) | After (cm; gaps) |
|---|---:|---:|---:|
| 0→1 | 46 / 288 | 0.178 / 0.594 / 1.171; 10 | 0.178 / 0.594 / 1.171; 10 |
| 1→2 | 32 / 288 | 1.419 / 4.990 / 10.438; 0 | 1.419 / 4.990 / 10.438; 0 |
| 2→3 | 34 / 256 | 2.179 / 12.648 / 35.355; 2 | 2.179 / 12.648 / 35.355; 2 |
| 3→4 | 40 / 265 | 5.099 / 35.999 / 1,190.974; 5 | 5.099 / 35.999 / 1,190.974; 5 |
| 4→5 | 58 / 270 | 0.235 / 3.694 / 491.570; 14 | 0.235 / 3.694 / 491.570; 14 |
| 5→6 | 65 / 266 | 12.234 / 127.224 / 536.573; 33 | 12.234 / 127.224 / 536.573; 33 |
| 6→7 | 41 / 269 | 28.238 / 291.861 / 945.477; 7 | 28.238 / 291.861 / 945.477; 7 |
| 7→8 | 32 / 275 | 83.843 / 1,225.416 / 3,755.407; 0 | 83.843 / 1,225.416 / 3,755.407; 0 |
## Ceiling continuity
The strict audit casts 16×16 interior rays per tile and pairs every shared same-LOD edge sample. Before the fix it found three LOD1 interior misses, one LOD2 interior miss, and 10 unpaired LOD1 perimeter samples. After the fix it found zero misses and zero edge gaps at all LODs.
| LOD | Cap tiles | Interior hits | Paired edge samples | Max root delta (cm) | Misses / gaps |
|---:|---:|---:|---:|---:|---:|
| 0 | 64/64 | 16,384/16,384 | 3,696/3,696 | 0 | 0 / 0 |
| 1 | 48/48 | 12,288/12,288 | 2,376/2,376 | 0 | 0 / 0 |
| 2 | 48/48 | 12,288/12,288 | 2,376/2,376 | 0.025 | 0 / 0 |
| 3 | 48/48 | 12,288/12,288 | 2,376/2,376 | 0.025 | 0 / 0 |
| 4 | 48/48 | 12,288/12,288 | 2,376/2,376 | 0 | 0 / 0 |
| 5 | 48/48 | 12,288/12,288 | 2,376/2,376 | 0 | 0 / 0 |
| 6 | 48/48 | 12,288/12,288 | 2,376/2,376 | 0 | 0 / 0 |
| 7 | 48/48 | 12,288/12,288 | 2,376/2,376 | 0 | 0 / 0 |
| 8 | 153/153 | 39,168/39,168 | 8,976/8,976 | 0 | 0 / 0 |
Full output is in `Saved/Linux/l19-diagnostics/fi_roof_after.log`; the pre-fix strict audit is `Saved/Linux/l19-diagnostics/baseline-fi-ceiling-strict.log`.
## Hashes and audits
Clang 19 (`-ffp-contract=off`) and GCC 14 (default) passed 28/28 runs: FI and SW, W1/W8/W12, with W12 repeated five times. The 24 m crossing passed 14/14 runs, with 12 matching hash rows each; its W1/W8/W12×5 hashes also matched the L14 compiler-specific references. The protected SurfaceWorld hash gate passed across the matrix and crossing. SurfaceWorld LOD0–2, full-detail, and exact-query hashes match L14 across the matrix and crossing; the representative W12 LOD3 hash also matches. LOD4–8 mesh/payload/topology hashes include the version-4 salt, and the tested captures show no visible SW change.
Representative Clang W12 hashes (density / mesh / payload / topology):
| Output | Full detail | Whole view |
|---|---|---|
| FloatingIslands | `43034299d33f2536 / a41e8353ec4bbe9c / cd0e3e15eef827b0 / 0b3c3f13cc1d6f8a` | `00bc3607a7839854 / 4baa66127c2b0892 / e11ef05e851a1517 / 1278bc4b1fffb869` |
| SurfaceWorld | `0ee0579bd15cbbe4 / 32e5d4964d610fee / 1932b96ee4b1d910 / 69743c6bad3447dc` | `c10697a8f48380c7 / 4197fc1072f0ff58 / 7b3e616ec9459851 / c879e35592bf33e5` |
SurfaceWorld LOD0–2 hashes (density / mesh / payload / topology):
| LOD | Hash |
|---:|---|
| 0 | `769f2a706d585a72 / 33eeeb39fa443816 / 645621a1d968983f / c2457ed905036c9d` |
| 1 | `69cc5a5c0a2c60af / b48335f5410c57d5 / d15c5480162ab8ba / feca1bd025823604` |
| 2 | `85deed5683a77202 / 53469895987aeea2 / e55f8ae7e1532033 / d5feb12a0e85c09b` |
Exact queries: FI density/unclamped `87e5c0dbf9ee9ee2`; SW density/unclamped `e4d4a8eb95b35933`; both detail `efcba20c0c70c415`, collision `e604823a249029bf`.
L13 route parity passed in all four audit runs (both recipes, both compilers), with zero mismatches. FI checked 782,026 exact-query samples; SW checked 910,651. L9 proof audits reported zero violations: FI 9,192 blocks / 12,234,552 samples; SW 27,479 / 36,574,549 samples. Full logs are in `Saved/Linux/l19-audits/`.
L3 FP-contract preamble/self-test, L4 `FLazy`, L7 shared cache, L9/L12 proofs, L11 readiness and crash handling, L13 route binding, the L18 shared ceiling, `ARCHITECTURE.md` §8.10, and the CLAUDE.md async rules remain intact. The only source edits are in shared Core; the only architecture addition is §8.38.
## Captures
Every JPEG is at most 50 KiB (limit 300 KB). `floating-islands-owner-ground-after.jpg` is the low view across the FI ground, matching the owner's angle. SurfaceWorld spawn, horizon, and above-ring before/after JPEGs are byte-identical.
- FI: `captures/floating-islands-flat-square-before.jpg`, `captures/floating-islands-flat-square-after.jpg`, `captures/floating-islands-owner-angle-before.jpg`, `captures/floating-islands-owner-angle-after.jpg`, `captures/floating-islands-owner-ground-before.jpg`, `captures/floating-islands-owner-ground-after.jpg`, `captures/floating-islands-ceiling-up-after.jpg`.
- SW: `captures/surface-world-l1-spawn-before.jpg`, `captures/surface-world-l1-spawn-after.jpg`, `captures/surface-world-horizon-before.jpg`, `captures/surface-world-horizon-after.jpg`, `captures/surface-world-rings-above-before.jpg`, `captures/surface-world-rings-above-after.jpg`.
## Failed and retried runs
- The pre-fix strict FI ceiling audit failed as expected: 4 interior misses and 10 unpaired LOD1 edge samples. The earlier loose report had counted only the 3 LOD1 interior misses. The final strict audit passed.
- A ceiling audit was mistakenly run on the ordinary SW terrain export; it reported 47,837 non-roof ray misses. That was the wrong target for this audit and was discarded.
- The first continuity-audit attempt was interrupted before results. `/usr/bin/time` was unavailable (exit 127); the repository `MeasureBuild.py` wrapper was used instead.
- The first FI auto-camera export used clip radius 0 / max LOD 0 and exited with `std::bad_alloc` (1.710 s, peak RSS 2,151,292 KiB). Retrying at radius 3 / LOD8 / W12 succeeded (10.786 s, peak RSS 597,976 KiB).
- An exploratory native-heightfield refinement extension did not change the FI L1→2 or L2→3 ring values and was reverted. A temporary debug probe/build used to inspect the ceiling field was also removed before the final build.
- The first hash-gate run happened before crossing logs existed and failed for zero crossing rows. After the 24 m crossing completed, the gate passed.
- The first SW ring probe did not inherit the CPU affinity limit; it was rerun under `taskset -c 0-11`, and the constrained table is unchanged.
- `renice -n 0` was denied by the environment. Runs stayed at inherited nice level 5 (below normal priority); the governor was left unchanged at `powersave`.
No build or run exceeded 15 minutes or 30 minutes. All final builds and run children used CPUs 0–11, at most 12 workers, `LP_NUM_THREADS=12` for llvmpipe, and the 6 GiB address-space cap. Peak RSS was 903,324 KiB (GCC build); the matrix, crossing, audits, roof audit, and captures peaked at 583,180, 550,832, 857,964, 541,972, and 510,680 KiB respectively. The outer matrix took 343.684 s; the crossing took 46.354 s. Governor: `powersave`.
**Owner note:** The FI ceiling now closes cleanly at z=+4 m. The visible ledges are lower SurfaceWorld terrain and are a real LOD sampling mismatch, not skirts. SurfaceWorld L1→2 and L2→3 agree closely at the spawn, but its far rings have larger outliers. The ledge fix needs permission to change SurfaceWorld LOD2; no such mesh change is included here. Nothing was committed, pushed, or stashed.
## Orchestrator review (Claude)
- Merged. The ceiling specks seen in L18's flat-square capture are gone in the L19 capture (checked by me),
and the strict audit reads 0 misses / 0 gaps at all LODs. SurfaceWorld LOD0–2, full-detail and exact
queries are unchanged; the far mesh hashes carry the `farHorizonVersion` 3→4 salt, with byte-identical
captures.
- Luna correctly stopped at the protected SurfaceWorld LOD2 rule. Ledge decision: the defect is at the
strate interface (lower stratum top near z≈−60…−73 m, sampled on 0.5/1/2 m grids at LOD1–3), which is
where the two chunk-unit conventions meet. It goes into L20 (the units/layers design round) as its
concrete test case, rather than being patched alone first.
@@ -1,79 +0,0 @@
#!/usr/bin/env python3
"""Run the L9 uniform-block proof and L13 route parity audits."""
import os
import signal
import subprocess
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[4]
OUT = ROOT / "Saved/Linux/l19-audits"
OUT.mkdir(parents=True, exist_ok=True)
if not os.sched_getaffinity(0).issubset(set(range(12))):
raise SystemExit("run under taskset -c 0-11")
BINARIES = {
"clang-off": ROOT / "Standalone/bin/linux/VoxelForgeCoreHeadless-linux19-clang",
"gcc-default": ROOT / "Standalone/bin/linux/VoxelForgeCoreHeadless-linux19-gcc",
}
RECIPES = {
"floating-islands": ("-22,-19,-22.8,0,-4", "--recipe=floating-islands"),
"surface-world": ("0,-35,-487.94,0,-22", "--recipe=surface-world"),
}
passed = True
for recipe, (camera, recipe_flag) in RECIPES.items():
for compiler, binary in BINARIES.items():
name = f"{recipe}-{compiler}"
logfile = OUT / f"{name}.log"
command = ["prlimit", "--as=6442450944", "--", str(binary),
str(ROOT / "Standalone/data/owner_world.json"),
"--world-assembler-prototype", "--stream-benchmark", "--stream-pipeline",
"--stream-hash", "--force-generate", "--clip-radius=3", "--max-clip-level=8",
"--workers=12", f"--camera={camera}", recipe_flag,
"--audit-uniform-block-proofs", "--audit-route-parity"]
started = time.monotonic()
peak_rss = 0
timed_out = False
with logfile.open("w", encoding="utf-8") as stream:
process = subprocess.Popen(command, stdout=stream, stderr=subprocess.STDOUT,
start_new_session=True)
while process.poll() is None:
pending, seen = [process.pid], set()
while pending:
pid = pending.pop()
if pid in seen:
continue
seen.add(pid)
try:
pending.extend(int(value) for value in
Path(f"/proc/{pid}/task/{pid}/children").read_text().split())
for line in Path(f"/proc/{pid}/status").read_text().splitlines():
if line.startswith("VmRSS:"):
peak_rss = max(peak_rss, int(line.split()[1]))
break
except (FileNotFoundError, PermissionError, ProcessLookupError, ValueError):
pass
if time.monotonic() - started > 900:
os.killpg(process.pid, signal.SIGTERM)
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
timed_out = True
passed = False
break
time.sleep(0.1)
code = process.wait()
elapsed = time.monotonic() - started
log = logfile.read_text(encoding="utf-8", errors="replace")
route_lines = [line for line in log.splitlines() if line.startswith("[RouteParityAudit]")]
proof_lines = [line for line in log.splitlines() if line.startswith("[UniformBlockProofAudit]")]
route_ok = bool(route_lines) and route_lines[-1].endswith("status=PASS")
proof_ok = bool(proof_lines) and "violations=0" in proof_lines[-1]
ok = code == 0 and not timed_out and route_ok and proof_ok
passed &= ok
print(f"[AuditRun] {name} exit={code} seconds={elapsed:.3f} peak_rss_kib={peak_rss} "
f"route={route_ok} proofs={proof_ok} status={'PASS' if ok else 'FAIL'}", flush=True)
print(f"[AuditSummary] rows={len(RECIPES)*len(BINARIES)} expected=4 "
f"result={'PASS' if passed else 'FAIL'} path={OUT}", flush=True)
raise SystemExit(0 if passed else 1)
@@ -1,81 +0,0 @@
#!/usr/bin/env python3
"""Run the L19 24 m SurfaceWorld crossing hash matrix."""
import os
import re
import signal
import subprocess
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[4]
OUT = ROOT / "Saved/Linux/l19-crossing"
OUT.mkdir(parents=True, exist_ok=True)
if not os.sched_getaffinity(0).issubset(set(range(12))):
raise SystemExit("run under taskset -c 0-11")
BINARIES = {
"clang-off": ROOT / "Standalone/bin/linux/VoxelForgeCoreHeadless-linux19-clang",
"gcc-default": ROOT / "Standalone/bin/linux/VoxelForgeCoreHeadless-linux19-gcc",
}
PATTERN = re.compile(r"^\[Pipeline(?:FullDetailHash|WholeViewHash|LODHash|ExactQueryHash)\].*$", re.M)
RUNS = [(1, 1), (8, 1), (12, 1), (12, 2), (12, 3), (12, 4), (12, 5)]
passed = True
for compiler, binary in BINARIES.items():
reference = None
for workers, repeat in RUNS:
name = f"{compiler}-w{workers}-r{repeat}"
logfile = OUT / f"{name}.log"
command = ["prlimit", "--as=6442450944", "--", str(binary),
str(ROOT / "Standalone/data/owner_world.json"),
"--world-assembler-prototype", "--stream-benchmark", "--stream-pipeline",
"--stream-hash", "--force-generate", "--clip-radius=3", "--max-clip-level=8",
f"--workers={workers}", "--camera=0,-35,-487.94,0,-22",
"--camera-step=24,0,0", "--region-crossing", "--recipe=surface-world"]
started = time.monotonic()
peak_rss = 0
timed_out = False
with logfile.open("w", encoding="utf-8") as stream:
process = subprocess.Popen(command, stdout=stream, stderr=subprocess.STDOUT,
start_new_session=True)
while process.poll() is None:
pending, seen = [process.pid], set()
while pending:
pid = pending.pop()
if pid in seen:
continue
seen.add(pid)
try:
pending.extend(int(value) for value in
Path(f"/proc/{pid}/task/{pid}/children").read_text().split())
for line in Path(f"/proc/{pid}/status").read_text().splitlines():
if line.startswith("VmRSS:"):
peak_rss = max(peak_rss, int(line.split()[1]))
break
except (FileNotFoundError, PermissionError, ProcessLookupError, ValueError):
pass
if time.monotonic() - started > 900:
os.killpg(process.pid, signal.SIGTERM)
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
timed_out = True
passed = False
break
time.sleep(0.1)
code = process.wait()
elapsed = time.monotonic() - started
hashes = PATTERN.findall(logfile.read_text(encoding="utf-8", errors="replace"))
ok = code == 0 and not timed_out and len(hashes) == 12
if reference is None:
reference = hashes
elif hashes != reference:
ok = False
print(f"[CrossingMismatch] {name}", flush=True)
passed &= ok
print(f"[CrossingRun] {name} exit={code} seconds={elapsed:.3f} "
f"peak_rss_kib={peak_rss} hash_rows={len(hashes)} "
f"status={'PASS' if ok else 'FAIL'}", flush=True)
print(f"[CrossingSummary] rows={len(BINARIES)*len(RUNS)} expected=14 "
f"result={'PASS' if passed else 'FAIL'} path={OUT}", flush=True)
raise SystemExit(0 if passed else 1)
@@ -1,88 +0,0 @@
#!/usr/bin/env python3
"""Run the L19 W1/W8/W12 x5 matrix under inherited taskset limits."""
import os
import re
import signal
import subprocess
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[4]
OUT = ROOT / "Saved/Linux/l19-matrix"
OUT.mkdir(parents=True, exist_ok=True)
if not os.sched_getaffinity(0).issubset(set(range(12))):
raise SystemExit("run under taskset -c 0-11")
BINARIES = {
"clang-off": ROOT / "Standalone/bin/linux/VoxelForgeCoreHeadless-linux19-clang",
"gcc-default": ROOT / "Standalone/bin/linux/VoxelForgeCoreHeadless-linux19-gcc",
}
RECIPES = {
"floating-islands": "-22,-19,-22.8,0,-4",
"surface-world": "0,-35,-487.94,0,-22",
}
PATTERN = re.compile(r"^\[Pipeline(?:FullDetailHash|WholeViewHash|LODHash|ExactQueryHash)\].*$", re.M)
RUNS = [(1, 1), (8, 1), (12, 1), (12, 2), (12, 3), (12, 4), (12, 5)]
passed = True
for recipe, camera in RECIPES.items():
for compiler, binary in BINARIES.items():
if not binary.exists():
raise SystemExit(f"missing binary: {binary}")
reference = None
for workers, repeat in RUNS:
name = f"{recipe}-{compiler}-w{workers}-r{repeat}"
logfile = OUT / f"{name}.log"
command = ["prlimit", "--as=6442450944", "--", str(binary),
str(ROOT / "Standalone/data/owner_world.json"),
"--world-assembler-prototype", "--stream-benchmark", "--stream-pipeline",
"--stream-hash", "--force-generate", "--clip-radius=3",
"--max-clip-level=8", f"--workers={workers}", f"--camera={camera}",
f"--recipe={recipe}"]
started = time.monotonic()
peak_rss = 0
timed_out = False
with logfile.open("w", encoding="utf-8") as stream:
process = subprocess.Popen(command, stdout=stream, stderr=subprocess.STDOUT,
start_new_session=True)
while process.poll() is None:
pending, seen = [process.pid], set()
while pending:
pid = pending.pop()
if pid in seen:
continue
seen.add(pid)
try:
pending.extend(int(value) for value in
Path(f"/proc/{pid}/task/{pid}/children").read_text().split())
for line in Path(f"/proc/{pid}/status").read_text().splitlines():
if line.startswith("VmRSS:"):
peak_rss = max(peak_rss, int(line.split()[1]))
break
except (FileNotFoundError, PermissionError, ProcessLookupError, ValueError):
pass
if time.monotonic() - started > 900:
os.killpg(process.pid, signal.SIGTERM)
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
timed_out = True
passed = False
break
time.sleep(0.1)
code = process.wait()
elapsed = time.monotonic() - started
hashes = PATTERN.findall(logfile.read_text(encoding="utf-8", errors="replace"))
ok = code == 0 and not timed_out and len(hashes) == 12
if reference is None:
reference = hashes
elif hashes != reference:
ok = False
print(f"[MatrixMismatch] {name}", flush=True)
passed &= ok
print(f"[MatrixRun] {name} exit={code} seconds={elapsed:.3f} "
f"peak_rss_kib={peak_rss} hash_rows={len(hashes)} "
f"status={'PASS' if ok else 'FAIL'}", flush=True)
print(f"[MatrixSummary] rows={len(RECIPES)*len(BINARIES)*len(RUNS)} expected=28 "
f"result={'PASS' if passed else 'FAIL'} path={OUT}", flush=True)
raise SystemExit(0 if passed else 1)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

@@ -1,81 +0,0 @@
# Linux20 — design research for metre-based strata and generation layers
**Date:** 2026-10-20
**Scope:** read current owner/Core code and L19 evidence; measure unit conversions and LOD ring
errors; write the L20 design only.
## Findings
- `CHUNK_SIZE` is 32 and legacy `VOXEL_SIZE` is 12.5 cm, so the owner chunk is 4 m
(`Source/VoxelForge/Public/VoxelTypes.h`). Core defaults to 25 cm and keeps 32 voxels per tile.
- `BuildSurfaceStratumPlan` computes SurfaceWorld layout from `Slot.*ChunkZ × CHUNK_SIZE` in Core
voxel units. This is 32 × 25 cm = **8 m per slot chunk**. L18 records this as the retained
SurfaceWorld `topChunkZ × 32` interpretation.
- `BuildFloatingIslandStratumPlan` serializes owner/Core voxel size and the reduced ratio. At the
default 12.5/25 cm ratio, its slot chunk is 32 × 0.5 = 16 Core voxels = **4 m**. Core reverses
sample Z using `GetCoreVoxelsPerOwnerChunk` in `ShapeWorldInternal.h`.
- This factor-of-two difference is real, but it is not enough to claim that it caused the L19 ring
heights. L19's ring evidence points to LOD-dependent extraction of the lower SurfaceWorld field.
It does mean there is no single metres-per-chunk conversion that both preserves the current native
bounds and makes their shared slot indices one physical interface. The design records the current
resolved bounds and treats a later interface unification as an explicit change.
- The L19 FloatingIslands-camera table reports LOD1→2 median / p95 / max = 147.141 / 148.403 /
149.862 cm, zero no-hit samples; LOD2→3 = 128.603 / 200.789 / 773.318 cm, with 8 no-hit samples
among 308. LOD1/2/3 step sizes at 25 cm are 0.5/1/2 m. The ring audit excludes skirts and masked
triangles. Native far-ground refinement starts at LOD4, so it cannot fix those two transitions.
- The exact location and current geometry evidence are from `Linux19/REPORT.md`: lower SurfaceWorld
terrain at approximately −60…−73 m; its terrain triangles remain visible below FloatingIslands.
The worst sampled LOD1→2 roots are −60.497 m and −61.996 m. The LOD2→3 pair is −73.080 m and
−65.347 m.
## Layer map
The owner-facing layout is composed by `VoxelStrateComposer.cpp`, stored/loaded by
`VoxelSeasonManifest.cpp`, and resolved into `FStrateSlot`s by `VoxelStrateManager.cpp`. The Core
snapshot adapter (`VoxelForgeCoreAdapter.cpp`) builds separate SurfaceWorld and FloatingIslands
plans. Core streams work from `VoxelForgeCore.cpp` and evaluates native fields in
`WorldAssemblerInternal.h` / `FloatingIslandsInternal.h`; legacy `UVoxelGenerator::GetDensityAt`
and operator-stack/cave paths remain in `VoxelGenerator.cpp`, `VoxelDensityOpStack.cpp`, and
`VoxelCaveMorphology.cpp`.
Shared pieces already include Core's FP-contract preamble, fixed-point field code, feature bounds,
column caches, and interval proofs. `ShapeWorldInternal.h` still chooses among native fields, manager
state, and the copied legacy evaluator. `World::generateTile` in `VoxelForgeCore.cpp` owns MC setup,
recipe feature branches, native SurfaceWorld far-ground/cap refinement, and recipe identity salts.
`FarShellsInternal.h` adds shared boundary ceilings and GPU far-shell repairs; its connector repair
input is prepared from FloatingIslands geometry in `ShapeWorldInternal.h`.
The complete mapping, boundary proposal, ranked violations, generator contract, and migration plan
are in [`DESIGN_STRATA_UNITS_AND_LAYERS.md`](../../../DESIGN_STRATA_UNITS_AND_LAYERS.md).
## Direction review
The proposed metre authoring, 25 cm per-strate default, fixed 32³ internal tiles, and separation of
director/generators/shared composition/mesher are sound. Two qualifications are recorded in the
design:
1. “Units cost nothing” is true for metre conversion itself. Voxel size affects the physical width
of 32³ tiles and the number of tiles/tasks/caches; halving spacing in XYZ implies about 8× the
density samples per physical volume, with more per-tile overhead on top.
2. A no-movement migration cannot use one global chunk-to-metre multiplier. Current Core paths use
8 m per SurfaceWorld slot chunk and 4 m per FloatingIslands slot chunk at defaults. Preserve and
report those current resolved bounds first; decide separately whether to leave any gap/overlap or
intentionally make the new metre-authored interface contiguous.
The L19 density/mesh evidence supports LOD extraction as the direct cause of the measured lower-ground
ring steps. A shared explicit ceiling surface is the right approach for seals/caps, but not sufficient
for those upward-facing ground ledges. Step 5 therefore exposes the SurfaceWorld ground profile to a
generic explicit-surface/transition contract and remains subject to the protected LOD2 approval.
## Output and worktree status
No source, manifest, generator, mesher, or build input was changed. No build or world run was made.
Thus no new W12 hash claim is needed for this documentation-only round. The L19 reference hashes
remain the expected equality gates for later source changes:
- SurfaceWorld whole view: `c10697a8f48380c7 / 4197fc1072f0ff58 / 7b3e616ec9459851 / c879e35592bf33e5`
- FloatingIslands whole view: `00bc3607a7839854 / 4baa66127c2b0892 / e11ef05e851a1517 / 1278bc4b1fffb869`
The pre-existing untracked `Standalone/Research/WorldAssemblerM3/Linux18/exports/` directory was
left untouched. No commit, push, or stash was made.
@@ -1,233 +0,0 @@
# Sol 6.1 (medium) read-only review of the L20 design — 2026-10-20
Requested by the owner. Prompt: `Saved/Linux/claude/sol-l20-review.md` (copied below the answer). Session `01a1582c-547a-7701-9d9e-35239b7f0a26`, 68,458 tokens, sandbox read-only.
**The direction is right. Preserve today’s world during conversion, but treat inconsistent bounds as compatibility data, not valid new layout. Allow the SurfaceWorld LOD2 boundary fix, with a precisely defined affected region and unchanged density.**
L20 needs a stronger bedrock model and an earlier ownership contract. Adding floor bedrock everywhere is also a deliberate geometry change: current FloatingIslands v3 explicitly omits its lower seal.
I only read files; I did not build, run, or modify anything.
**1. The two decisions**
**Decision 1: preserve first, repair separately.** L17 demonstrates why: unifying the chunk scale removed the approved SurfaceWorld ground and moved the world ([Linux17/REPORT.md:168](/home/jahni/VoxelM/Plugins/VoxelForge/Standalone/Research/WorldAssemblerM3/Linux17/REPORT.md:168)).
The mismatch is real. SurfaceWorld uses slot chunks directly as 32 Core voxels; FloatingIslands applies the owner/Core ratio ([VoxelForgeCoreAdapter.cpp:290](/home/jahni/VoxelM/Plugins/VoxelForge/Source/VoxelForge/Private/VoxelForgeCoreAdapter.cpp:290), [VoxelForgeCoreAdapter.cpp:464](/home/jahni/VoxelM/Plugins/VoxelForge/Source/VoxelForge/Private/VoxelForgeCoreAdapter.cpp:464)).
However, preserve **effective behavior**, not just converted endpoints. Dispatch itself uses different conversions: SurfaceWorld divides Z by 32, while FloatingIslands uses the owner/Core scale ([ShapeWorldInternal.h:2130](/home/jahni/VoxelM/Plugins/VoxelForge/Standalone/Core/src/ShapeWorldInternal.h:2130), [ShapeWorldInternal.h:2158](/home/jahni/VoxelM/Plugins/VoxelForge/Standalone/Core/src/ShapeWorldInternal.h:2158)). An apparent interval between bounds therefore does not prove that interval currently generates air.
Keep historical overlaps and ambiguities in a versioned compatibility snapshot. **Reject overlaps in newly authored layouts.** Otherwise preservation becomes permanent acceptance of the bug.
**Decision 2: approve the change in principle.** L19 measured actual lower-ground extraction differences, not ceiling triangles: up to 1.50 m and 7.73 m ([Linux19/REPORT.md:9](/home/jahni/VoxelM/Plugins/VoxelForge/Standalone/Research/WorldAssemblerM3/Linux19/REPORT.md:9)). An explicit ceiling cannot fix these.
Define the affected tiles from the observed surface and transition support, including halos—not merely distance from a nominal strate plane. Preserve exact queries and unaffected near-player geometry. Validate against the same physical surface so the audit cannot “improve” by pairing different surfaces or hiding terrain.
Metre authoring and default 25 cm voxels are sound. Fixed 32³ tiles mean physical tile width still follows voxel size; if Jahni wants fixed physical streaming regions, introduce those separately from internal tiles.
**2. A concrete strate structure**
Use one immutable, versioned director output. Distinguish a strate’s **generator interior** from the bedrock separating interiors. This makes thickness and ownership unambiguous.
```text
ResolvedWorld
schemaVersion, evaluatorVersion, seed, worldIdentity
physicalUnit = fixed integer unit independent of voxel size
strates[] // ordered downward
verticalSegments[] // exact partition of declared world extent
interfaces[]
passages[]
Strate
stableId // persisted; independent of array position
order
bottomM, topM // generator interior: [bottomM, topM)
voxelSizeM = 0.25
latticeOriginM
generatorKind
recipeId, recipeVersion, resolvedRecipe, seedKey
floorBandId, ceilingBandId
interfaceAboveId, interfaceBelowId
VerticalSegment
stableId, bottomM, topM
kind = StrateInterior | Bedrock | VoidGap
ownerId
BedrockBand
stableId, bottomM, topM
thicknessM = topM - bottomM
volumeMaterialId
upperFaceMaterialId, lowerFaceMaterialId
digPolicy = Diggable | Protected | Restricted
allowedPassageIds[]
surfaceDescriptorIds[]
Interface
stableId, upperStrateId, lowerStrateId
orderedSegmentIds[] // bedrock, optional void, further bedrock
passagePlacementRecipe
resolvedPassageIds[]
Passage
stableId, interfaceId
physical tunnel shape, aperture boundaries
upper/lower endpoints, landing/support geometry
crossedBandIds[], clearance, carvePermission
```
Author in metres; serialize canonical fixed physical units with explicit rounding. The resolved fields above are produced once, not independently editable copies.
For a shared slab, the upper strate’s floor and lower strate’s ceiling reference **the same band**. Its thickness and digging policy cannot disagree between sides. Separate skins with a void between them require three explicit segments.
I recommend ordinary inter-strate bedrock remain diggable, preserving the established player-dug descent behavior ([ARCHITECTURE.md:472](/home/jahni/VoxelM/Plugins/VoxelForge/ARCHITECTURE.md:472)). Protection should be an explicit band policy.
The invariants are:
- Unique stable IDs; explicit order; finite bounds; positive interior height and bedrock thickness.
- Every physical height within the declared stack belongs to exactly one segment. No overlaps or implicit gaps.
- Every strate has floor and ceiling bedrock, including terminal strates.
- Interiors remain closed except through registered passages or authorized player-created apertures.
- A void gap lies between closed skins. A freely open connection requires an explicit aperture, potentially covering the whole interface.
- Passages cross every intervening band and provide usable entrances, exits, and support.
- All generators, proofs, streaming, meshing, collision, and material queries consume this snapshot. None reconstruct boundaries from chunk indices.
Keep legacy recipe seed keys frozen during migration. Switching randomness from strate index to stable ID must be versioned separately to avoid changing the world.
**3. Bedrock should be both volume and explicit geometry**
Use an authoritative solid volume for density, digging, collision queries, and conservative proofs, plus explicit boundary surfaces for reliable extraction. Both representations derive from the same band and aperture descriptors.
Density alone cannot guarantee a thin band survives coarse sampling. Conversely, a visual plane alone supplies no solid interior and can disagree with collision or digging.
Current code illustrates the mismatch: the upper seal fills inward over its thickness, while fallback ceiling vertices are placed at `Bounds.TopZ` ([VoxelDensityPrimitives.h:44](/home/jahni/VoxelM/Plugins/VoxelForge/Source/VoxelForge/Public/VoxelDensityPrimitives.h:44), [FarShellsInternal.h:1238](/home/jahni/VoxelM/Plugins/VoxelForge/Standalone/Core/src/FarShellsInternal.h:1238)). The new contract must distinguish the band’s outer boundary from its room-facing surface.
For a ceiling above an interior, its lower face is at `topM`; for a floor below an interior, its upper face is at `bottomM`. Thickness extends away from the interior.
The mesher should own each exposed face once, suppress overlapping ordinary extraction, and use shared edge anchors across LODs. Passage mouths need explicit clipping and wall geometry; corner sampling alone can miss a small aperture.
Authorized edits must modify both density and surface extraction. Protected bands require explicit edit masking. Generated passages carve after bedrock composition, consistent with today’s passage ordering ([VoxelDensityPrimitives.h:86](/home/jahni/VoxelM/Plugins/VoxelForge/Source/VoxelForge/Public/VoxelDensityPrimitives.h:86)).
Collision uses the same geometry semantics at a gameplay resolution independent of camera LOD. Peers reproduce bands and generated passages from the versioned plan; only player edits need synchronization.
Cost stays local: cheap band queries and flat faces generally, extra refinement around openings and edited areas.
**4. What I would change in L20**
My top three risks are:
1. **Migrating bounds without migrating dispatch.** Today’s “resolved” bounds still consult the manager and branch by generator ([ShapeWorldInternal.h:67](/home/jahni/VoxelM/Plugins/VoxelForge/Standalone/Core/src/ShapeWorldInternal.h:67)). Snapshot ownership, fallback behavior, and recipe anchors together.
2. **Changing gameplay under structural cleanup.** FloatingIslands v3 applies only an upper seal ([ShapeWorldInternal.h:2192](/home/jahni/VoxelM/Plugins/VoxelForge/Standalone/Core/src/ShapeWorldInternal.h:2192)). Restoring a floor changes visibility and descent. Require a new layout version; do not silently reintroduce the removed floor.
3. **Maintaining conflicting density, mesh, and collision boundaries.** Explicit surfaces must be authoritative constraints derived from bands, rather than another repair overlay.
Reorder the migration to: compatibility snapshot → canonical ownership and bedrock schema → minimal shared boundary composition → targeted LOD transition prototype → metre authoring and generator adapters. Keep the broad generator/helper refactor incremental. Mixed resolutions remain last.
**5. Smallest first implementation**
Implement a **versioned resolved-layout snapshot and validator**, populated by the existing director/adapter. Record actual physical bounds, recipe/cap anchors, voxel sizes, current floor/ceiling behavior, and dispatch provenance. Flag incompatible intervals explicitly. Leave evaluation unchanged.
Its acceptance test should require:
- Exact preservation of existing resolved anchors and recipe values, including routes and cap profiles.
- Boundary probes immediately below, at, and above every endpoint, comparing actual old dispatch with the snapshot’s recorded behavior.
- Deterministic identity across worker counts and serialization round trips.
- Rejection of overlapping or uncovered new layouts.
- Existing SurfaceWorld density and geometry hashes unchanged; L19 ceiling coverage unchanged.
This delivers inspectable strate structure first. Enforcing new floors and repairing ledges then become separate, measurable world changes.
---
## Prompt
# VoxelForge — design review (Sol, read-only): strate structure, bedrock and the L20 decisions
You are reviewing a design for VoxelForge, a voxel terrain plugin for a multiplayer Unreal Engine
game, with its generation done in a C++ Core library. The game is underground: the world is a
vertical stack of **strates** (layers). Each strate has its own generator type:
- SurfaceWorld: an enclosed surface-like heightfield world;
- FloatingIslands;
- caves, and future types.
Players travel between strates through passages. Every machine generates the same terrain from a
seed. Only player edits cross the network.
**This is a read-only review.** Read files, but don't build, run, edit or create anything. The
owner pays for this review, so be efficient: read what you need, and keep the answer focused and
concrete.
## Read first
- `/home/jahni/VoxelM/Plugins/VoxelForge/Standalone/DESIGN_STRATA_UNITS_AND_LAYERS.md`: the design
under review (round L20).
- `/home/jahni/VoxelM/Plugins/VoxelForge/Standalone/Research/WorldAssemblerM3/Linux20/REPORT.md`
- For the bugs that motivated it: `.../Linux17/REPORT.md`, `.../Linux18/REPORT.md` and
`.../Linux19/REPORT.md`, in the same folder. Each has an "Orchestrator review" section at the end.
- Code, as needed:
- `Source/VoxelForge/Private/VoxelForgeCoreAdapter.cpp` (plan building: SurfaceWorld vs
FloatingIslands chunk conversion);
- `Source/VoxelForge/Private/VoxelStrateManager.cpp` and `Source/VoxelForge/Public/VoxelStrateTypes.h`
(strate slots and params);
- `Standalone/Core/src/ShapeWorldInternal.h` (`FResolvedStratumBounds`, `GetResolvedStratumBounds`);
- `Standalone/Core/src/FarShellsInternal.h` (`AppendStratumBoundaryCeilings`);
- `Source/VoxelForge/Public/VoxelDensityPrimitives.h` (boundary seals);
- `CLAUDE.md`, and `ARCHITECTURE.md` (§8) for the hard rules.
## The owner's direction
The owner is Jahni. Quotes:
- "Everything should use a parameter like on the strate, saying which voxel size it is, by default
25 for everyone, same for island."
- "Our system should be in different categories: the director/orchestrator, the generators (all
using the same kind of format, helper functions … from a shared library like noise functions) and
the mesher; the generators are dictated by our current strate parameters."
- "The voxel size shouldn't dictate the size of a chunk … wouldn't it be better to have like Unreal
unit distance, and have x voxels fill it?"
- "Any strate should have a ceiling, since we're underground."
- "The ceiling height is decided by the strate parameter, it's not something unique to sky island."
- Now: **"we need proper strate structure, knowing where each starts etc."**, including the strate
**bedrocks (ceiling and floor)**.
## What I (the orchestrator) recommended, which he wants judged
1. **Layout is authored in metres;** each strate has a voxel size (default 25 cm); internal tiles
stay 32³ voxels. Units cost nothing at run time, while the voxel count does.
2. **Decision 1 (preservation):** when converting today's chunk-based strate parameters to metres,
keep every strate exactly where it currently is in the generated world, including any gap or
overlap that the current 8 m (SurfaceWorld) vs 4 m (FloatingIslands) per-chunk mismatch creates.
Report those gaps and overlaps, then tune in metres. The alternative is to force them to meet
during the migration.
3. **Decision 2:** allow step 5 of the migration (an explicit, LOD-stable interface surface) to
change SurfaceWorld LOD2 output near strate boundaries, to fix the owner's "ledges" (cross-LOD
ring steps of up to 1.5 m and 7.7 m at the FloatingIslands/SurfaceWorld interface). Near-player
terrain away from boundaries must stay identical.
## Questions (answer each)
1. **Are the two decisions and the direction right?** Say where you'd decide differently, and why.
Is preserving today's possibly-inconsistent bounds the right first step, or does it entrench a
bug? Is there a better migration order?
2. **Propose a proper strate structure.** A concrete data model the director owns. For each strate:
- its stable ID and order;
- top and bottom in metres;
- **floor bedrock and ceiling bedrock:** thickness in metres, material, whether players can dig
through, and how passages pierce them;
- its voxel size;
- its generator and recipe;
- its interfaces to the strate above and below: solid bedrock band, open void, passage
placement.
Define the invariants: no overlaps; every metre owned by exactly one strate or one explicit
bedrock/gap band; ceiling and floor always closed, except at passages; contiguous or explicit
gaps. Show how "where each strate starts and ends" becomes a single source of truth that every
generator and the mesher read, never re-derive.
3. **Bedrock as geometry.** Should a ceiling or floor be a density band (a seal), an explicit
surface the mesher knows about, or both? Weigh LOD stability (the ledge problem: thin seals
extract at different heights per LOD), collision, player digging, multiplayer determinism, and
cost. Give a recommendation.
4. **What in the L20 design would you change, cut, or reorder?** Name the top 3 risks.
5. **The smallest first implementation step** that delivers the strate structure without moving the
approved SurfaceWorld world, and its acceptance test.
## Answer format
Plain English. The owner reads it, so lead with your verdicts in a few lines, then the details.
Around 1,500 words at most, plus the data-model sketch. Cite file:line where you rely on code.
@@ -1,203 +0,0 @@
# World Assembler L21 — resolved strate layout
This round adds a read-only layout snapshot and validator. It does not change density or mesh
evaluation.
## Snapshot and current stack
World identity is `owner-world/seed/0`; Core voxel size is 0.25 m, owner voxel size is 0.125 m, and
all lattice origins are `(0,0,0)`. Intervals below are half-open `[bottom, top)` metres. Stable strate
IDs are `owner-world/seed/0/strate/<index>/generator/<kind>`. The shared Core record uses canonical
JSON schema v1 and an FNV-1a payload identity.
The required structure, top to bottom, is:
```text
strate N ceiling band
content
bedrock band
strate N+1 ceiling band
content
bedrock band
```
Ceiling and bedrock remain distinct bands owned by their own strate. Their nominal edges touch; a
separate `EVoxelStrateTransition` declaration describes possible interpenetration.
| Prototype | Order / stable suffix | Generator; recipe version | Interior/content (m) | Current ceiling | Current bedrock | Transition at lower interface |
|---|---|---|---|---|---|---|
| SurfaceWorld | 0 / `TunnelNetwork` | TunnelNetwork; `legacy.TunnelNetwork` v0 | `[-120, 8)` | No Core density band. Manager configures a 1 m upper `VF_ApplyBoundarySeal` at `[8,9)`, but the compiled analytic Core path does not apply it. | No Core density band. Manager configures a 1 m lower `VF_ApplyBoundarySeal` at `[-121,-120)`, but the compiled analytic Core path does not apply it. | Gradient, 2 chunks = 8 m by the 4 m manager chunk. Core does not apply it; manager/dispatch chunk widths are 4/8 m. |
| SurfaceWorld | 1 / `SurfaceWorld` | SurfaceWorld; `SurfaceWorld.Heightfield2D` v1 | `[-632,-120)` | No separate volumetric band; cap profile is in content, with `AppendStratumBoundaryCeilings` mesh fallback. | None. | Gradient, 1 chunk = 4 m by manager units; no lower strate in this plan. Manager/dispatch widths are 4/8 m. |
| FloatingIslands | 0 / `FloatingIslands` | FloatingIslands; `FloatingIslands.ClusterField` geometry v3 | `[-60,4)` | Active one-sided upper seal `[3.5,4)` = 0.5 m. It overlaps the content range by 0.5 m. | None in geometry v3. | Gradient, 2 chunks = 8 m. Core does not apply it; manager/dispatch widths are both 4 m. |
| FloatingIslands | 1 / `SurfaceWorld` | SurfaceWorld; `SurfaceWorld.Heightfield2D` v1 | `[-632,-120)` | No separate volumetric band; cap profile is in content, with mesh fallback. | None. | Gradient, 1 chunk = 4 m; no lower strate in this plan. Manager/dispatch widths are 4/8 m. |
Dispatch provenance is recorded per stratum in the JSON snapshot:
- SurfaceWorld bounds come from `BuildSurfaceStratumPlan`, which converts each chunk with 32 Core
voxels = 8 m. `NativeSurfaceDensityAt` selects with `floor(CoreZ/32)`, then calls
`GetGeneratorTypeForChunk` / `GetStrateIndex`. The manager's owner chunk is 4 m.
- FI bounds come from `BuildFloatingIslandStratumPlan`, which converts each 32-voxel owner chunk
through the 12.5/25 cm owner/Core ratio = 16 Core voxels = 4 m. `NativeFloatingIslandDensityAt`
uses the same conversion before the manager lookup.
- Legacy TunnelNetwork selection uses the Core 32-voxel chunk lookup. The manager helper assigns
the upper strate's transition to its lower interface.
SurfaceWorld strata carry four cap profiles, 33 route points and their attached passages. The FI
strate carries four island anchors and its attached passages. The snapshot preserves these recipe
anchors in their source fixed-point units.
The owner configuration’s non-Hard transitions are currently not honored by Core at these interfaces.
`UVoxelStrateManager::GetGenerationParams` contains legacy vector blending, but Core’s compiled
dispatcher selects the resolved/native per-strate fields without applying that blend. FI v3 calls
`VF_ApplyUpperBoundarySeal` for its ceiling; player edit brushes are applied after the native field,
so that seal remains diggable. Bands default to `diggable=true`, `protected=false`; protection is an
explicit option.
```text
Current SurfaceWorld plan, top → bottom
TunnelNetwork ceiling [8,9) (configured; inactive in Core density)
TunnelNetwork content [-120,8)
TunnelNetwork bedrock [-121,-120) (configured; inactive in Core)
SurfaceWorld ceiling: none
SurfaceWorld content [-632,-120)
SurfaceWorld bedrock: none
Current FI prototype, top → bottom
FI ceiling [3.5,4) active, inset into FI content by 0.5 m
FI content [-60,4)
FI bedrock: missing
Unassigned interval [-120,-60) = 60 m
SurfaceWorld ceiling: none
SurfaceWorld content [-632,-120)
SurfaceWorld bedrock: none
```
The SurfaceWorld and FI content interiors therefore do not overlap: the FI prototype has a 60 m gap.
The owner manager slots meet at −60 m when both use 4 m owner chunks, but SurfaceWorld plan/query
dispatch converts chunks at 8 m while FI converts at 4 m. In the gap, Core answers through the
compiled analytic FloatingIslands fallback, not either planned recipe; probes at −68 m returned
solid density −4.125. SurfaceWorld and TunnelNetwork content interiors touch at −120 m in the
SurfaceWorld prototype, but Core does not apply the declared Gradient there.
## Compatibility validation and boundary probes
Compatibility mode accepted both layouts with seven reported issues apiece. SurfaceWorld reports
unhonored transition, 4/8 m dispatch-unit ambiguity on both strates, and missing current-field
ceiling and bedrock bands on both. FI reports its unhonored transition, missing FI bedrock, the
0.5 m ceiling/content overlap, the 60 m uncovered interval, and missing SurfaceWorld ceiling and
bedrock. These are recorded as compatibility deviations, not world changes.
Strict mode accepted a valid synthetic two-strate fixture. Its seven negative controls rejected:
| Control | Strict check that rejects it |
|---|---|
| Nominal band overlap | Bedrock(N) bottom must equal ceiling(N+1) top. |
| Nominal band gap | The same exact nominal contiguity check. |
| Missing bedrock | `bedrock.present` is required. |
| Missing ceiling | `ceiling.present` is required. |
| Wrong band order | Each band kind and the ceiling → content → bedrock edges must match. |
| Gap between bedrock(N) and ceiling(N+1) | Their nominal endpoints must be equal. |
| Interpenetration wider than transition | Explicit overlap must be at most the mode’s limit; this control uses 4,000,001 µm against a 4,000,000 µm Gradient zone. |
Hard has a 0 m limit. Gradient uses `TransitionBlendChunks × 4 m`; Interleaved adds its recorded
two-manager-chunk warp amplitude to the blend width. The nominal bands still touch exactly; the
separate interpenetration field records any permitted physical crossing. Current Core
interpenetration is 0 m because it does not apply the declared blends.
Each plan audited 21 points: one Core voxel (0.25 m) below, at, and above every distinct content,
active-band, configured-band, and transition-zone endpoint. The remaining points agreed with the
snapshot. Every disagreement was an uncovered snapshot point answered by a named compiled analytic
fallback:
| Prototype | Probe Z (m) | Actual Core dispatch | Density / occupancy |
|---|---|---|---|
| SurfaceWorld | −632.250 | `compiled-analytic/TunnelNetwork` | `+1`, air |
| SurfaceWorld | 8.000, 8.250, 8.750, 9.000, 9.250 | `compiled-analytic/TunnelNetwork` | `+9.648438`, `+10.64844`, `+12.64844`, `+13.64844`, `+14.64844`; all air |
| FI | −632.250 | `compiled-analytic/TunnelNetwork` | `+1`, air |
| FI | −120.000, −119.750 | `compiled-analytic/FloatingIslands` | `−108.4793`, `−107.4969`; solid |
| FI | −68.250, −68.000, −67.750, −60.250 | `compiled-analytic/FloatingIslands` | `−4.125`; solid at each point |
| FI | 4.000, 4.250 | `compiled-analytic/FloatingIslands` | `+0.671875`, `+2.253906`; air |
Probe summaries: SurfaceWorld 6/21 disagreements; FI 9/21. Full per-point records are in
`Saved/Linux/linux21/boundary-probes-{surface-world,floating-islands}.log`.
## Identity, output parity and cost
Snapshots round-tripped through canonical JSON. At W1/W8/W12 their bytes were identical per recipe:
| Recipe | Stable identity | Canonical JSON SHA-256 |
|---|---|---|
| SurfaceWorld | `resolved-layout-v1-fnv64:63cf4d2661149fcd` | `267586b3da9bc5c08c654c097559b205222f53c594c4c4332cb4929fd3d75c05` |
| FloatingIslands | `resolved-layout-v1-fnv64:1d90167f37ef9323` | `7bb9e9d745de3a2edf4276f507a5e4c082ff86aa73d9c1ad7e77c1b4d8b8bea8` |
The 28 hash runs (both recipes, Clang `fp-contract=off` and GCC default, W1/W8/W12 and W12×5)
matched all 12 L19 rows per run. The 14 dedicated 24 m crossing runs also matched all 12 L19
crossing rows. The table gives the final Clang W12×5 rows, in density/mesh/payload/topology order;
each equals its L19 reference.
| Scope | SurfaceWorld | FloatingIslands |
|---|---|---|
| Full detail | `0ee0579bd15cbbe4 / 32e5d4964d610fee / 1932b96ee4b1d910 / 69743c6bad3447dc` | `43034299d33f2536 / a41e8353ec4bbe9c / cd0e3e15eef827b0 / 0b3c3f13cc1d6f8a` |
| Whole view | `c10697a8f48380c7 / 4197fc1072f0ff58 / 7b3e616ec9459851 / c879e35592bf33e5` | `00bc3607a7839854 / 4baa66127c2b0892 / e11ef05e851a1517 / 1278bc4b1fffb869` |
| LOD 0 | `769f2a706d585a72 / 33eeeb39fa443816 / 645621a1d968983f / c2457ed905036c9d` | `ccf97d8e95163a35 / 3333fa0ddebdece2 / d1906bffc2b9d6f2 / a261f3d965e15c12` |
| LOD 1 | `69cc5a5c0a2c60af / b48335f5410c57d5 / d15c5480162ab8ba / feca1bd025823604` | `25fa2f0fa7fbb6e6 / c549c519707ac1d7 / 66f797cde4ebdecf / 2383982a12a27ee5` |
| LOD 2 | `85deed5683a77202 / 53469895987aeea2 / e55f8ae7e1532033 / d5feb12a0e85c09b` | `c0577decd8a02cab / 3ccf08b7be6edc5b / 0abcbbda5a06c110 / 11c77b71b606fe75` |
| LOD 3 | `6518caefb3be7e7f / ec513c90b853a614 / f62fa1137ff17f82 / ccf1dcf681965816` | `386e0c0ef2d7c920 / 1ee2c82d34ad9918 / 000a6514ba018406 / 1b4523b19e90f305` |
| LOD 4 | `62d4be96021992f4 / 42706847cb9c744a / eab76f9634e4b9bd / 207ffbb6ef184397` | `e8117a3a803be9f8 / 8a6c36cae1fe0e30 / c839f1b1629eff8c / 0ce9d7ea77b4f62b` |
| LOD 5 | `5e4a8c38b8cea6fc / 76adc9ae86988e27 / 938975bf7cc6d94d / 42e135856abdbcac` | `ca6d1df453c6b600 / 02c90d834d9a3fb6 / 4364c37d526f4104 / 1b1cf40d25e50ddf` |
| LOD 6 | `e036e95b9006945b / a880cc101a4ed957 / bd82f1aefad6dd89 / 5e9f3408345d95b3` | `6764e347b08603a0 / 46c6ed9a1f029b94 / 5b8dc9d5b7cb0d3d / a10a4a69a93eac4d` |
| LOD 7 | `8ee358af56a30d8d / 5cbd8e5965a2cc3f / d4a7fe5d9e4bde30 / 4dd52cd090a9af78` | `c7cd1b483c598595 / a545eb567dc4a0df / b0a1fb225437e05a / 301d1b884c509550` |
| LOD 8 | `c3458e1cbdb9c471 / fba3698d21dd1be0 / 77dfb814eac3a24c / c9514f1580c42449` | `7b6e9279b4993109 / cc63440d9867a18d / 12f5cec78b38fa1b / eed919db6db6b2a7` |
Exact-query rows (density/unclamped, detail, collision): SurfaceWorld `e4d4a8eb95b35933 / e4d4a8eb95b35933`,
`efcba20c0c70c415`, `e604823a249029bf`; FloatingIslands `87e5c0dbf9ee9ee2 / 87e5c0dbf9ee9ee2`,
`efcba20c0c70c415`, `e604823a249029bf`. The representative 24 m crossing W12×5 whole-view row is the
SurfaceWorld row above; all crossing full-detail, LOD and exact-query rows matched the L19 crossing
reference.
Five interleaved hashing-off W12 pairs against L19 measured SurfaceWorld medians 1.510 s old / 1.512 s
new (+0.14%) and FI 13.487 s old / 13.381 s new (−0.79%). The opt-in snapshot is constructed once
at plan time, outside tile workers; ordinary standalone evaluation does not request it. No hash rows
were produced during these pairs.
Clang and GCC builds passed at 12 jobs. Final build peak process-tree/single-process RSS was
2,697,676/450,248 KiB (Clang) and 4,570,704/897,024 KiB (GCC). The final evidence runner's maximum
single-process RSS was 583,736 KiB. All runs used CPUs 0–11 and stayed below the per-run limit; no
governor or system changes were made.
## Failed and retried runs
- An initial snapshot invocation omitted `--stream-benchmark --stream-pipeline` and exited 2; adding
the required flags passed.
- Early Clang builds caught a `strates` member typo, then an audit initializer/type error. Both were
fixed; the final Clang builds passed.
- The first complete evidence pass exited 1 at boundary probing because the audit read the host
manager after the harness had released it. Dispatch provenance was moved to Core's live selector;
the final audits passed.
- One GCC build wrapper was interrupted (exit 130) while diagnosing an empty progress log, then
rerun successfully. No runtime/hash run timed out or exceeded 15 minutes, and no L19 hash mismatch
remained.
## Owner note
This records the present strata and confirms the selected ceiling → content → bedrock model. FI still
has no floor in v3; SurfaceWorld has no volumetric floor or separate ceiling; the 8 m / 4 m dispatch
conversions leave a 60 m FI-prototype gap answered by analytic fallback. Core currently ignores the
configured transition blend at these interfaces. Bedrock and ceiling protection remain explicit
options with diggable defaults. This round changes no world output.
The Unreal adapter adds only a separate `resolved_layout` JSON field beside `world_assembly`; that
small edit could not be compiled on this Linux machine. No async path, density evaluator, hash input,
or recipe version changed. No commit, push, or stash was made.
## Orchestrator review (Claude)
- Merged: read-only snapshot + validator, no world change (28 hash runs and 14 crossing runs equal L19;
cost within noise). The Unreal adapter gains a 193-line `resolved_layout` export beside
`world_assembly`. It is export-only, but UNCOMPILED here; it must be built on the owner PC.
- Key facts for the owner: the authored params put the SW top at −60 m (4 m owner chunks), Core
builds SW at −120…−632 m (8 m conversion); the 60 m between FI and SW is unowned and answered by
the analytic FloatingIslands fallback as solid. No strate has an active bedrock band; SW has no
ceiling band (mesh fallback only); configured Gradient transitions are ignored by Core.
- To check next: whether the "ledges" ground seen under the islands is this fallback solid in the
unowned gap rather than SW terrain (L19 attributed them to SW at about −60…−73 m).
@@ -1,165 +0,0 @@
#!/usr/bin/env python3
"""Constrained L21 snapshot, output-parity, crossing, and off-cost evidence."""
import os
import re
import signal
import statistics
import subprocess
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[4]
OUT = ROOT / "Saved/Linux/linux21"
OUT.mkdir(parents=True, exist_ok=True)
if not os.sched_getaffinity(0).issubset(set(range(12))):
raise SystemExit("run under taskset -c 0-11")
BIN = {
"clang-off": ROOT / "Standalone/bin/linux/VoxelForgeCoreHeadless-linux21-clang",
"gcc-default": ROOT / "Standalone/bin/linux/VoxelForgeCoreHeadless-linux21-gcc",
}
OLD_CLANG = ROOT / "Standalone/bin/linux/VoxelForgeCoreHeadless-linux19-clang"
OLD_GCC = ROOT / "Standalone/bin/linux/VoxelForgeCoreHeadless-linux19-gcc"
DATA = ROOT / "Standalone/data/owner_world.json"
HASH_ROW = re.compile(r"^\[Pipeline(?:FullDetailHash|WholeViewHash|LODHash|ExactQueryHash)\].*$", re.M)
LODS = [(1, 1), (8, 1), (12, 1), (12, 2), (12, 3), (12, 4), (12, 5)]
RECIPES = {
"surface-world": "0,-35,-487.94,0,-22",
"floating-islands": "-22,-19,-22.8,0,-4",
}
results = []
def launch(name, argv, timeout=900):
logfile = OUT / f"{name}.log"
command = ["taskset", "-c", "0-11", "prlimit", "--as=6442450944", "--", *map(str, argv)]
started = time.monotonic()
peak_tree = 0
peak_process = 0
timed_out = False
with logfile.open("w", encoding="utf-8") as stream:
process = subprocess.Popen(command, stdout=stream, stderr=subprocess.STDOUT,
start_new_session=True)
while process.poll() is None:
pending, seen, total = [process.pid], set(), 0
while pending:
pid = pending.pop()
if pid in seen:
continue
seen.add(pid)
try:
pending.extend(int(x) for x in Path(f"/proc/{pid}/task/{pid}/children").read_text().split())
values = {}
for line in Path(f"/proc/{pid}/status").read_text().splitlines():
if line.startswith(("VmRSS:", "VmHWM:")):
key, amount, *_ = line.split()
values[key] = int(amount)
total += values.get("VmRSS:", 0)
peak_process = max(peak_process, values.get("VmRSS:", 0), values.get("VmHWM:", 0))
except (FileNotFoundError, PermissionError, ProcessLookupError, ValueError):
pass
peak_tree = max(peak_tree, total)
if time.monotonic() - started > timeout:
os.killpg(process.pid, signal.SIGTERM)
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
timed_out = True
break
time.sleep(0.1)
code = process.wait()
elapsed = time.monotonic() - started
rows = HASH_ROW.findall(logfile.read_text(encoding="utf-8", errors="replace"))
results.append((name, code, elapsed, peak_process, peak_tree, timed_out, len(rows)))
print(f"[L21Run] {name} exit={code} seconds={elapsed:.3f} peak_process_rss_kib={peak_process} "
f"peak_tree_rss_kib={peak_tree} hash_rows={len(rows)} timed_out={str(timed_out).lower()}", flush=True)
return logfile
def base_args(binary, recipe, workers, hash_output=False, crossing=False):
args = [binary, DATA, "--world-assembler-prototype", "--stream-benchmark", "--stream-pipeline",
"--force-generate", "--clip-radius=3", "--max-clip-level=8", f"--workers={workers}",
f"--camera={RECIPES[recipe]}", f"--recipe={recipe}"]
if hash_output:
args.append("--stream-hash")
if crossing:
args += ["--camera-step=24,0,0", "--region-crossing"]
return args
# Plan-time identities and canonical serialization at W1/W8/W12, both field recipes.
snapshots = {}
for recipe in RECIPES:
for workers, repeat in [(1, 1), (8, 1), (12, 1)]:
path = OUT / f"snapshot-{recipe}-w{workers}-r{repeat}.json"
args = [BIN["clang-off"], DATA, "--world-assembler-prototype", "--stream-benchmark",
"--stream-pipeline", f"--recipe={recipe}", f"--workers={workers}",
f"--resolved-layout-output={path}", "--resolved-layout-only"]
log = launch(f"snapshot-{recipe}-w{workers}-r{repeat}", args)
if results[-1][1] != 0:
raise SystemExit(f"snapshot plan failed: {log}")
snapshots[(recipe, workers)] = path.read_bytes()
if len({snapshots[(recipe, workers)] for workers in (1, 8, 12)}) != 1:
raise SystemExit(f"snapshot serialization changed with worker count: {recipe}")
print(f"[L21SnapshotIdentity] recipe={recipe} worker_counts=1,8,12 canonical_bytes=identical status=PASS", flush=True)
# Full matrix. Every row is compared against the L19 W12x5 reference.
for recipe in RECIPES:
for compiler, binary in BIN.items():
for workers, repeat in LODS:
name = f"matrix-{recipe}-{compiler}-w{workers}-r{repeat}"
log = launch(name, base_args(binary, recipe, workers, hash_output=True))
rows = HASH_ROW.findall(log.read_text(encoding="utf-8", errors="replace"))
reference_name = f"{recipe}-{compiler}-w12-r5.log"
reference = ROOT / "Saved/Linux/l19-matrix" / reference_name
expected = HASH_ROW.findall(reference.read_text(encoding="utf-8", errors="replace"))
if results[-1][1] != 0 or len(rows) != 12 or rows != expected:
print(f"[L21HashMismatch] {name} expected_rows={len(expected)} actual_rows={len(rows)}", flush=True)
raise SystemExit(1)
# The crossing matrix retains the 24 m two-view query proof on both compilers.
for compiler, binary in BIN.items():
for workers, repeat in LODS:
name = f"crossing-{compiler}-w{workers}-r{repeat}"
log = launch(name, base_args(binary, "surface-world", workers, hash_output=True, crossing=True))
rows = HASH_ROW.findall(log.read_text(encoding="utf-8", errors="replace"))
reference = ROOT / "Saved/Linux/l19-crossing" / f"{compiler}-w12-r5.log"
expected = HASH_ROW.findall(reference.read_text(encoding="utf-8", errors="replace"))
if results[-1][1] != 0 or len(rows) != 12 or rows != expected:
print(f"[L21CrossingHashMismatch] {name} expected_rows={len(expected)} actual_rows={len(rows)}", flush=True)
raise SystemExit(1)
# Five interleaved W12 pairs per recipe, hashing disabled. Alternate order by pair to reduce drift.
off_pairs = {recipe: {"old": [], "new": []} for recipe in RECIPES}
for recipe in RECIPES:
for pair in range(1, 6):
order = [("old", OLD_CLANG), ("new", BIN["clang-off"])] if pair % 2 else [("new", BIN["clang-off"]), ("old", OLD_CLANG)]
for label, binary in order:
name = f"offcost-{recipe}-pair{pair}-{label}"
log = launch(name, base_args(binary, recipe, 12, hash_output=False), timeout=900)
if results[-1][1] != 0:
raise SystemExit(f"hashing-off cost run failed: {log}")
off_pairs[recipe][label].append(results[-1][2])
print(f"[L21OffCostPair] recipe={recipe} pair={pair} old_seconds={off_pairs[recipe]['old'][-1]:.3f} "
f"new_seconds={off_pairs[recipe]['new'][-1]:.3f}", flush=True)
for recipe, pair in off_pairs.items():
old = statistics.median(pair["old"])
new = statistics.median(pair["new"])
print(f"[L21OffCostSummary] recipe={recipe} pairs=5 median_old_seconds={old:.3f} "
f"median_new_seconds={new:.3f} delta_percent={(new-old)/old*100.0:.2f}", flush=True)
# Query the real compiled Core field at every distinct recorded stratum/band endpoint.
for recipe in RECIPES:
name = f"boundary-probes-{recipe}"
args = base_args(BIN["clang-off"], recipe, 12, hash_output=False)
args += ["--audit-resolved-layout-boundaries"]
log = launch(name, args)
if results[-1][1] != 0:
raise SystemExit(f"Core boundary probes failed: {log}")
print(f"[L21EvidenceSummary] snapshots=6 matrix=28 crossing=14 off_cost_pairs=10 boundary_audits=2 status=PASS", flush=True)
for name, code, elapsed, rss, tree, timed_out, rows in results:
print(f"[L21RunDetail] {name} exit={code} seconds={elapsed:.3f} peak_process_rss_kib={rss} "
f"peak_tree_rss_kib={tree} hash_rows={rows} timed_out={str(timed_out).lower()}", flush=True)
@@ -1,173 +0,0 @@
# Linux22 — one strate-layout unit and the closed stack
The owner setting is now **8 m per layout chunk** for every generator. FloatingIslands spans **+8 to −120 m** (128 m) and SurfaceWorld spans **−120 to −632 m** (512 m). Their shared boundary is −120 m, so the old 60 m gap is gone. SurfaceWorld keeps the same physical interval and content field as L21.
## Stack and bands
| Strate | Full interval | Ceiling | Content | Bedrock |
|---|---:|---:|---:|---:|
| FloatingIslands | +8…−120 m | +7.5…+8 m (0.5 m) | +7.5…−119.5 m (127 m) | −119.5…−120 m (0.5 m) |
| SurfaceWorld | −120…−632 m | −120…−126.25 m (6.25 m) | −126.25…−625.75 m (499.5 m) | −625.75…−632 m (6.25 m) |
```text
z=+8.00 m FloatingIslands ceiling outer face
z=+7.50 m FloatingIslands content begins
Islands: bottoms −63.468…−60.912 m; tops −57.419…−52.357 m
z=−119.50 m FloatingIslands bedrock inner face
z=−120.00 m FI/SW boundary: FI bedrock meets SW ceiling; no gap
z=−126.25 m SurfaceWorld content begins; cap profiles rise above here
z=−625.75 m SurfaceWorld bedrock inner face
z=−632.00 m SurfaceWorld bedrock outer face
```
The alternate owner SurfaceWorld recipe also exercises TunnelNetwork above it: TunnelNetwork uses the same +8…−120 m interval, with a 1 m ceiling, 126 m content band, and 1 m bedrock band. Every tested strate type receives both solid bands in the shared composition path. Existing `BoundarySealThickness` supplies each band’s thickness: TunnelNetwork 8 owner voxels = 1 m, FloatingIslands 4 = 0.5 m, SurfaceWorld 50 = 6.25 m. `BaseDensity` supplies solid density. Bands are diggable and unprotected by default. `InterStrateGapChunks=0` controls spacing, not band thickness; `EdgeSealThickness` remains horizontal. No new thickness parameter was needed.
Visible ceilings use the shared L18/L19 boundary path, extended to floors. The authored transitions are Gradient (blend widths 2 chunks for the upper strate and 1 for SurfaceWorld), but Core still uses the explicit **Hard fallback with zero interpenetration**. The snapshot records this deviation; Gradient and Interleaved blending are not claimed as implemented.
## Unit resolution and validation
`StrateLayoutChunkSizeMeters` is one world setting with an 8.0 m default. The director/adapter and standalone loader resolve it to micrometres and Core fixed-point width. At 25 cm Core voxels the width is 8,192 subvoxels = 32 Core voxels; at the S1 20 cm check it is 10,240 subvoxels = 40 Core voxels. The internal 32³ Core tile remains a separate concept.
Changed conversion and consumer sites:
- `UVoxelStrateManager` resolves the world setting; `VoxelForgeCoreAdapter::AttachValidatedWorldAssembly` passes one fixed-point width into recipes and `ResolvedLayoutSnapshotV2`. `OwnerWorldLoader::Resolve` mirrors that resolution in the standalone path.
- `BuildSurfaceStratumPlan` now scales chunk bounds by the resolved width instead of `CHUNK_SIZE` (32 Core voxels). `BuildFloatingIslandStratumPlan` writes the same width into geometry version 4.
- `NativeSurfaceDensityAt` and native SurfaceWorld strata classification use snapshot width for `floor(CoreZ / width)` and bounds. FloatingIslands dispatch uses its validated snapshot recipe width. Legacy TunnelNetwork chunk lookup uses the same snapshot width.
- Shared ceiling and floor composition, far-shell clipping, cap bounds, endpoint probes, and strict layout validation use the resolved width. `FloatingIslandManifestV1::FromJson` no longer reconstructs legacy width from Core tile size or owner/Core voxel ratio; world assembly supplies and validates the resolved value.
Current owner snapshots:
- SurfaceWorld recipe: `resolved-layout-v2-fnv64:96d6a8b64f73c2d8`.
- FloatingIslands recipe: `resolved-layout-v2-fnv64:2b343bc155f181d5`.
- 20 cm S1 snapshot: `resolved-layout-v2-fnv64:0a56caef7dd44cac`.
Strict validation passed on the generated owner world for both recipes: zero issues, 7/7 negative controls rejected, and 27 boundary probes per recipe with **zero dispatch/snapshot disagreements**. Both stacks have zero unowned gap and zero undeclared band overlap. The 20 cm snapshot also passed strict validation.
## SurfaceWorld clearance and spawn
The clearance scan samples a 4,096 × 4,096 m area at 1 m spacing around the derived route spawn (16,785,409 samples). Clearance is ceiling inner face minus the higher of ground and cap. Negative values mean a cap pokes through the ceiling at −126.25 m.
| Biome slot / ID | Max ground | Max cap/surface | Minimum sampled clearance |
|---|---:|---:|---:|
| 0 / 4097 | −442.333 m | −44.496 m | **−81.754 m** |
| 1 / 4098 | −313.660 m | −30.881 m | **−95.369 m** |
| 2 / 4099 | −419.399 m | −0.425 m | **−125.825 m** |
| 3 / 4100 | −361.088 m | −109.922 m | **−16.328 m** |
Ground/mountain surfaces stay below −313.660 m in this scan. The collisions come from cap profiles: authored `CeilingUndulation` is 1000 or 900 Core voxels (250 m or 225 m). They were not clamped. The owner can raise the strate or reduce those cap profiles. Since SurfaceWorld’s interval and content are unchanged from L21, this clearance issue is unchanged too.
The SurfaceWorld plan produces 33 route points. The L1 benchmark and spawn camera now derive from `route.front`: **(9.250, 41.250, −502.848) m**, yaw 0°, pitch −22°. Route planning passed (648 candidates, 366 grade rejects, zero sweep rejects); walkability passed 5,642/5,642. The highest route point is −501.714 m, giving 375.464 m clearance to the ceiling face. FloatingIslands walkability passed 4,000/4,000.
| Island | Bottom…top | Bedrock margin | Ceiling margin |
|---:|---:|---:|---:|
| 0 | −62.700…−57.419 m | 56.800 m | 64.919 m |
| 1 | −61.410…−56.000 m | 58.090 m | 63.500 m |
| 2 | −63.468…−55.878 m | 56.032 m | 63.378 m |
| 3 | −60.912…−52.357 m | 58.588 m | 59.857 m |
## Captures
All six L22 captures are 1600×900 JPEGs under 50 KB (limit 300 KB). SurfaceWorld images compare with L19’s same-named views. The FI review angle is the owner-style low view at (−22, −19, −61) m; separate views look up at the ceiling and down at the new bedrock floor.
| View | L22 | L19 equivalent |
|---|---|---|
| SurfaceWorld, route-derived spawn | [L22](captures/surface-world-l1-spawn-after.jpg) | [L19](../Linux19/captures/surface-world-l1-spawn-after.jpg) |
| SurfaceWorld horizon | [L22](captures/surface-world-horizon-after.jpg) | [L19](../Linux19/captures/surface-world-horizon-after.jpg) |
| SurfaceWorld rings from above | [L22](captures/surface-world-rings-above-after.jpg) | [L19](../Linux19/captures/surface-world-rings-above-after.jpg) |
| FloatingIslands low owner angle | [L22](captures/floating-islands-owner-angle-after.jpg) | [L19](../Linux19/captures/floating-islands-owner-angle-after.jpg) |
| FloatingIslands ceiling | [L22](captures/floating-islands-ceiling-up-after.jpg) | [L19](../Linux19/captures/floating-islands-ceiling-up-after.jpg) |
| FloatingIslands bedrock floor | [L22](captures/floating-islands-bedrock-down-after.jpg) | — |
A whole-stack side render was not readable from the surface-only mesh export. The vertical stack diagram above gives the exact interfaces and bands.
## L19 ring tables rerun
RingProbe ran on L19 and L22 meshes at the same historical cameras: SurfaceWorld (0, −35, −487.94) m and FloatingIslands (−22, −19, −22.8) m. Values are median / p95 / maximum absolute edge-height difference in centimetres, followed by no-hit edge count. These are LOD mesh-edge gaps, not gaps in the validated strate stack.
### SurfaceWorld rings
| LOD | L19 edges/samples | L19 cm (gaps) | L22 edges/samples | L22 cm (gaps) |
|---|---:|---:|---:|---:|
| 0→1 | 46/288 | 0.178 / 0.594 / 1.171 (10) | 46/288 | 0.178 / 0.594 / 1.171 (10) |
| 1→2 | 32/288 | 1.419 / 4.990 / 10.438 (0) | 32/288 | 1.419 / 4.990 / 10.438 (0) |
| 2→3 | 34/256 | 2.179 / 12.648 / 35.355 (2) | 66/544 | 0 / 8.260 / 35.355 (2) |
| 3→4 | 40/265 | 5.099 / 35.999 / 1,190.974 (5) | 72/537 | 0 / 22.456 / 1,190.974 (6) |
| 4→5 | 58/270 | 0.235 / 3.694 / 491.570 (14) | 104/835 | 0 / 77.070 / 5,751.081 (6) |
| 5→6 | 65/266 | 12.234 / 127.224 / 536.573 (33) | 96/576 | 0 / 0 / 6,935.708 (32) |
| 6→7 | 41/269 | 28.238 / 291.861 / 945.477 (7) | 64/288 | 0 / 2,991.225 / 9,240.525 (32) |
| 7→8 | 32/275 | 83.843 / 1,225.416 / 3,755.407 (0) | 32/288 | 0 / 10,444.014 / 10,839.630 (0) |
The 0→1 and 1→2 rows are unchanged. Higher rings changed as the complete strata bands and far boundaries entered the view; the largest far-ring discrepancies increased. The full LOD-stable interface surface remains future work.
### FloatingIslands / SurfaceWorld interface rings
| LOD | L19 edges/samples | L19 cm (gaps) | L22 edges/samples | L22 cm (gaps) |
|---|---:|---:|---:|---:|
| 0→1 | 0/0 | — (0) | 63/185 | 1.328 / 6.795 / 10.623 (17) |
| 1→2 | 33/231 | 147.141 / 148.403 / 149.862 (0) | 0/0 | — (0) |
| 2→3 | 49/308 | 128.603 / 200.789 / 773.318 (8) | 32/288 | 0 / 0 / 0 (0) |
| 3→4 | 64/277 | 3.269 / 47.774 / 188.531 (27) | 32/288 | 0 / 0 / 0 (0) |
| 4→5 | 72/544 | 29.992 / 124.373 / 443.482 (6) | 72/547 | 0 / 74.140 / 552.186 (6) |
| 5→6 | 64/266 | 12.234 / 127.224 / 536.573 (32) | 64/288 | 0 / 0 / 0 (32) |
| 6→7 | 32/264 | 29.013 / 301.752 / 42,624.479 (0) | 32/288 | 0 / 0 / 0 (0) |
| 7→8 | 64/275 | 83.843 / 1,225.416 / 3,755.407 (32) | 64/288 | 0 / 0 / 0 (32) |
The FI table changed substantially. The new bedrock floor is visible at −119.5 m and supplies flat matched samples in several coarser rings; the old L1→2 interface edge is absent in this camera’s L22 mesh. This does not implement the later full LOD-stable interface design.
## Hashes, determinism, invariants, and cost
Versions: evaluator 7, recipe schema 2, layout snapshot schema 2, FloatingIslands geometry 4. New W12 baseline rows are density / mesh / payload / topology:
| Recipe/view | Full detail | Whole view |
|---|---|---|
| SurfaceWorld, derived spawn | `e7e0b0668a491c46 / ca35fe7a91099574 / 19f29f621cfdbbc7 / e37b3191a7200c67` | `4932f16f7d8dd5ab / 98e68419a13b76db / 56124d542206790c / 75ef1148afa20ca8` |
| FloatingIslands, auto island camera | `647bcb4038627e16 / 87324ad688a49bfa / a0c5b9a73288e393 / f9c316a79dd42152` | `2b5b06283399ad9d / 5c66f389b526f6bb / f2e7ff68d9dc2262 / 121abcf0607f0cf1` |
For the same historical SurfaceWorld camera, L21 and L22 exact-query density/unclamped hashes match at `e4d4a8eb95b35933`; detail is `efcba20c0c70c415`, collision is `e604823a249029bf`. Full-detail hashes also match exactly: `0ee0579bd15cbbe4 / 32e5d4964d610fee / 1932b96ee4b1d910 / 69743c6bad3447dc`. Whole-view hashes differ because shared bands and complete outer strata now contribute to the mesh.
Determinism passed 28/28 runs (both recipes, Clang 19 with FP contraction off and GCC 14 default; W1, W8, W12×5). The 24 m SurfaceWorld crossing passed 14/14. Resolved snapshots were byte-identical across W1/W8/W12. Final W12 smoke hashes on both post-guard binaries still match their baselines. SurfaceWorld route parity passed with 782,026 exact-query samples and zero mismatches; FloatingIslands also passed with 782,026 samples and zero mismatches. SurfaceWorld’s proof audit checked 25,927 blocks / 34,508,837 samples with zero violations. FI had zero checked blocks and 24,576 conservative unknown/fallback blocks, zero violations; it did not claim positive proof coverage. Shape readiness, base/page equivalence, and walkability audits passed.
The W12 hashing-off five-pair median cost against the L21 binary was 1.613 s → 1.411 s for SurfaceWorld (−12.52%) and 11.087 s → 18.840 s for FloatingIslands (+69.93%), reflecting FI’s added 64 m of volume. Largest measured process RSS was 897,840 KiB; largest process-tree RSS was 4,603,848 KiB. Builds and runs stayed under the 6 GiB address-space limit, CPUs 0–11, at most 12 workers, and the 15/30 minute limits. The governor was unchanged.
The L3 FP-contract preamble/self-test and L4 `FLazy`, L7 shared cache, L9/L12 proofs, L11 readiness/crash handling, L13 route binding, L18/L19 shared ceiling, L21 snapshot/validator, `ARCHITECTURE.md` §8.10, and CLAUDE.md async rules remain in place. The Linux22 architecture note is §8.40.
## Unreal edits and Windows checklist
Unreal edits are limited to:
- `Source/VoxelForge/Public/VoxelSettings.h` — world setting `StrateLayoutChunkSizeMeters`, default 8.0.
- `Source/VoxelForge/Public/VoxelStrateManager.h` and `Private/VoxelStrateManager.cpp` — resolve and use one layout width for manager strate bounds/lookups.
- `Source/VoxelForge/Private/VoxelForgeCoreAdapter.cpp` — pass that width to plans and the V2 snapshot; compose the same parameter-driven ceiling and bedrock bands for each generator.
The Unreal module cannot be compiled on this Linux machine. Windows checklist:
1. Rebuild the VoxelForge module and confirm the setting defaults to 8.0 m.
2. Load the owner world with FloatingIslands and SurfaceWorld; verify +8…−120 m and −120…−632 m, with no gap at −120 m.
3. Verify ceiling and bedrock are visible and breakable, then check the route-derived SurfaceWorld spawn and cap/ceiling collisions against the captures.
4. Run the boundary validator and compare the generated snapshot with the two Linux22 identities above.
## Failed and retried runs
- Three early Clang builds failed while implementation files were being synchronized: the standalone loader referenced settings/API not yet copied; the next compile found three undeclared copied-manager width references; a later attempt found a missing closing brace in the clearance audit. These were corrected; the final Clang and GCC builds passed.
- One final smoke attempt used a nonexistent `linux22-clang-off` binary suffix and exited 127 before running a workload. It was rerun with the correct `linux22-clang` and `linux22-gcc` paths; all four W12 hash checks passed.
- A zero-byte `build-clang-off-floor.log` has no recorded compiler output and was superseded by the successful measured final builds.
- The clearance scan completed successfully and reported the cap collisions above; this is a world-fit finding, not a failed run. No build or run timed out or exceeded its limit.
Nothing was committed, pushed, or stashed.
## Orchestrator review (Claude)
- Merged. The strict validator passes on the real owner world; SW full-detail and exact-query hashes are
unchanged (content did not move); FI is +8…−120 m with a bedrock floor.
- Captures checked by me: the FI owner-angle view shows islands above a clean, flat bedrock floor with a
closed ceiling, and the ledges are gone. The SW rings-from-above view shows continuous terrain with no
visible ring steps, so the large far-ring values in the RingProbe table (up to ~108 m) are most likely the
probe pairing different surfaces now that bands are in view, not real breaks. Treat that table with care
until the probe filters by surface owner. The SW horizon is from the new route-derived spawn, so it is not
the same angle as L19.
- Owner decision needed: SW cap profiles (`CeilingUndulation` 225–250 m) exceed the new ceiling band by up
to ~126 m; reported, not clamped.
- Cost: FI whole view +70% (its strate doubled in volume); SW −12.5%.
- Unreal edits (VoxelSettings `StrateLayoutChunkSizeMeters` = 8.0, StrateManager, CoreAdapter) are
UNCOMPILED here; Windows checklist above. CLAUDE.md's scale rule was updated to match.
- Transitions are still Hard (recorded deviation).
Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

@@ -1,158 +0,0 @@
# L23 — inter-strate passage
## Owner answer
**After L22, Core did not have a resolved-layout passage through the new bands.** L22 exported
`FVoxelPassage` points as `milli owner voxels` metadata, but the native FloatingIslands and
SurfaceWorld Core paths did not use that metadata to carve the resolved bands. The legacy manager
still has `UVoxelStrateManager::GeneratePassages`; its coordinates are in owner voxels, not metres.
The owner voxel is 12.5 cm (`OwnerVoxelSizeMicrons=125000`); `voxel_size_cm=25` is the Core voxel.
The legacy 0→1 passage therefore had upper `(-19.594, 3.137, -14.255) m` and lower
`(-19.594, 3.137, -102.959) m`, with radius 1 m. Its lower point was still in FloatingIslands
content (`-119.5…+7.5 m`), 23.29 m above SurfaceWorld content (`-625.75…-126.25 m`). It did not
open the FI bedrock (`-120…-119.5 m`) and SW ceiling (`-126.25…-120 m`). The JSON also contains a
legacy 0→0 passage; L23 plans only adjacent resolved strata.
L23 now derives the passage from the director-resolved bands and route anchors. For the FI recipe,
mouths are `(9.800, 4.571, -54.831) m` and `(9.250, 9.250, -502.608) m`. For the SurfaceWorld
recipe the unanchored upper mouth is `(10.732, -5.775, -107.766) m`; the lower mouth is the same.
Both locations are inside the actual content and within 24 m of `(0,0)`.
## Planner, radius, and routes
`UVoxelStrateManager::GeneratePassages` remains the legacy Unreal planner. L22's season manifest
carried recipes/routes, while the adapter copied manager passage points into V2 anchors with the
legacy units. L23's adapter and headless director convert each upper strate's `PassageConfig` to
Core fixed units, build a V3 layout with route anchors, then call `PlanResolvedLayoutPassagesV1`.
The planner hashes seed, upper/lower strate, connection, and salt, so peers with the same resolved
input choose the same path. Strate moves and route changes trigger a new plan; exported root
`passages` are not imported.
The placement disk comes from `PassageConfig.DistanceMax=192` owner voxels = 24 m; when no route
anchor is available, `DistanceMin=64` owner voxels = 8 m supplies the inner annulus. `OriginSpineRadius`
and spawn radius are separate settings. `MouthRadius`/`MidRadius` set tunnel cross-section; Core
enforces a 1.25 m minimum radius for the player capsule. Neither ceiling nor cap parameters changed.
In the FI snapshot, route point 28 (last of 29) equals the FI departure mouth; SW route point 0
(first of 33) equals its arrival mouth. Both route audits pass. This owner layout has exactly two
strata, so SW has no next interface/departure mouth; its free route endpoint is
`(54.750, 54.750, -502.308) m`.
## Passage audit
Capsule is 0.34 m × 1.76 m. A passage fails on any blocked capsule sample, unsupported floor probe,
grade failure, mouth outside content/radius, route-mouth mismatch, or if the no-passage control
does not detect blockage.
| Recipe | Interfaces | Center samples | Capsule samples | Blocked | Support probes / unsupported | Grade failures | Mouths in content / radius |
|---|---:|---:|---:|---:|---:|---:|---:|
| FloatingIslands → SurfaceWorld | 1/1 | 5,174 | 325,962 | 0 | 40,412 / 0 | 0 | 2/2 · 2/2 |
| TunnelNetwork → SurfaceWorld | 1/1 | 4,513 | 284,319 | 0 | 35,254 / 0 | 0 | 2/2 · 2/2 |
The deliberate no-passage controls found 17,218 blocked capsule samples (FI recipe) and 23,876
(SurfaceWorld recipe); both were detected. FI’s 29-point route and SW’s 33-point route pass with
0 blocked samples, 0 unsupported probes, 0 grade failures, and mouth binding 2/2. The
SurfaceWorld-only route passes 33 points with the same zero failures and binding 1/1.
The shared composition layer applies each generator field, then bedrock/ceiling bands, then the
bounded passage carve and support shelf. Only the tunnel path opens a band. The full 0→1 capsule
audit crosses the FI bedrock and SW ceiling; support stays below the capsule.
The audit samples the resolved Core field by interface owner and does not reuse the old ring-table
probe, so it does not pair band and content samples from different surface owners.
Runtime passage checks covered all eight generator kinds: TunnelNetwork, FlatPlain, CrystalChamber,
Maze, VerticalShafts, and Underwater as upper-strate fixtures; FloatingIslands in the FI recipe;
SurfaceWorld as the real lower strate in both owner-world recipes. The SurfaceWorld-as-upper fixture
could not produce its separate route: all 648 route candidates failed the grade filter. That fixture
is recorded as a failed route setup, not counted as a passage pass. The real SurfaceWorld lower
strate audits pass.
## Determinism, proofs, and content hashes
Clang 19 (`--fp-contract=off`) and GCC 14 (`--fp-contract=default`) builds passed. Both executables
ran the mandatory Core FP-contraction self-test without rejection. For both recipes, W1/W8/W12×5
across both compilers produced one distinct result per hash class. The same 28-run matrix passed the
24 m region crossing: 314 moving tiles, stable within each recipe. Route parity passed on both
compilers: 8/8 page pairs, 14 higher-LOD exact pairs, 782,026 exact-query samples, and one edit,
all with zero mismatches. V3 strict validation accepted both layouts with 0 issues; all 9 malformed
layout controls were rejected.
Passage-centered uniform-proof boxes are conservatively unknown/fallback (FI: 21,504 fallback and
unknown, 0 violations); no false certificate is emitted around the new carve. Away from the passage,
SurfaceWorld at `(512,512,-500) m` matches the L22 baseline bit-for-bit: 27,368 certified blocks,
36,426,808 samples, 1,304 fallbacks, 0 unknowns/violations. Full-detail hash is
`66ac781666579e3e / 914873894a0e38c4 / ec8b03ade039cd56 / a2b621b0321d43dc` (density/mesh/payload/
topology); whole-view hash is `ddc6d1942db48f52 / bce985905e70dac4 / 266f5a008bcf4491 /
e6fa520c5ad2817b`. LOD0–3 and 9 exact-query hashes also match. The earlier unbounded comparison
included the far horizon and was discarded; this comparison used render-distance 0 and max LOD 3.
Changes are limited to resolved passage planning, band openings along those paths, and supported
landings. SurfaceWorld content away from the passage is unchanged by the hashes above. L3 FP
contract setup/self-test, L4 `FLazy`, L7 shared cache, L9/L12 proof behavior, L11 readiness/crash
path, L13 route binding, L18/L19 shared ceiling, L21/L22 layout bands, ARCHITECTURE §8.10, and
`CLAUDE.md` async/Epoch rules remain intact. The route and passage audits exercise L13 binding; the
async/cache files were not edited.
## Captures
Small 1280×720 JPEGs (all render inputs/PNG intermediates stay in `Saved/Linux/linux23/`):
- [FI passage mouth](captures/fi-mouth.jpg)
- [Tunnel at the FI bedrock / SW ceiling interface](captures/tunnel-interface.jpg)
- [Arrival in SurfaceWorld](captures/sw-arrival.jpg)
## Changes and Windows checklist
Version bumps: resolved-layout snapshot V3, evaluator 9, FloatingIslands geometry 4. The only
Unreal-side source edit is `Source/VoxelForge/Private/VoxelForgeCoreAdapter.cpp`: it binds V3
routes/configs and invokes the resolved planner. Core and standalone sources build here; the Unreal
adapter cannot be compiled on this Linux host.
On Windows:
1. Build the Editor/plugin with the updated Core header and adapter; check UHT and link.
2. Load the owner world at seed 0 and verify strict V3 validation and stable mouth coordinates.
3. Walk the FI route, passage, and SW route with the 0.34 m × 1.76 m capsule; inspect all three
capture viewpoints in-engine.
4. Move a strate or route anchor, reload, and verify the passage is re-derived and peer-identical.
5. Confirm SW away from the passage and its ceiling/cap parameters remain unchanged.
## Failed and retried runs
Failed development audit logs (all retained under `Saved/Linux/linux23/`): FI
`audit-floating-islands.log`, `r2–r5`, `r17–r19`, `r21–r36`, `r38–r41`; SurfaceWorld
`audit-surface-world.log`, `audit-surface-world-diagnostic.log`, `audit-surface-world-diagnostic-r2/r3`,
and `audit-surface-world-r2–r7`, `r19`, `r21–r22`, `r24–r26`, `r28–r31`, `r33`, `r35`. The early
failures were blocked capsule samples or unsupported landing probes. r35 still had 10 unsupported
passage support probes; r36’s correction left 1,977 blocked capsule samples. r37 build failed on
undeclared `begin/end`; r38 regressed to 10 unsupported probes. r39–r41 diagnostics traced support
search across a non-monotone lower route tail; r42 build failed on `continue` inside a lambda. The
lower-mouth split/index fix passed r43; final Clang/GCC builds and audits pass.
Other retries: `plan-surface-world-r2.log` used the wrong data path; two layout-only calls omitted
the required benchmark/pipeline flags and exited 2. The first upper-SurfaceWorld fixture failed its
648-candidate route search as noted above. Initial offscreen renders hit the read-only Mesa cache
location and were rerun with cache disabled and the CPU/address-space limits. Initial captures were
also rerendered under affinity/memory limits. Camera trials were replaced by the three listed JPEGs.
The first SurfaceWorld away hash comparison included the far horizon and was replaced with the
bounded L22/L23 comparison. The hash parser initially reported missing rows because its regex was
not multiline; corrected parsing found 28/28 runs and zero mismatches.
Runs were pinned to CPUs 0–11 and capped at 6 GiB address space; no task exceeded 30 minutes or
stalled for 15. This shell inherited nice level 5; an attempt to restore normal priority was denied,
so I made no priority or governor change. No commit, push, or stash was made.
## Orchestrator review (Claude)
- Merged as a correctness fix: the strates were not connected after L22 (and Core never carved the
passage at all); now a planned, deterministic passage crosses FI bedrock and the SW ceiling, with a
capsule audit of 0 blocked / 0 unsupported and a detected negative control.
- **The look is not yet "natural" (my capture review):** `fi-mouth.jpg` shows a stepped tube hanging in
FI's open void (there is no rock to carve between the island-level mouth at −54.8 m and the bedrock at
−119.5 m); `sw-arrival.jpg` shows flat stacked terraces; `tunnel-interface.jpg` is too close to read.
Owner input needed on where an FI passage should start (island vs bedrock floor) and how it should
look.
- Open: the SurfaceWorld-as-upper-strate fixture can't plan its route (648/648 grade-rejected), a real
limit for future layouts.
- Unreal adapter edit uncompiled here; Windows checklist above.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

@@ -1,113 +0,0 @@
# VoxelForge L24 — passages and anchor island
## Owner summary
Inter-strate passages are now planned in Core from the upper strate's `FStratePassageConfig`, for every generator. The public default is **Worm**: a gently graded, deterministic meander with variable radius and rough walls. Straight, Spiral and Cascading remain selectable per strate. FloatingIslands sets its upper passage to **Spiral** and gets a unique anchor island with a helical ramp down inside a rock root to the bedrock floor; the passage then continues through the SurfaceWorld ceiling. The other islands remain floating.
The seed-derived anchor is stable island ordinal 2 at about `(9.800, 4.571) m`, within the 24 m placement disk; its mouth phase also hashes the seed and stable island ID. The root radius is 6 m, the helix radius is 3 m and the bore radius is at least 1.5 m, leaving 1.5 m nominal rock between the bore and root edge before bounded relief. The authored two-turn minimum extends to 19 turns to keep the 64 m descent under the 10.8-degree target. The root reaches the bedrock floor at about `-119.5 m`. The FI route departure is bound to the island mouth. Island placement hashes and ordinals for the other islands are unchanged.
The SurfaceWorld arrival uses its native hillside/terrain plus the passage tread; the shared carver no longer stamps a flat lower route-anchor shelf over the cave opening. The final mouth capture shows the opening from above and a few metres away.
## Captures
All are JPEGs under 300 KB. The FI exterior capture pairs a full view with a world-space half-plane cutaway; the second panel exposes the helical bore in the root above the bedrock slab. The interior image is from the audited centerline, aimed down the ramp with a 150-degree camera and camera headlamp. The SurfaceWorld arrival is an overhead view, about 7 m laterally from the mouth. Straight and Worm are left/right from matching final-source views.
- [FI anchor island, root and helix cutaway](captures/fi-anchor-cutaway.jpg) — 35,221 bytes
- [Inside the helix, looking along the descent](captures/fi-helix-inside.jpg) — 8,754 bytes
- [SurfaceWorld arrival mouth](captures/sw-arrival-mouth.jpg) — 14,720 bytes
- [Straight (left) beside default Worm (right)](captures/straight-vs-worm.jpg) — 60,020 bytes
## Passage and naturalness audits
The capsule is 0.34 m wide by 1.76 m high. The grade contract is 15 degrees; the planner targets at most 10.8 degrees to leave margin. Wall and ceiling relief is up to 0.24 m, gravity-facing relief is attenuated by 20%, and the floor relief stays gentler with support under the capsule. The naturalness check rejects horizontal runs longer than 8 m (segments flatter than 0.5 degrees) and requires at least 0.20 m peak-to-peak wall relief from at least 8 valid wall samples. The L23 smooth, unrelieved wall control measures 0 m relief and is detected as a failure.
Final-source Clang r55 FI audit: 801 control points, 5,317 centers, 334,971 capsule samples; **0 blocked, 0 unsupported, 0 grade failures**; support samples 29,278; both mouths are in content and within radius; two route bindings pass; blocked-passage negative control detected. Naturalness: flat run 0 m, wall relief 0.793 m from 72 samples; pass. Strict V3 validator accepted the layout and rejected 9/9 malformed controls.
Final-source Clang r55 SurfaceWorld style sweep:
| Style | Capsule samples | Blocked / unsupported / grade failures | Wall relief | Naturalness |
|---|---:|---:|---:|---|
| Straight | 284,256 | 0 / 0 / 0 | 0.441 m (10 samples) | Pass |
| Worm | 284,949 | 0 / 0 / 0 | 0.298 m (12 samples) | Pass |
| Spiral | 337,995 | 0 / 0 / 0 | 0.753 m (14 samples) | Pass |
| Cascading | 287,910 | 0 / 0 / 0 | 0.435 m (14 samples) | Pass |
All styles had 0 m flat runs against the 8 m limit; route bindings, blocked controls and strict validator controls also passed in each run. The earlier L23 geometry has 0 m wall relief and fails the new naturalness threshold.
Audit logs are in `Saved/Linux`: `linux24-audit-fi-clang19-r55-lower-mouth.log` and `linux24-style-{straight,worm,spiral,cascading}-surface-final-r55.log`.
## Determinism and compatibility evidence
The final-source r55 worker matrix passed Clang and GCC at W1, W8, W12, and W12 repeated five times. It covers all 120 full-detail tiles and the 176-tile whole view through LOD2; every worker/repeat/compiler produced identical hashes:
| Final-source view | Density | Mesh | Payload | Topology |
|---|---|---|---|---|
| Full detail, 120 tiles | `657388bd79ce59a1` | `7ab35e5ea2bd80a5` | `fe853e905a362755` | `963af083379cfd25` |
| Whole view, 176 tiles through LOD2 | `90d1f05a8c8c2406` | `c330e8944d533dd6` | `47102acb793fb854` | `354faeb5134a0aea` |
| LOD0, 64 tiles | `25d79b76f9d0cd01` | `33a2c2fdee222be5` | `32b8a3331d984725` | `7033aba8bb626ea5` |
| LOD1, 56 tiles | `24df5021a729fdd5` | `65cf44f4e7cf20e5` | `0fda084ee0cc0355` | `35ffa189a5b54da5` |
| LOD2, 56 tiles | `d5cf2f60a27cfee2` | `dbb8283a93e79956` | `05f9170ad820dac4` | `6d79c252b66d30ea` |
| Exact probes, 9 | `7b7c50ac24ccadcc` | detail `efcba20c0c70c415` | collision `e604823a249029bf` | — |
Per-run logs are in `Saved/Linux` as `linux24-r55-worker-hash-fi-{clang,gcc}-l2-w1.log`, `...-w8.log`, `...-w12.log`, and `...-w12-r1.log` through `...-r5.log`. Crossing, away-field, proof, boundary and L13 logs use the same `linux24-r55-` prefix.
The unrestricted r55 hash runs including LOD3 stopped after shape compilation without producing pipeline hashes; they were not counted as passes. The r54 full matrix passed Clang and GCC at W1, W8, W12, W12×5 and LOD0–8. Representative r54 hashes (before lower-mouth shelf removal) were:
| View | Density | Mesh | Payload | Topology |
|---|---|---|---|---|
| Full detail, 120 tiles | `e248e7f04a0eb5dc` | `09c8289f260df275` | `7501d467bebdc9b2` | `43c78d5cab335dbf` |
| Whole view, 195 tiles | `d4833386ea55cc28` | `26863a50c8138aa6` | `46601fd8395b44ea` | `9680964dfaa5f2d1` |
| Exact probes, 9 | `dea346fbf2e2d259` | detail `efcba20c0c70c415` | collision `97df60072c993bff` | — |
The r55 24 m crossing passed for FI and SurfaceWorld on both compilers: 314 entering tiles each in the full crossing run. The final-source hashed LOD0–1 crossing covered 288 entering tiles and matched across compilers. FI hashes (density/mesh/payload/topology): `9fadf809b3b081b2 / 307b09c297623cf2 / 2fe406d2bd1229d2 / 7728405d1bf07a61`. SurfaceWorld: `ace56c8f205238ad / a9c603a1248de6b8 / ea55f1f4fcc6a894 / 5ea7bc78a1b678ae`. Exact probe hashes matched the worker matrix. The r54 full-range hashed crossing also passed for FI and SurfaceWorld on both compilers (96 voxels, 314 tiles): FI `f9e89a48116c45ff / a6c8f20efcfb460f / f4df697779b2bf00 / e378f82fedc1a822`; SurfaceWorld `3561ea23485e359f / e8331620fb0fb908 / 765f7dad67c852aa / 3ccc09ac81c05d71`.
SurfaceWorld away from the passage remained bit-identical to L23 on both compilers in the final-source LOD0–1 bounded comparison: 960 full-detail tiles, hashes `66ac781666579e3e / 914873894a0e38c4 / ec8b03ade039cd56 / a2b621b0321d43dc`, matching the r54/L23 baseline exactly. The r54 full whole-view hashes were `ddc6d1942db48f52 / bce985905e70dac4 / 266f5a008bcf4491 / e6fa520c5ad2817b`. Final-source r55 SurfaceWorld L9 proofs on both compilers checked 25,720 blocks / 34,233,320 samples (1,304 expected fallbacks, 0 unknown, 0 violations). Final-source r55 FI proof runs on both compilers had 2,560 expected fallbacks/unknowns, 0 checked samples and 0 violations; the boundary audit checked 27 endpoints with 0 disagreements. Final-source L13 route parity passed on both compilers: 8 page pairs, 14 higher-LOD exact pairs, 782,026 exact-query samples, 0 mismatches, one edit pair, 64 expected unknown proof blocks, 0 violations.
**Final-source r55 cross-compiler reruns:** Clang build, FI passage audit, all four style audits, 120-tile worker hash matrix, 24 m crossings, L13 parity, L9 FI proof and boundary checks pass. GCC build passes; its 120-tile worker matrix, 24 m crossings, L9 FI proof and boundary checks pass. The r55 GCC FI capsule audit did not finish; the prior r54 GCC audit, style sweep, crossings, parity, proofs and full LOD0–8 hash matrix passed.
## Changes and versions
- Shared passage planning honours all four styles and their per-strate parameters; Worm is the public default. It adds a deterministic anchor-root record, FI helix path, bounded wall relief and the naturalness audit.
- The owner FI upper-strate config selects Spiral. Its stable anchor/root is limited to ordinal 2; other island placements are unchanged.
- Lower SW arrival support overlays were removed so the native terrain meets the cave mouth without stacked shelves.
- The Linux offscreen capture helper gained a camera headlamp and optional world-space clip plane for cutaway views.
- `WorldAssemblyEvaluatorVersion=10`; FI recipe geometry version `5`; resolved-layout snapshot remains V3.
Unreal-facing edits are limited to `Source/VoxelForge/Public/VoxelStrateTypes.h` (per-strate passage fields/default) and `Source/VoxelForge/Private/VoxelForgeCoreAdapter.cpp` (forward those fields to Core). The remaining changes are shared standalone Core, audit/capture support, owner JSON and docs: `VoxelForgeCore.h`, `FloatingIslandsInternal.h`, `ResolvedLayoutInternal.h`, `ShapeWorldInternal.h`, `StreamBenchmarkPipeline.h`, `WorldAssemblyPrototype.h`, `LinuxOffscreenCapture.cpp`, and `Standalone/data/owner_world.json`. Documentation is in `ARCHITECTURE.md` §8.42 and `CODEMAP.md` §3.25. Unreal changes are source-only here and were not compiled.
## Windows checklist
1. Regenerate project files and build `VoxelForgeEditor Win64 Development` with the project toolchain.
2. Confirm the FI upper-strate passage style is Spiral and the other unmodified strata use Worm; regenerate the resolved layout after changing strate passage settings.
3. In PIE, walk from the anchor island down the root and through the SurfaceWorld arrival; check capsule clearance, support, collision and mouth transitions.
4. Confirm the other FI islands still float, then repeat with the same seed on a second client/editor process and compare placement and passage shape.
5. Change one strate to Straight, Worm, Spiral and Cascading in turn; regenerate and verify only that strate's passage style changes.
## Failed and retried runs
- Early route calibration r32–r34 found 3–4 blocked capsule samples; r35–r42 radius/bore adjustments alternated blocked and unsupported samples. r39 also failed strict validation because a mouth exceeded the placement radius.
- r43 added diagnostics. r44 corrected XY projection. r45's 0.25 m lift produced 1,124 blocked samples and 4 unsupported; r46's 0.20 m lift left 4 unsupported; r47's 0.25 m lift produced 1,042 blocked; r48's relaxed support rule produced 5,660 blocked.
- r49 build failed on an undeclared `DeterministicSqrt`; r50 corrected the name but still had 5,609 blocked; r51 narrowed support and reached zero blocked/unsupported. r52 removed the fixture's FI style override and restored the L23 geometry comparison.
- r53's 0.16 m relief failed the valid-wall-sample threshold for some styles. r54 increased relief to 0.24 m and set the minimum to 8 samples; all four styles passed. r55 removed lower-mouth support shelves; Clang FI and style audits still pass.
- GCC r55 style sweep was interrupted after its Straight case emitted capsule and naturalness PASS results, before a complete style summary. A separate GCC r55 FI capsule-audit retry remained silent and was stopped after roughly 8 minutes. GCC r54 audits passed.
- Three unrestricted r55 stream-hash attempts (FI W1, FI W12, and SurfaceWorld W12) stopped after shape compilation with no pipeline summary. Limiting the final-source matrix to LOD0–2 completed 120 full-detail plus 56 LOD2 tiles and passed across both compilers and worker counts. A `max-clip-level=1` trial was rejected by Core's bounded 4,096-node shape compiler envelope; retrying with the supported clip limit and `max-level=1` passed.
- An LOD0–3 FI proof invocation remained silent after shape compilation; the LOD0–1 FI proof retry and the 960-tile SurfaceWorld proof completed on both compilers with zero violations. Camera trials replaced a horizontal SW view that showed flat bands with the downward arrival view; a closer oblique trial also exposed stair-like bands and was discarded. Low-FOV interior trials showed only a close wall, so the final interior view uses a 150-degree camera and headlamp.
- Two initial r55 capture exports at `max-level=1` wrote empty 4,380-byte mesh scenes; the renderer rejected them for containing no triangles. An unrestricted `max-level=3` capture export reached 593,068 desired tiles, grew to an incomplete 1.7 GB mesh and was stopped. Bounded exports without an explicit camera used the profile viewer start away from the anchor; repeating them at `(9.8, 4.6, -85) m` produced the intended 195-tile views. A three-value `--camera` argument was rejected (exit 2) and corrected to the required five-value form. An early bounded export with the wrong camera and coarse mesh was discarded. Initial Mesa cache writes targeted the read-only home cache and were disabled; subsequent renders used `Saved/Linux/mesa-shader-cache`. No system changes were made.
- One initial headless invocation omitted required flags (exit 2), and one GCC binary name typo returned 127; both were corrected. The offscreen capture helper was rebuilt after adding clip-plane cutaways and brighter headlamp shading.
No commit, push or stash was made. No Unreal build was available on this machine.
## Orchestrator review (Claude)
- **Re-run by me, full view (LOD0–8, 2,370 tiles), Clang W1/W8/W12 + GCC W12:** identical whole-view hashes
(SW `c817c4c84eb82e11/53e2e3b2358d2cb1/2c4f1724df03c3da/61a51ac3091f9e8f`, FI
`ea50fd77bea1fc9f/b4344b2b80a63eb3/8839f2e0fd20290b/9c98918b7ca4e2e8`); SW 1.44 s, FI 15.3 s whole view.
The "unrestricted r55 runs stopped after shape compilation" were command-line issues, not a code hang.
- Merged for: per-strate passage styles honoured in Core, Worm as the natural default, the naturalness
check with an L23 negative control, and the removed SW lower shelves.
- **Not as the owner asked (my capture review):** in `straight-vs-worm.jpg` the FI helix appears as a
jagged spiral **ribbon hanging in open air around the pillar** (wider than the pillar, and continuing
below the floor), not a tunnel enclosed inside the rock root. `sw-arrival-mouth.jpg` and
`fi-helix-inside.jpg` are too close or blurry to judge. Next round: the helix enclosed in rock, no
tread or support geometry in open air, readable wide captures.
- Unreal edits (`VoxelStrateTypes.h` passage fields/default, CoreAdapter) uncompiled here.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

+12 -236
View File
@@ -16,7 +16,6 @@
#include <limits>
#include <string>
#include <string_view>
#include <unordered_set>
#include <vector>
namespace
@@ -26,8 +25,6 @@ namespace
float Position[3];
float Normal[3];
float Height;
float WorldPosition[3];
float TileData[4];
};
struct FScene
@@ -35,73 +32,12 @@ namespace
std::uint32_t VoxelSizeMicrons=0;
std::array<double,3> CameraMeters{};
double YawDegrees=0.0,PitchDegrees=0.0;
float MinimumHeight=std::numeric_limits<float>::infinity();
float MaximumHeight=-std::numeric_limits<float>::infinity();
std::vector<FVertex> Vertices;
std::vector<std::uint32_t> Indices;
struct FTileRange
{
std::array<std::int32_t,4> Key{};
std::size_t IndexBegin=0;
std::uint32_t IndexCount=0;
std::vector<std::uint8_t> FaceMasks;
};
std::vector<FTileRange> Tiles;
std::uint64_t Triangles=0,SkirtTriangles=0;
std::uint64_t VisibleSkirtTriangles=0,HiddenSameLodSkirtTriangles=0;
std::uint64_t DrawnTriangles=0;
std::uint32_t TileCount=0;
};
struct FTileKeyHash
{
std::size_t operator()(const std::array<std::int32_t,4>& Key) const noexcept
{
std::size_t Hash=0xcbf29ce484222325ull;
for(const std::int32_t Value:Key)
{
Hash^=static_cast<std::uint32_t>(Value);
Hash*=0x100000001b3ull;
}
return Hash;
}
};
std::int32_t FloorDiv(std::int64_t Value,std::int64_t Divisor)
{
const std::int64_t Quotient=Value/Divisor, Remainder=Value%Divisor;
return static_cast<std::int32_t>(Quotient-((Remainder<0)?1:0));
}
std::uint8_t ComputeVisibleSkirtFaceMask(
const std::array<std::int32_t,4>& Tile,
const std::unordered_set<std::array<std::int32_t,4>,FTileKeyHash>& Desired)
{
const std::int64_t Extent=static_cast<std::int64_t>(32)<<Tile[3];
const std::int64_t Origin[3]={static_cast<std::int64_t>(Tile[0])*Extent,
static_cast<std::int64_t>(Tile[1])*Extent,static_cast<std::int64_t>(Tile[2])*Extent};
std::uint8_t Mask=0;
for(std::int32_t Axis=0;Axis<3;++Axis)for(std::int32_t Side=0;Side<2;++Side)
{
std::int64_t Probe[3]={Origin[0]+Extent/2,Origin[1]+Extent/2,
Origin[2]+Extent/2};
Probe[Axis]=Side?Origin[Axis]+Extent:Origin[Axis]-1;
std::int32_t NeighborLevel=-1;
for(std::int32_t Level=0;Level<=8;++Level)
{
const std::int64_t NeighborExtent=static_cast<std::int64_t>(32)<<Level;
const std::array<std::int32_t,4> Neighbor={
FloorDiv(Probe[0],NeighborExtent),FloorDiv(Probe[1],NeighborExtent),
FloorDiv(Probe[2],NeighborExtent),Level};
if(Desired.contains(Neighbor))
{NeighborLevel=Level;break;}
}
if(NeighborLevel<0||NeighborLevel!=Tile[3])
Mask|=static_cast<std::uint8_t>(1u<<(Axis*2+Side));
}
return Mask;
}
template<typename T> bool Read(std::ifstream& File,T& Value)
{
File.read(reinterpret_cast<char*>(&Value),sizeof(Value));
@@ -134,8 +70,7 @@ namespace
if(!Read(File,SurfaceVertices)||!Read(File,SkirtCount)||!Read(File,VertexCount)
||!Read(File,IndexCount)||!Read(File,MaskCount)
||VertexCount>10000000||IndexCount>60000000||MaskCount>20000000
||IndexCount%3!=0||(MaskCount!=0&&MaskCount!=IndexCount/3)
||Key[3]<0||Key[3]>8)
||IndexCount%3!=0||(MaskCount!=0&&MaskCount!=IndexCount/3))
{Error="tile mesh header is malformed";return false;}
if(TotalVertices+VertexCount>std::numeric_limits<std::uint32_t>::max()
||TotalIndices+IndexCount>std::numeric_limits<std::size_t>::max())
@@ -151,25 +86,6 @@ namespace
for(float& Value:Scene.Vertices[I].Normal)if(!Read(File,Value))
{Error="tile normals are truncated";return false;}
Scene.Vertices[I].Height=Scene.Vertices[I].Position[2];
Scene.MinimumHeight=std::min(Scene.MinimumHeight,Scene.Vertices[I].Height);
Scene.MaximumHeight=std::max(Scene.MaximumHeight,Scene.Vertices[I].Height);
}
const double TileVoxels=static_cast<double>(32u<<Key[3]);
const float TileExtentMeters=static_cast<float>(TileVoxels
*static_cast<double>(Scene.VoxelSizeMicrons)/1000000.0);
const float TileOriginX=static_cast<float>(static_cast<double>(Key[0])
*TileExtentMeters);
const float TileOriginY=static_cast<float>(static_cast<double>(Key[1])
*TileExtentMeters);
for(std::size_t I=Base;I<Base+VertexCount;++I)
{
FVertex& Vertex=Scene.Vertices[I];
std::copy(std::begin(Vertex.Position),std::end(Vertex.Position),
std::begin(Vertex.WorldPosition));
Vertex.TileData[0]=TileOriginX;
Vertex.TileData[1]=TileOriginY;
Vertex.TileData[2]=TileExtentMeters;
Vertex.TileData[3]=static_cast<float>(Key[3]);
}
const std::size_t IndexOffset=Scene.Indices.size();
Scene.Indices.resize(IndexOffset+IndexCount);
@@ -186,36 +102,11 @@ namespace
}
Scene.Triangles+=IndexCount/3;
Scene.SkirtTriangles+=SkirtCount;
Scene.Tiles.push_back({{Key[0],Key[1],Key[2],Key[3]},IndexOffset,
IndexCount,std::move(Masks)});
TotalVertices+=VertexCount;TotalIndices+=IndexCount;
}
if(File.peek()!=std::char_traits<char>::eof())
{Error="mesh scene has trailing bytes";return false;}
if(Scene.Indices.empty()){Error="mesh scene contains no triangles";return false;}
std::unordered_set<std::array<std::int32_t,4>,FTileKeyHash> Desired;
Desired.reserve(Scene.Tiles.size());
for(const auto& Tile:Scene.Tiles)Desired.insert(Tile.Key);
std::vector<std::uint32_t> VisibleIndices;
VisibleIndices.reserve(Scene.Indices.size());
for(const auto& Tile:Scene.Tiles)
{
const std::uint8_t VisibleMask=ComputeVisibleSkirtFaceMask(Tile.Key,Desired);
for(std::uint32_t Triangle=0;Triangle<Tile.IndexCount/3;++Triangle)
{
const std::size_t MaskIndex=Triangle;
const std::uint8_t FaceMask=MaskIndex<Tile.FaceMasks.size()
?Tile.FaceMasks[MaskIndex]:0;
if(FaceMask!=0&&(FaceMask&VisibleMask)==0)
{++Scene.HiddenSameLodSkirtTriangles;continue;}
if(FaceMask!=0)++Scene.VisibleSkirtTriangles;
const std::size_t Index=Tile.IndexBegin+static_cast<std::size_t>(Triangle)*3;
VisibleIndices.insert(VisibleIndices.end(),Scene.Indices.begin()+Index,
Scene.Indices.begin()+Index+3);
}
}
Scene.Indices=std::move(VisibleIndices);
Scene.DrawnTriangles=Scene.Indices.size()/3;
return true;
}
@@ -260,12 +151,8 @@ precision highp float;
layout(location=0) in vec3 inCameraPosition;
layout(location=1) in vec3 inNormal;
layout(location=2) in float inHeight;
layout(location=3) in vec3 inWorldPosition;
layout(location=4) in vec4 inTileData;
out vec3 vNormal;
out float vHeight;
out vec3 vWorldPosition;
out vec4 vTileData;
uniform float uTanHalfHorizontal;
uniform float uTanHalfVertical;
uniform float uNear;
@@ -278,58 +165,19 @@ void main()
inCameraPosition.y/uTanHalfVertical,clipZ,z);
vNormal=normalize(inNormal);
vHeight=inHeight;
vWorldPosition=inWorldPosition;
vTileData=inTileData;
})GLSL";
static constexpr char FragmentSource[]=R"GLSL(#version 300 es
precision highp float;
in vec3 vNormal;
in float vHeight;
in vec3 vWorldPosition;
in vec4 vTileData;
out vec4 outColor;
uniform int uReadableMode;
uniform int uTileEdges;
uniform float uHeightCenter;
uniform float uHeightRange;
uniform float uTileEdgeWidth;
uniform vec3 uLightDirection;
uniform int uHeadlamp;
uniform int uClipEnabled;
uniform vec4 uClipPlane;
void main()
{
if(uClipEnabled!=0&&dot(vec4(vWorldPosition,1.0),uClipPlane)<0.0)discard;
vec3 n=normalize(vNormal);
vec3 color;
if(uReadableMode==0)
{
vec3 normalColor=abs(n)*0.78+vec3(0.12);
float band=mod(floor((vHeight+10000.0)/80.0),2.0);
vec3 bandColor=mix(vec3(0.24,0.31,0.37),vec3(0.39,0.42,0.35),band);
color=mix(bandColor,normalColor,0.68);
}
else
{
float heightT=clamp(0.5+(vHeight-uHeightCenter)/max(uHeightRange,0.001),0.0,1.0);
vec3 heightTint=mix(vec3(0.80,0.91,1.0),vec3(1.0,0.91,0.77),heightT);
float diffuse=max(dot(n,normalize(uLightDirection)),0.0);
float illumination=uHeadlamp!=0?0.78+0.34*diffuse:0.62+0.38*diffuse;
color=vec3(0.64,0.62,0.56)*heightTint*illumination;
}
if(uTileEdges!=0&&vTileData.z>0.0)
{
vec2 local=mod(vWorldPosition.xy-vTileData.xy,vTileData.z);
vec2 edge=min(local,vec2(vTileData.z)-local);
float distanceToTileEdge=min(edge.x,edge.y);
float antialias=max(fwidth(distanceToTileEdge),0.005);
float line=1.0-smoothstep(uTileEdgeWidth-antialias,
uTileEdgeWidth+antialias,distanceToTileEdge);
vec3 edgeColor=mix(vec3(0.16,0.22,0.25),vec3(0.30,0.23,0.14),
clamp(vTileData.w/8.0,0.0,1.0));
color=mix(color,edgeColor,0.32*line);
}
outColor=vec4(color,1.0);
vec3 normalColor=abs(n)*0.78+vec3(0.12);
float band=mod(floor((vHeight+10000.0)/80.0),2.0);
vec3 bandColor=mix(vec3(0.24,0.31,0.37),vec3(0.39,0.42,0.35),band);
outColor=vec4(mix(bandColor,normalColor,0.68),1.0);
})GLSL";
const GLuint VS=CompileShader(GL_VERTEX_SHADER,VertexSource);
const GLuint FS=CompileShader(GL_FRAGMENT_SHADER,FragmentSource);
@@ -376,9 +224,7 @@ void main()
}
bool Render(FScene& Scene,const std::filesystem::path& Output,int Width,int Height,
double HorizontalFovDegrees,bool ReadableMode,bool Headlamp,bool TileEdges,
double TileEdgeWidthMeters,bool ClipPlaneEnabled,
const std::array<double,4>& ClipPlane)
double HorizontalFovDegrees)
{
EGLDisplay Display=MakeDisplay();
EGLint Major=0,Minor=0;
@@ -458,10 +304,6 @@ void main()
reinterpret_cast<void*>(offsetof(FVertex,Normal)));
glEnableVertexAttribArray(2);glVertexAttribPointer(2,1,GL_FLOAT,GL_FALSE,sizeof(FVertex),
reinterpret_cast<void*>(offsetof(FVertex,Height)));
glEnableVertexAttribArray(3);glVertexAttribPointer(3,3,GL_FLOAT,GL_FALSE,sizeof(FVertex),
reinterpret_cast<void*>(offsetof(FVertex,WorldPosition)));
glEnableVertexAttribArray(4);glVertexAttribPointer(4,4,GL_FLOAT,GL_FALSE,sizeof(FVertex),
reinterpret_cast<void*>(offsetof(FVertex,TileData)));
glViewport(0,0,Width,Height);glDisable(GL_CULL_FACE);glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);glClearColor(0.035f,0.055f,0.075f,1.0f);
glClearDepthf(1.0f);glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
@@ -470,22 +312,6 @@ void main()
glUniform1f(glGetUniformLocation(Program,"uTanHalfVertical"),static_cast<float>(TanHalfVertical));
glUniform1f(glGetUniformLocation(Program,"uNear"),static_cast<float>(Near));
glUniform1f(glGetUniformLocation(Program,"uFar"),static_cast<float>(Far));
glUniform1i(glGetUniformLocation(Program,"uReadableMode"),ReadableMode?1:0);
glUniform1i(glGetUniformLocation(Program,"uTileEdges"),TileEdges?1:0);
glUniform1f(glGetUniformLocation(Program,"uHeightCenter"),
static_cast<float>(Scene.CameraMeters[2]));
glUniform1f(glGetUniformLocation(Program,"uHeightRange"),64.0f);
glUniform1f(glGetUniformLocation(Program,"uTileEdgeWidth"),
static_cast<float>(TileEdgeWidthMeters));
glUniform1i(glGetUniformLocation(Program,"uClipEnabled"),ClipPlaneEnabled?1:0);
glUniform1i(glGetUniformLocation(Program,"uHeadlamp"),Headlamp?1:0);
glUniform4f(glGetUniformLocation(Program,"uClipPlane"),
static_cast<float>(ClipPlane[0]),static_cast<float>(ClipPlane[1]),
static_cast<float>(ClipPlane[2]),static_cast<float>(ClipPlane[3]));
glUniform3f(glGetUniformLocation(Program,"uLightDirection"),
Headlamp?static_cast<float>(-Forward[0]):-0.42f,
Headlamp?static_cast<float>(-Forward[1]):-0.58f,
Headlamp?static_cast<float>(-Forward[2]):0.70f);
glDrawElements(GL_TRIANGLES,static_cast<GLsizei>(Scene.Indices.size()),GL_UNSIGNED_INT,nullptr);
glFinish();
std::vector<std::uint8_t> Pixels(static_cast<std::size_t>(Width)*Height*4);
@@ -497,15 +323,9 @@ void main()
{
std::error_code SizeError;
const auto Bytes=std::filesystem::file_size(Output,SizeError);
std::printf("[OffscreenCapture] source_triangles=%llu drawn_triangles=%llu tiles=%u "
"skirts=%llu visible_skirt_triangles=%llu hidden_same_lod_skirt_triangles=%llu "
"shading=%s tile_edges=%s edge_width_m=%.3f png_bytes=%llu status=PASS path=%s\n",
static_cast<unsigned long long>(Scene.Triangles),
static_cast<unsigned long long>(Scene.DrawnTriangles),Scene.TileCount,
std::printf("[OffscreenCapture] triangles=%llu tiles=%u skirts=%llu png_bytes=%llu status=PASS path=%s\n",
static_cast<unsigned long long>(Scene.Triangles),Scene.TileCount,
static_cast<unsigned long long>(Scene.SkirtTriangles),
static_cast<unsigned long long>(Scene.VisibleSkirtTriangles),
static_cast<unsigned long long>(Scene.HiddenSameLodSkirtTriangles),
ReadableMode?"readable":"normal",TileEdges?"on":"off",TileEdgeWidthMeters,
static_cast<unsigned long long>(SizeError?0:Bytes),Output.string().c_str());
}
glDeleteProgram(Program);glDeleteBuffers(1,&Ebo);glDeleteBuffers(1,&Vbo);
@@ -521,14 +341,12 @@ int main(int argc,char** argv)
{
if(argc<3)
{
std::fprintf(stderr,"Usage: %s scene.vfmesh output.png [--size=WIDTHxHEIGHT] [--fov-deg=90] [--camera-m=X,Y,Z] [--yaw-deg=N] [--pitch-deg=N] [--shade=readable|normal] [--headlamp=on|off] [--tile-edges=on|off] [--tile-edge-width-m=N] [--clip-plane=NX,NY,NZ,D]\n",argv[0]);
std::fprintf(stderr,"Usage: %s scene.vfmesh output.png [--size=WIDTHxHEIGHT] [--fov-deg=90] [--camera-m=X,Y,Z] [--yaw-deg=N] [--pitch-deg=N]\n",argv[0]);
return 2;
}
int Width=2560,Height=1440;double Fov=90.0;
bool HasYaw=false,HasPitch=false;double Yaw=0.0,Pitch=0.0;
bool HasCamera=false;std::array<double,3> Camera{};
bool ReadableMode=true,TileEdges=false,Headlamp=false;double TileEdgeWidthMeters=0.15;
bool ClipPlaneEnabled=false;std::array<double,4> ClipPlane{};
for(int I=3;I<argc;++I)
{
const std::string_view Arg(argv[I]);
@@ -562,46 +380,6 @@ int main(int argc,char** argv)
{std::fprintf(stderr,"Invalid camera angle\n");return 2;}
if(IsYaw){Yaw=Parsed;HasYaw=true;}else{Pitch=Parsed;HasPitch=true;}
}
else if(Arg.starts_with("--shade="))
{
const std::string_view Mode=Arg.substr(8);
if(Mode=="readable")ReadableMode=true;
else if(Mode=="normal")ReadableMode=false;
else {std::fprintf(stderr,"Invalid shading mode\n");return 2;}
}
else if(Arg.starts_with("--headlamp="))
{
const std::string_view Mode=Arg.substr(11);
if(Mode=="on")Headlamp=true;
else if(Mode=="off")Headlamp=false;
else {std::fprintf(stderr,"Invalid headlamp mode\n");return 2;}
}
else if(Arg.starts_with("--tile-edges="))
{
const std::string_view Mode=Arg.substr(13);
if(Mode=="on")TileEdges=true;
else if(Mode=="off")TileEdges=false;
else {std::fprintf(stderr,"Invalid tile-edge mode\n");return 2;}
}
else if(Arg.starts_with("--tile-edge-width-m="))
{
char* End=nullptr;const std::string Value(Arg.substr(20));
TileEdgeWidthMeters=std::strtod(Value.c_str(),&End);
if(End==Value.c_str()||*End!='\0'||!std::isfinite(TileEdgeWidthMeters)
||TileEdgeWidthMeters<=0.0||TileEdgeWidthMeters>5.0)
{std::fprintf(stderr,"Invalid tile-edge width\n");return 2;}
}
else if(Arg.starts_with("--clip-plane="))
{
const std::string Value(Arg.substr(13));
if(std::sscanf(Value.c_str(),"%lf,%lf,%lf,%lf",&ClipPlane[0],&ClipPlane[1],
&ClipPlane[2],&ClipPlane[3])!=4
||!std::isfinite(ClipPlane[0])||!std::isfinite(ClipPlane[1])
||!std::isfinite(ClipPlane[2])||!std::isfinite(ClipPlane[3])
||std::hypot(ClipPlane[0],ClipPlane[1],ClipPlane[2])<=0.0)
{std::fprintf(stderr,"Invalid clip plane; use NX,NY,NZ,D with a non-zero normal\n");return 2;}
ClipPlaneEnabled=true;
}
else {std::fprintf(stderr,"Unknown option: %.*s\n",static_cast<int>(Arg.size()),Arg.data());return 2;}
}
FScene Scene;std::string Error;
@@ -610,12 +388,10 @@ int main(int argc,char** argv)
if(HasCamera)Scene.CameraMeters=Camera;
if(HasYaw)Scene.YawDegrees=Yaw;
if(HasPitch)Scene.PitchDegrees=Pitch;
std::printf("[OffscreenScene] voxels_per_meter=%.6f camera_m=(%.3f,%.3f,%.3f) yaw=%.2f pitch=%.2f height_m=%.3f..%.3f shade=%s tile_edges=%s vertices=%zu triangles=%llu\n",
std::printf("[OffscreenScene] voxels_per_meter=%.6f camera_m=(%.3f,%.3f,%.3f) yaw=%.2f pitch=%.2f vertices=%zu triangles=%llu\n",
1000000.0/Scene.VoxelSizeMicrons,Scene.CameraMeters[0],Scene.CameraMeters[1],Scene.CameraMeters[2],
Scene.YawDegrees,Scene.PitchDegrees,Scene.MinimumHeight,Scene.MaximumHeight,
ReadableMode?"readable":"normal",TileEdges?"on":"off",Scene.Vertices.size(),
Scene.YawDegrees,Scene.PitchDegrees,Scene.Vertices.size(),
static_cast<unsigned long long>(Scene.Triangles));
return Render(Scene,argv[2],Width,Height,Fov,ReadableMode,Headlamp,TileEdges,
TileEdgeWidthMeters,ClipPlaneEnabled,ClipPlane)?0:3;
return Render(Scene,argv[2],Width,Height,Fov)?0:3;
}
-18
View File
@@ -43,8 +43,6 @@ struct FStandaloneOwnerWorld
int32 LODOctaveDrop = 0;
std::uint32_t OwnerVoxelSizeMicrons = 125000;
std::uint32_t CoreVoxelSizeMicrons = 250000;
std::uint32_t StrateLayoutChunkSizeMicrometres = 8000000;
std::int64_t StrateLayoutChunkWidthSubvoxels = 8192;
};
namespace StandaloneOwnerLoader
@@ -380,21 +378,6 @@ namespace StandaloneOwnerLoader
ReadField(Root,"strate_content_cut_min_level",Out.Settings->StrateContentCutMinLevel);
ReadField(SettingsJson,"TotalStrates",Out.Settings->TotalStrates);
ReadField(SettingsJson,"InterStrateGapChunks",Out.Settings->InterStrateGapChunks);
ReadField(SettingsJson,"StrateLayoutChunkSizeMeters",Out.Settings->StrateLayoutChunkSizeMeters);
const VFJson::Value& LayoutChunkMicrometres=Root.Get("strate_layout_chunk_size_um");
const double LayoutChunkSizeMicrometres=LayoutChunkMicrometres.IsNumber()
?LayoutChunkMicrometres.Number()
:static_cast<double>(Out.Settings->StrateLayoutChunkSizeMeters)*1000000.0;
if(!std::isfinite(LayoutChunkSizeMicrometres)||LayoutChunkSizeMicrometres<250000.0
||LayoutChunkSizeMicrometres>64000000.0
||std::abs(LayoutChunkSizeMicrometres-std::round(LayoutChunkSizeMicrometres))>0.001)
{Error="strate layout chunk size must be an integral micrometre value between 0.25 m and 64 m";return false;}
Out.StrateLayoutChunkSizeMicrometres=static_cast<std::uint32_t>(std::llround(LayoutChunkSizeMicrometres));
Out.Settings->StrateLayoutChunkSizeMeters=static_cast<float>(LayoutChunkSizeMicrometres/1000000.0);
Out.StrateLayoutChunkWidthSubvoxels=static_cast<std::int64_t>(std::llround(
LayoutChunkSizeMicrometres*256.0/CoreMicrons));
if(Out.StrateLayoutChunkWidthSubvoxels<=0)
{Error="strate layout chunk size resolves to no Core subvoxels";return false;}
Out.Settings->StratePool.Reset();
Out.Settings->FixedStrates.Empty();
const auto& Strates = Root.Get("strates").AsArray();
@@ -415,7 +398,6 @@ namespace StandaloneOwnerLoader
Error = "copied strate manager rejected the owner settings snapshot";
return false;
}
Out.Manager->SetHardTransitionFallbackForAssembly(true);
Out.Generator = std::make_unique<UVoxelGenerator>();
Out.Generator->InitializeSettings(Out.Settings.get());
Out.Generator->SetStrateManager(Out.Manager.get());
+38 -198
View File
@@ -17,7 +17,6 @@
#include <iostream>
#include <iterator>
#include <limits>
#include <map>
#include <memory>
#include <string>
#include <string_view>
@@ -36,6 +35,7 @@ namespace
bool StreamBenchmark=false;
bool StreamPipeline=false;
bool StreamHash=false;
bool TileCachePrototype=false;
bool ProfileColumnOverlap=false;
bool UseSharedColumnCache=true;
bool ForceGenerate=false;
@@ -64,11 +64,6 @@ namespace
float CameraYawDegrees=0.0f;
float CameraPitchDegrees=0.0f;
std::filesystem::path MeshExportPath;
std::filesystem::path ResolvedLayoutOutputPath;
bool ResolvedLayoutOnly=false;
bool AuditResolvedLayoutBoundaries=false;
bool AuditResolvedLayoutPassages=false;
bool AuditSurfaceClearance=false;
};
bool ParseInteger(std::string_view text,int& output)
@@ -123,13 +118,9 @@ namespace
" --mesh-export=FILE (write the exact generated tile meshes for offline rendering)\n"
" --profile-column-overlap --far-horizon-lod8-step=N --force-generate\n"
" --seed=N --recipe=surface-world|floating-islands\n"
" --resolved-layout-output=FILE (canonical plan-time layout snapshot)\n"
" --resolved-layout-only (exit after plan and snapshot validation)\n"
" --audit-resolved-layout-boundaries (query Core at each recorded endpoint)\n"
" --audit-resolved-layout-passages (capsule, support, route-binding and blocked-control audit)\n"
" --audit-surface-clearance (sample biome terrain/caps against the resolved ceiling)\n"
" --auto-surface-camera (place the 27-tile cube on this seed's surface)\n"
" --mesh-coverage (report non-empty tiles and indexed triangles)\n"
" --tile-cache-prototype (opt-in exact disk-cache round trip; writes Saved/Linux/cache/l16-prototype)\n"
" --screen-space-gate (measure display error and historical negative controls)\n"
" --audit-uniform-block-proofs (fill and check every interval-certified block)\n"
" --profile-lod-work (report per-LOD density sample counts)\n"
@@ -145,13 +136,18 @@ namespace
return false;
}
if(arg=="--world-assembler-prototype")options.WorldAssemblerPrototype=true;
else if(arg=="--resolved-layout-only")options.ResolvedLayoutOnly=true;
else if(arg=="--audit-resolved-layout-boundaries")options.AuditResolvedLayoutBoundaries=true;
else if(arg=="--audit-resolved-layout-passages")options.AuditResolvedLayoutPassages=true;
else if(arg=="--audit-surface-clearance")options.AuditSurfaceClearance=true;
else if(arg=="--stream-benchmark")options.StreamBenchmark=true;
else if(arg=="--stream-pipeline")options.StreamPipeline=true;
else if(arg=="--stream-hash")options.StreamHash=true;
else if(arg=="--tile-cache-prototype")
{
options.TileCachePrototype=true;
options.StreamPipeline=true;
options.StreamBenchmark=true;
options.WorldAssemblerPrototype=true;
options.ForceGenerate=true;
options.StreamHash=true;
}
else if(arg=="--profile-column-overlap")options.ProfileColumnOverlap=true;
else if(arg=="--force-generate")options.ForceGenerate=true;
else if(arg=="--mesh-coverage")options.MeshCoverage=true;
@@ -170,8 +166,6 @@ namespace
else if(recipe=="floating-islands")options.FloatingIslandsRecipe=true;
else {std::fprintf(stderr,"Invalid --recipe value: %.*s\n",static_cast<int>(recipe.size()),recipe.data());return false;}
}
else if(arg.starts_with("--resolved-layout-output="))
options.ResolvedLayoutOutputPath=std::string(arg.substr(std::string_view("--resolved-layout-output=").size()));
else if(arg.starts_with("--seed="))
{if(!readInt("--seed=",options.SeedOverride))return false;options.HasSeedOverride=true;}
else if(arg.starts_with("--render-distance-chunks="))
@@ -320,11 +314,7 @@ int main(int argc,char** argv)
FVector cameraVoxels=ownerWorld->ViewerStartVoxels;
if(options.HasCamera)
{
const float VoxelsPerMetre=1000000.0f/std::max<std::uint32_t>(1,ownerWorld->CoreVoxelSizeMicrons);
cameraVoxels=FVector(options.CameraMeters.X*VoxelsPerMetre,
options.CameraMeters.Y*VoxelsPerMetre,options.CameraMeters.Z*VoxelsPerMetre);
}
cameraVoxels=FVector(options.CameraMeters.X*4.0f,options.CameraMeters.Y*4.0f,options.CameraMeters.Z*4.0f);
const auto planStart=Clock::now();
VoxelForgeCore::WorldAssemblyManifest worldAssembly;
@@ -335,165 +325,6 @@ int main(int argc,char** argv)
&&!StandaloneWorldAssemblyPrototype::AttachFloatingIslandWorldAssembly(
*ownerWorld,ownerJsonRoot,worldAssembly,error))
{std::fprintf(stderr,"Floating-island assembly setup failed: %s\n",error.c_str());return 2;}
VoxelForgeCore::ResolvedLayoutSnapshotV3 resolvedLayout;
{
const std::string_view variant=options.FloatingIslandsRecipe?"floating-islands":"surface-world";
if(!StandaloneWorldAssemblyPrototype::BuildResolvedLayoutSnapshot(
*ownerWorld,worldAssembly,variant,resolvedLayout,error))
{std::fprintf(stderr,"Resolved-layout snapshot failed: %s\n",error.c_str());return 2;}
const std::string layoutJson=resolvedLayout.ToJson();
const auto roundTrip=VoxelForgeCore::ResolvedLayoutSnapshotV3::FromJson(layoutJson,error);
if(!roundTrip||roundTrip->ToJson()!=layoutJson||roundTrip->stableIdentity!=resolvedLayout.stableIdentity)
{if(error.empty())error="resolved-layout canonical serialization did not round-trip";
std::fprintf(stderr,"Resolved-layout round trip failed: %s\n",error.c_str());return 2;}
if(!options.ResolvedLayoutOutputPath.empty())
{
if(!options.ResolvedLayoutOutputPath.parent_path().empty())
std::filesystem::create_directories(options.ResolvedLayoutOutputPath.parent_path());
std::ofstream output(options.ResolvedLayoutOutputPath,std::ios::binary);
if(!output){std::fprintf(stderr,"Could not write resolved-layout snapshot: %s\n",options.ResolvedLayoutOutputPath.c_str());return 2;}
output.write(layoutJson.data(),static_cast<std::streamsize>(layoutJson.size()));
if(!output){std::fprintf(stderr,"Resolved-layout snapshot write failed: %s\n",options.ResolvedLayoutOutputPath.c_str());return 2;}
}
const auto controls=VoxelForgeCore::AuditResolvedLayoutValidatorV3();
std::vector<VoxelForgeCore::ResolvedLayoutIssueV2> compatibilityIssues;
std::string compatibilityError;
const bool compatibilityAccepted=resolvedLayout.validate(
VoxelForgeCore::ResolvedLayoutValidationModeV3::compatibility,
compatibilityIssues,compatibilityError);
std::vector<VoxelForgeCore::ResolvedLayoutIssueV2> strictIssues;
std::string strictError;
const bool strictAccepted=resolvedLayout.validate(
VoxelForgeCore::ResolvedLayoutValidationModeV3::strict,strictIssues,strictError);
std::printf("[ResolvedLayoutSnapshot] schema=%u stable_identity=%s strata=%zu bytes=%zu round_trip=PASS\n",
resolvedLayout.schemaVersion,resolvedLayout.stableIdentity.c_str(),resolvedLayout.strates.size(),layoutJson.size());
std::printf("[ResolvedLayoutCompatibility] accepted=%s issues=%zu error=%s\n",
compatibilityAccepted?"true":"false",compatibilityIssues.size(),compatibilityError.c_str());
for(const auto& issue:compatibilityIssues)
std::printf("[ResolvedLayoutCompatibilityIssue] code=%s detail=%s\n",
issue.code.c_str(),issue.detail.c_str());
if(!compatibilityAccepted)
{std::fprintf(stderr,"Resolved-layout compatibility validation failed: %s\n",compatibilityError.c_str());return 2;}
std::printf("[ResolvedLayoutStrict] accepted=%s issues=%zu error=%s\n",
strictAccepted?"true":"false",strictIssues.size(),strictError.c_str());
for(const auto& issue:strictIssues)
std::printf("[ResolvedLayoutStrictIssue] code=%s detail=%s\n",issue.code.c_str(),issue.detail.c_str());
if(!strictAccepted)
{std::fprintf(stderr,"Resolved-layout strict validation failed: %s\n",strictError.c_str());return 2;}
std::printf("[ResolvedLayoutValidatorControls] rejected=%u/%u status=%s\n",
controls.controlsRejectedAsExpected,controls.controlsRun,controls.passed?"PASS":"FAIL");
if(!controls.passed)
{for(const auto& failure:controls.failures)std::printf("[ResolvedLayoutValidatorControlFailure] %s %s\n",failure.code.c_str(),failure.detail.c_str());return 2;}
if(!options.ResolvedLayoutOutputPath.empty())
std::printf("[ResolvedLayoutSnapshotOutput] path=%s\n",options.ResolvedLayoutOutputPath.c_str());
if(auto* root=std::get_if<VFJson::Value::Object>(&ownerJsonRoot.Data))
{VFJson::Value layoutText;layoutText.Data=layoutJson;(*root)["resolved_layout_json"]=std::move(layoutText);}
else
{std::fprintf(stderr,"Owner snapshot root cannot carry its resolved layout.\n");return 2;}
if(options.AuditSurfaceClearance)
{
if(options.FloatingIslandsRecipe)
{std::fprintf(stderr,"--audit-surface-clearance requires --recipe=surface-world\n");return 2;}
const auto surface=std::find_if(resolvedLayout.strates.begin(),resolvedLayout.strates.end(),
[](const auto& Stratum){return Stratum.generatorKind=="SurfaceWorld";});
const auto plan=surface==resolvedLayout.strates.end()?worldAssembly.plan.strates.end()
:std::find_if(worldAssembly.plan.strates.begin(),worldAssembly.plan.strates.end(),
[&](const auto& Stratum){return Stratum.strateIndex==surface->strateIndex;});
if(surface==resolvedLayout.strates.end()||plan==worldAssembly.plan.strates.end()
||!surface->ceiling.presentInCurrentField)
{std::fprintf(stderr,"SurfaceWorld clearance audit could not resolve its plan/ceiling\n");return 2;}
const VoxelForgeCore::Heightfield2D Field(worldAssembly.recipe,*plan);
if(!Field.isValid())
{std::fprintf(stderr,"SurfaceWorld clearance audit field is invalid\n");return 2;}
constexpr std::int64_t HalfExtentMetres=2048,StepMetres=1;
const double CoreMicrometres=std::max<std::uint32_t>(1,ownerWorld->CoreVoxelSizeMicrons);
const double MetresPerSubvoxel=CoreMicrometres
/(1000000.0*VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel);
double CenterX=0.0,CenterY=0.0;
if(!plan->route.empty())
{CenterX=plan->route.front().positionSubvoxels[0]*MetresPerSubvoxel;
CenterY=plan->route.front().positionSubvoxels[1]*MetresPerSubvoxel;}
const std::int64_t CenterXQ=static_cast<std::int64_t>(std::llround(
CenterX/MetresPerSubvoxel));
const std::int64_t CenterYQ=static_cast<std::int64_t>(std::llround(
CenterY/MetresPerSubvoxel));
const std::int64_t StepQ=static_cast<std::int64_t>(std::llround(
StepMetres/MetresPerSubvoxel));
struct FBiomeClearance
{
std::uint64_t Samples=0;
double MaximumGround=-std::numeric_limits<double>::infinity();
double MaximumCap=-std::numeric_limits<double>::infinity();
double MaximumSurface=-std::numeric_limits<double>::infinity();
double MinimumClearance=std::numeric_limits<double>::infinity();
double AtX=0.0,AtY=0.0,AtHeight=0.0;
std::int64_t MaximumCapQ=std::numeric_limits<std::int64_t>::min();
};
std::map<std::uint32_t,FBiomeClearance> ByBiome;
const double CeilingFace=static_cast<double>(surface->ceiling.bottomMicrometres)/1000000.0;
for(std::int64_t Y=-HalfExtentMetres;Y<=HalfExtentMetres;Y+=StepMetres)
for(std::int64_t X=-HalfExtentMetres;X<=HalfExtentMetres;X+=StepMetres)
{
const auto Sample=Field.point(CenterXQ+(X/StepMetres)*StepQ,
CenterYQ+(Y/StepMetres)*StepQ,0);
const double Ground=Sample.groundHeightSubvoxels*MetresPerSubvoxel;
const double Cap=Sample.capHeightSubvoxels*MetresPerSubvoxel;
const double SurfaceHeight=std::max(Ground,Cap);
auto& Stats=ByBiome[Sample.biomeId];
++Stats.Samples;
Stats.MaximumGround=std::max(Stats.MaximumGround,Ground);
Stats.MaximumCap=std::max(Stats.MaximumCap,Cap);
Stats.MaximumCapQ=std::max(Stats.MaximumCapQ,Sample.capHeightSubvoxels);
Stats.MaximumSurface=std::max(Stats.MaximumSurface,SurfaceHeight);
const double Clearance=CeilingFace-SurfaceHeight;
if(Clearance<Stats.MinimumClearance)
{Stats.MinimumClearance=Clearance;Stats.AtX=CenterX+X;Stats.AtY=CenterY+Y;
Stats.AtHeight=SurfaceHeight;}
}
double MaximumRouteZ=-std::numeric_limits<double>::infinity();
for(const auto& Point:plan->route)
MaximumRouteZ=std::max(MaximumRouteZ,Point.positionSubvoxels[2]*MetresPerSubvoxel);
const auto CapBounds=Field.capHeightBounds();
const auto RouteSample=plan->route.empty()?VoxelForgeCore::HeightfieldPointSample{}
:Field.point(plan->route.front().positionSubvoxels[0],
plan->route.front().positionSubvoxels[1],0);
std::printf("[SurfaceClearancePlan] has_recipe_override=%s layout_chunk_q=%lld plan_cap_q=%lld cap_bounds_q=(%lld,%lld)\n",
plan->hasRecipeOverride?"true":"false",
static_cast<long long>(worldAssembly.recipe.layoutChunkWidthSubvoxels),
static_cast<long long>(plan->capHeightSubvoxels),
static_cast<long long>(CapBounds[0]),static_cast<long long>(CapBounds[1]));
for(const auto& Profile:worldAssembly.recipe.biomes)
std::printf("[SurfaceClearanceProfile] biome_id=%u has_cap=%s cap_q=%lld undulation_q=%lld detail_q=%lld ridge_q=%lld\n",
Profile.stableId,Profile.hasCapProfile?"true":"false",
static_cast<long long>(Profile.capHeightSubvoxels),
static_cast<long long>(Profile.capUndulationSubvoxels),
static_cast<long long>(Profile.capDetailAmplitudeSubvoxels),
static_cast<long long>(Profile.capRidgeAmplitudeSubvoxels));
std::printf("[SurfaceClearanceAudit] box_m=4096x4096 step_m=%lld samples=%lld ceiling_inner_face_m=%.3f unmodified_field=true\n",
static_cast<long long>(StepMetres),
static_cast<long long>((2*HalfExtentMetres/StepMetres+1)*(2*HalfExtentMetres/StepMetres+1)),
CeilingFace);
std::printf("[SurfaceClearanceCapRange] plan_min_m=%.3f plan_max_m=%.3f spawn_cap_m=%.3f spawn_ground_m=%.3f\n",
CapBounds[0]*MetresPerSubvoxel,CapBounds[1]*MetresPerSubvoxel,
RouteSample.capHeightSubvoxels*MetresPerSubvoxel,
RouteSample.groundHeightSubvoxels*MetresPerSubvoxel);
for(const auto& Feature:plan->features)
std::printf("[SurfaceClearanceFeature] type=%u params_q=(%lld,%lld,%lld,%lld)\n",
Feature.type,static_cast<long long>(Feature.parametersSubvoxels[0]),
static_cast<long long>(Feature.parametersSubvoxels[1]),
static_cast<long long>(Feature.parametersSubvoxels[2]),
static_cast<long long>(Feature.parametersSubvoxels[3]));
for(const auto& [BiomeId,Stats]:ByBiome)
std::printf("[SurfaceClearanceBiome] biome_id=%u samples=%llu max_ground_m=%.3f max_cap_m=%.3f max_cap_q=%lld max_surface_m=%.3f min_clearance_m=%.3f at_m=(%.1f,%.1f,%.3f)\n",
BiomeId,static_cast<unsigned long long>(Stats.Samples),Stats.MaximumGround,
Stats.MaximumCap,static_cast<long long>(Stats.MaximumCapQ),Stats.MaximumSurface,Stats.MinimumClearance,
Stats.AtX,Stats.AtY,Stats.AtHeight);
std::printf("[SurfaceClearanceRoute] route_points=%zu max_route_z_m=%.3f clearance_m=%.3f status=%s\n",
plan->route.size(),MaximumRouteZ,CeilingFace-MaximumRouteZ,
MaximumRouteZ<CeilingFace?"PASS":"COLLISION");
}
if(options.ResolvedLayoutOnly)return 0;
}
if(options.AutoSurfaceCamera)
{
constexpr std::int64_t UnitsPerVoxel=VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel;
@@ -515,17 +346,25 @@ int main(int argc,char** argv)
}
else
{
if(worldAssembly.plan.strates.empty()||worldAssembly.plan.strates.front().route.empty())
{std::fprintf(stderr,"[SeedSurfacePlacement] FAIL: route-derived spawn is missing\n");return 2;}
const auto& spawn=worldAssembly.plan.strates.front().route.front();
cameraVoxels={static_cast<float>(static_cast<double>(spawn.positionSubvoxels[0])/UnitsPerVoxel),
static_cast<float>(static_cast<double>(spawn.positionSubvoxels[1])/UnitsPerVoxel),
static_cast<float>(static_cast<double>(spawn.positionSubvoxels[2])/UnitsPerVoxel)};
std::printf("[SeedSurfacePlacement] recipe=surface-world seed=%d source=route.front position_voxel=(%.6f,%.6f,%.6f) position_m=(%.3f,%.3f,%.3f) status=PASS\n",
seed,cameraVoxels.X,cameraVoxels.Y,cameraVoxels.Z,
cameraVoxels.X*ownerWorld->CoreVoxelSizeMicrons/1000000.0f,
cameraVoxels.Y*ownerWorld->CoreVoxelSizeMicrons/1000000.0f,
cameraVoxels.Z*ownerWorld->CoreVoxelSizeMicrons/1000000.0f);
const auto xSubvoxels=static_cast<std::int64_t>(std::llround(cameraVoxels.X*UnitsPerVoxel));
const auto ySubvoxels=static_cast<std::int64_t>(std::llround(cameraVoxels.Y*UnitsPerVoxel));
const auto currentZSubvoxels=static_cast<std::int64_t>(std::llround(cameraVoxels.Z*UnitsPerVoxel));
std::int64_t selectedGround=0,bestDistance=std::numeric_limits<std::int64_t>::max();
for(const auto& stratum:worldAssembly.plan.strates)
{
VoxelForgeCore::Heightfield2D field(worldAssembly.recipe,stratum);
if(!field.isValid())continue;
const auto column=field.point(xSubvoxels,ySubvoxels,0);
const std::int64_t distance=std::abs(column.groundHeightSubvoxels-currentZSubvoxels);
if(distance<bestDistance)
{bestDistance=distance;selectedGround=column.groundHeightSubvoxels;}
}
if(bestDistance==std::numeric_limits<std::int64_t>::max())
{std::fprintf(stderr,"[SeedSurfacePlacement] FAIL: no valid SurfaceWorld heightfield\n");return 2;}
cameraVoxels.Z=static_cast<float>(static_cast<double>(selectedGround)/UnitsPerVoxel);
std::printf("[SeedSurfacePlacement] recipe=surface-world seed=%d ground_voxel=%.6f camera_voxel=(%.6f,%.6f,%.6f) status=PASS\n",
seed,static_cast<double>(selectedGround)/UnitsPerVoxel,
cameraVoxels.X,cameraVoxels.Y,cameraVoxels.Z);
}
}
std::printf("[WorldAssemblerPlanTiming] total_ms=%.3f status=PASS\n",
@@ -538,9 +377,8 @@ int main(int argc,char** argv)
FStandaloneCoreScheduler scheduler;
const FVector cameraStepVoxels=options.HasCameraStep
?FVector(options.CameraStepMeters.X*1000000.0f/std::max<std::uint32_t>(1,ownerWorld->CoreVoxelSizeMicrons),
options.CameraStepMeters.Y*1000000.0f/std::max<std::uint32_t>(1,ownerWorld->CoreVoxelSizeMicrons),
options.CameraStepMeters.Z*1000000.0f/std::max<std::uint32_t>(1,ownerWorld->CoreVoxelSizeMicrons)):FVector::ZeroVector;
?FVector(options.CameraStepMeters.X*4.0f,options.CameraStepMeters.Y*4.0f,
options.CameraStepMeters.Z*4.0f):FVector::ZeroVector;
return StandaloneStreamBenchmark::RunPipelinedStreamingBenchmark(ownerWorld,snapshot,
cameraVoxels,options.WorkerCount,options.MaxLevel,VoxelForgeCore::DetailVariant::coherent,
scheduler,options.StreamHash,false,false,false,false,coldStart,
@@ -550,7 +388,9 @@ int main(int argc,char** argv)
cameraStepVoxels,options.AuditUniformBlockProofs,options.ProfileLodWork,
options.RegionCrossing,options.AuditTileShapeReadiness,
options.DiagnosticSlowShapeCompileMs,options.AuditBasePageEquivalence,
options.AuditRouteParity,options.AuditResolvedLayoutBoundaries,
options.AuditResolvedLayoutPassages,
&resolvedLayout);
options.AuditRouteParity,
options.TileCachePrototype
?std::filesystem::current_path()/"Saved/Linux/cache/l16-prototype"
:std::filesystem::path{},
options.DataPath);
}
+111 -551
View File
@@ -3,6 +3,7 @@
#include "OwnerWorldLoader.h"
#include "StreamingWorld.h"
#include "LinuxScreenSpaceGate.h"
#include "../Research/WorldAssemblerM3/Linux16/TileCachePrototype.h"
#include <algorithm>
#include <array>
@@ -254,9 +255,8 @@ namespace StandaloneStreamBenchmark
bool bRegionCrossing=false,
bool bAuditTileShapeReadiness=false,int DiagnosticSlowShapeCompileMs=0,
bool bAuditBasePageEquivalence=false,bool bAuditRouteParity=false,
bool bAuditResolvedLayoutBoundaries=false,
bool bAuditResolvedLayoutPassages=false,
const VoxelForgeCore::ResolvedLayoutSnapshotV3* ResolvedLayout=nullptr)
const std::filesystem::path& TileCachePrototypeRoot={},
const std::filesystem::path& OwnerSnapshotPath={})
{
using Clock=std::chrono::steady_clock;
FStandaloneOwnerWorld& World=*OwnerWorld;
@@ -277,6 +277,42 @@ namespace StandaloneStreamBenchmark
const bool bRoundTunnels=World.Generator->bStandaloneResearchRoundTunnels;
const bool bEnhancedTunnelWalls=World.Generator->bStandaloneResearchEnhancedWalls;
VoxelForgeCore::World Shape(CoreSnapshot);
std::unique_ptr<StandaloneTileCachePrototype::TileDiskCache> TileCache;
FStandaloneCoreTileRoute CoreTileRoute;
VoxelForgeCore::TileGenerationOptions CacheOptions;
if(!TileCachePrototypeRoot.empty())
{
const auto RepoRoot=std::filesystem::current_path().lexically_normal();
const auto AllowedRoot=(RepoRoot/"Saved/Linux/cache").lexically_normal();
const auto RequestedRoot=std::filesystem::absolute(TileCachePrototypeRoot).lexically_normal();
const std::string AllowedString=AllowedRoot.string()+std::string(1,std::filesystem::path::preferred_separator);
if(RequestedRoot.string().rfind(AllowedString,0)!=0||OwnerSnapshotPath.empty())
{
std::fprintf(stderr,"[TileCachePrototype] path rejected: cache writes must stay under Saved/Linux/cache and owner snapshot identity must be provided.\n");
return 2;
}
if(ClosestDisplayDistances[0]==0.0)
ClosestDisplayDistances=StandaloneScreenSpaceGate::ClosestDisplayedDistancesMeters(
World,CameraPositionVoxels,World.CoreVoxelSizeMicrons);
const auto Identity=StandaloneTileCachePrototype::MakeIdentity(
World,CoreSnapshot,OwnerSnapshotPath);
if(Identity.ownerSnapshotHash==0||!Assembly)
{
std::fprintf(stderr,"[TileCachePrototype] missing owner snapshot or world assembly identity.\n");
return 2;
}
TileCache=std::make_unique<StandaloneTileCachePrototype::TileDiskCache>(
RequestedRoot,Identity,ClosestDisplayDistances);
CacheOptions.hashDensity=true;
StandaloneTileCachePrototype::TileDiskCache* Cache=TileCache.get();
CoreTileRoute=[Cache](const VoxelForgeCore::World& TileWorld,
const VoxelForgeCore::TileKey& Key,
const VoxelForgeCore::TileGenerationOptions& Options,bool& bHit,
std::string& Error)
{return Cache->GenerateOrLoad(TileWorld,Key,Options,bHit,Error);};
std::printf("[TileCachePrototype] enabled root=%s owner_snapshot=%s mode=worker_generate_store_read_or_warm_hit codec=zlib-6\n",
RequestedRoot.string().c_str(),OwnerSnapshotPath.string().c_str());
}
FStandaloneDesiredTileSet Desired=StandaloneWorldMesher::BuildDesiredSet(World,CameraPositionVoxels);
const auto CoreTiles=Shape.desiredTiles(
{CameraPositionVoxels.X,CameraPositionVoxels.Y,CameraPositionVoxels.Z});
@@ -414,7 +450,7 @@ namespace StandaloneStreamBenchmark
ShapeRequest.enhancedTunnelWalls=bEnhancedTunnelWalls;
FStandaloneStreamingGenerator Streamer(World,WorkerCount,bHashDensity,nullptr,MaxLevel,
bSkipUvAndColors,bSkipMaterialGroups,bSkipUV,bSkipColors,&Shape,bProfileColumnOverlap,
FarHorizonLOD8InteriorStepVoxels,bUseSharedColumnCache);
FarHorizonLOD8InteriorStepVoxels,bUseSharedColumnCache,std::move(CoreTileRoute));
Streamer.SetUniformBlockProofAuditEnabled(bAuditUniformBlockProofs);
if(bScreenSpaceGate||bReportLodWorkProfile)Streamer.SetMesherStageProfilingEnabled(true);
const auto StreamStart=Clock::now();
@@ -441,548 +477,6 @@ namespace StandaloneStreamBenchmark
Streamer.Stop();
std::fprintf(stderr,"[StreamPipeline] full shape build failed: %s\n",BuildError.c_str());return 2;
}
if(bAuditResolvedLayoutPassages)
{
if(ResolvedLayout==nullptr||!CoreSnapshot.resolvedLayout())
{Streamer.Stop();std::fprintf(stderr,"[ResolvedPassageAudit] missing resolved-layout snapshot\n");return 2;}
struct FWalkAudit
{
std::uint64_t segments=0,centers=0,capsuleSamples=0,blocked=0;
std::uint64_t supportSamples=0,unsupported=0,gradeFailures=0;
std::array<std::array<double,4>,8> firstBlocked{};
std::array<std::array<double,4>,8> firstUnsupported{};
std::array<std::array<bool,5>,8> firstSupportMasks{};
std::size_t firstBlockedCount=0,firstUnsupportedCount=0;
bool passed=false;
};
const double coreMetres=static_cast<double>(World.CoreVoxelSizeMicrons)/1000000.0;
const auto auditPlayerPath=[&](const VoxelForgeCore::World& Field,
const std::vector<std::array<double,3>>& path,
double supportStartMetres,double supportStepMetres,
double supportMaximumMetres,std::uint32_t minimumSupportProbes,
double supportProbeRadiusMetres)
{
FWalkAudit audit;
if(path.size()<2)return audit;
constexpr std::array<double,7> heights{{-0.84,-0.60,-0.30,0.0,0.30,0.60,0.84}};
constexpr std::array<std::array<double,2>,8> directions{{
{{1.0,0.0}},{{0.7071067811865475,0.7071067811865475}},{{0.0,1.0}},
{{-0.7071067811865475,0.7071067811865475}},{{-1.0,0.0}},
{{-0.7071067811865475,-0.7071067811865475}},{{0.0,-1.0}},
{{0.7071067811865475,-0.7071067811865475}}}};
const auto solidAt=[&](double xMetres,double yMetres,double zMetres)
{
++audit.capsuleSamples;
const VoxelForgeCore::Vec3d position{xMetres/coreMetres,yMetres/coreMetres,zMetres/coreMetres};
const float density=Field.densityAt(position);
if(density<0.0f)
{
if(audit.firstBlockedCount<audit.firstBlocked.size())
{
audit.firstBlocked[audit.firstBlockedCount++]={xMetres,yMetres,zMetres,density};
std::printf("[ResolvedWalkDispatch] kind=blocked xyz_m=(%.3f,%.3f,%.3f) path=%s\n",
xMetres,yMetres,zMetres,Field.densityDispatchPathAt(position).c_str());
}
++audit.blocked;return true;
}
return false;
};
for(std::size_t segment=1;segment<path.size();++segment)
{
++audit.segments;
const auto& a=path[segment-1];const auto& b=path[segment];
const double dx=b[0]-a[0],dy=b[1]-a[1],dz=b[2]-a[2];
const double horizontal=std::hypot(dx,dy)*coreMetres;
const double vertical=std::abs(dz)*coreMetres;
if(horizontal<=1.0e-6||vertical>horizontal*0.2679491924311227)
++audit.gradeFailures;
const double length=std::sqrt(dx*dx+dy*dy+dz*dz)*coreMetres;
const std::uint64_t intervals=std::max<std::uint64_t>(1,
static_cast<std::uint64_t>(std::ceil(length/0.5)));
for(std::uint64_t step=0;step<=intervals;++step)
{
if(segment>1&&step==0)continue;
const double t=static_cast<double>(step)/intervals;
const double x=(a[0]+dx*t)*coreMetres;
const double y=(a[1]+dy*t)*coreMetres;
const double z=(a[2]+dz*t)*coreMetres;
++audit.centers;
for(const double h:heights)
{
const double capOffset=std::max(0.0,std::abs(h)-0.54);
const double radial=std::abs(h)<=0.54?0.34
:std::sqrt(std::max(0.0,0.34*0.34-capOffset*capOffset));
solidAt(x,y,z+h);
for(const auto& direction:directions)
solidAt(x+direction[0]*radial,y+direction[1]*radial,z+h);
}
const double footZ=z-0.88;
const std::array<std::array<double,2>,5> supportOffsets{{
{{0.0,0.0}},{{supportProbeRadiusMetres,0.0}},
{{-supportProbeRadiusMetres,0.0}},
{{0.0,supportProbeRadiusMetres}},
{{0.0,-supportProbeRadiusMetres}}}};
std::uint32_t supportedProbes=0;
double firstUnsupportedX=x,firstUnsupportedY=y,lastUnsupportedDensity=0.0;
std::array<bool,5> supportMask{};
for(std::size_t offsetIndex=0;offsetIndex<supportOffsets.size();++offsetIndex)
{
const auto& offset=supportOffsets[offsetIndex];
const double supportX=x+offset[0],supportY=y+offset[1];
bool supported=false;
for(double depth=supportStartMetres;
depth<=supportMaximumMetres+1.0e-6;depth+=supportStepMetres)
{
++audit.supportSamples;
lastUnsupportedDensity=Field.densityAt({supportX/coreMetres,
supportY/coreMetres,(footZ-depth)/coreMetres});
if(lastUnsupportedDensity<0.0)
{
supported=true;break;
}
}
if(supported){++supportedProbes;supportMask[offsetIndex]=true;}
else{firstUnsupportedX=supportX;firstUnsupportedY=supportY;}
}
if(supportedProbes<minimumSupportProbes)
{
++audit.unsupported;
if(audit.firstUnsupportedCount<audit.firstUnsupported.size())
{
const std::size_t sample=audit.firstUnsupportedCount++;
audit.firstUnsupported[sample]={
firstUnsupportedX,firstUnsupportedY,footZ,lastUnsupportedDensity};
audit.firstSupportMasks[sample]=supportMask;
std::printf("[ResolvedWalkDispatch] kind=unsupported xyz_m=(%.3f,%.3f,%.3f) support_probes=%u/5 mask=%d%d%d%d%d path=%s\n",
firstUnsupportedX,firstUnsupportedY,footZ,supportedProbes,
supportMask[0],supportMask[1],supportMask[2],supportMask[3],supportMask[4],
Field.densityDispatchPathAt({firstUnsupportedX/coreMetres,
firstUnsupportedY/coreMetres,footZ/coreMetres}).c_str());
}
}
}
}
audit.passed=audit.centers>0&&audit.blocked==0&&audit.unsupported==0
&&audit.gradeFailures==0;
return audit;
};
const auto qToMetres=[&](std::int64_t q)
{return static_cast<double>(q)*World.CoreVoxelSizeMicrons
/(VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel*1000000.0);};
struct FPassageNaturalnessAudit
{
double maximumFlatRunMetres=0.0;
double wallReliefPeakToPeakMetres=0.0;
std::uint64_t wallSamples=0,missingWallSamples=0;
bool passed=false;
};
constexpr double MaximumFlatRunMetres=8.0;
constexpr double MinimumWallReliefMetres=0.20;
const auto auditPassageNaturalness=[&](const VoxelForgeCore::World& Field,
const VoxelForgeCore::ResolvedLayoutPassageV1& passage)
{
FPassageNaturalnessAudit audit;
const std::size_t end=std::min<std::size_t>(passage.lowerMouthControlIndex,
passage.controlPoints.size()-1);
double flatRun=0.0;
for(std::size_t i=1;i<=end;++i)
{
const auto& a=passage.controlPoints[i-1];
const auto& b=passage.controlPoints[i];
const double dx=qToMetres(b.positionSubvoxels[0]-a.positionSubvoxels[0]);
const double dy=qToMetres(b.positionSubvoxels[1]-a.positionSubvoxels[1]);
const double dz=qToMetres(b.positionSubvoxels[2]-a.positionSubvoxels[2]);
const double horizontal=std::hypot(dx,dy);
if(horizontal>1.0e-6&&std::abs(dz)/horizontal
<std::tan(0.5*3.14159265358979323846/180.0))
{flatRun+=horizontal;audit.maximumFlatRunMetres=std::max(
audit.maximumFlatRunMetres,flatRun);}
else flatRun=0.0;
}
if(end>=6)
{
const std::size_t sampleCount=std::min<std::size_t>(64,end-4);
double minimumRadius=std::numeric_limits<double>::infinity();
double maximumRadius=-std::numeric_limits<double>::infinity();
for(std::size_t sample=0;sample<sampleCount;++sample)
{
const std::size_t index=2+(sample*(end-4))
/std::max<std::size_t>(1,sampleCount-1);
const auto& point=passage.controlPoints[index];
const auto& before=passage.controlPoints[index-1];
const auto& after=passage.controlPoints[index+1];
const double tangentX=qToMetres(after.positionSubvoxels[0]-before.positionSubvoxels[0]);
const double tangentY=qToMetres(after.positionSubvoxels[1]-before.positionSubvoxels[1]);
const double tangentLength=std::hypot(tangentX,tangentY);
if(tangentLength<=1.0e-6){++audit.missingWallSamples;continue;}
const double radiusMetres=qToMetres(point.radiusSubvoxels);
const double sampleRadius=std::max(0.20,radiusMetres-0.18);
const double centerX=qToMetres(point.positionSubvoxels[0]);
const double centerY=qToMetres(point.positionSubvoxels[1]);
const double centerZ=qToMetres(point.positionSubvoxels[2]);
const double nx=-tangentY/tangentLength,ny=tangentX/tangentLength;
for(const double side:{-1.0,1.0})
{
const VoxelForgeCore::Vec3d probe{
(centerX+side*nx*sampleRadius)/coreMetres,
(centerY+side*ny*sampleRadius)/coreMetres,
centerZ/coreMetres};
const double density=Field.densityAt(probe);
if(!std::isfinite(density)){++audit.missingWallSamples;continue;}
const double densityMetres=density*coreMetres;
if(densityMetres< -0.75||densityMetres>0.75)
{++audit.missingWallSamples;continue;}
// For the carved SDF, r + density is the wall radius. Its
// variation along the passage measures the applied rock relief.
const double wallRadius=sampleRadius+densityMetres;
minimumRadius=std::min(minimumRadius,wallRadius);
maximumRadius=std::max(maximumRadius,wallRadius);
++audit.wallSamples;
}
}
if(audit.wallSamples>0&&std::isfinite(minimumRadius)
&&std::isfinite(maximumRadius))
audit.wallReliefPeakToPeakMetres=maximumRadius-minimumRadius;
}
audit.passed=audit.maximumFlatRunMetres<=MaximumFlatRunMetres
&&audit.wallReliefPeakToPeakMetres>=MinimumWallReliefMetres
&&audit.wallSamples>=8;
return audit;
};
const auto looksNatural=[&](double flatRun,double reliefPeakToPeak)
{return flatRun<=MaximumFlatRunMetres
&&reliefPeakToPeak>=MinimumWallReliefMetres;};
const auto findStratum=[&](std::int32_t index)->const VoxelForgeCore::ResolvedLayoutStratumV2*
{
const auto it=std::find_if(ResolvedLayout->strates.begin(),ResolvedLayout->strates.end(),
[index](const auto& s){return s.strateIndex==index;});
return it==ResolvedLayout->strates.end()?nullptr:&*it;
};
const auto mouthInContent=[&](std::int32_t index,const std::array<std::int64_t,3>& mouth)
{
const auto* stratum=findStratum(index);if(!stratum)return false;
const std::int64_t zUm=static_cast<std::int64_t>(std::llround(
static_cast<double>(mouth[2])*World.CoreVoxelSizeMicrons
/VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel));
return zUm>=stratum->content.bottomMicrometres&&zUm<stratum->content.topMicrometres;
};
std::uint64_t passageCount=0,passagePasses=0,blockedControls=0,naturalPasses=0;
for(const auto& passage:ResolvedLayout->passages)
{
std::vector<std::array<double,3>> path;path.reserve(passage.controlPoints.size());
for(const auto& point:passage.controlPoints)
{
const double playerZ=static_cast<double>(point.positionSubvoxels[2]
-point.radiusSubvoxels)+1.13*VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel
*1000000.0/World.CoreVoxelSizeMicrons;
path.push_back({qToMetres(point.positionSubvoxels[0])/coreMetres,
qToMetres(point.positionSubvoxels[1])/coreMetres,playerZ/256.0});
}
const FWalkAudit passageAudit=auditPlayerPath(Shape,path,0.125,0.125,0.25,3,0.45);
const FPassageNaturalnessAudit naturalAudit=auditPassageNaturalness(Shape,passage);
const auto radialSquared=[](const std::array<std::int64_t,3>& p)
{return p[0]*p[0]+p[1]*p[1];};
const bool mouthsInRadius=radialSquared(passage.upperMouthSubvoxels)
<=passage.placementRadiusSubvoxels*passage.placementRadiusSubvoxels
&&radialSquared(passage.lowerMouthSubvoxels)
<=passage.placementRadiusSubvoxels*passage.placementRadiusSubvoxels;
const bool mouthsInContent=mouthInContent(passage.upperStrateIndex,passage.upperMouthSubvoxels)
&&mouthInContent(passage.lowerStrateIndex,passage.lowerMouthSubvoxels);
++passageCount;naturalPasses+=naturalAudit.passed;
passagePasses+=passageAudit.passed&&mouthsInRadius&&mouthsInContent
&&naturalAudit.passed;
std::printf("[ResolvedPassageAudit] id=%s interface=%d-%d control_points=%zu center_samples=%llu capsule_samples=%llu blocked=%llu support_samples=%llu unsupported=%llu grade_failures=%llu mouth_content=%d/2 mouth_radius=%d/2 walkability=%s\n",
passage.stableId.c_str(),passage.upperStrateIndex,passage.lowerStrateIndex,
passage.controlPoints.size(),static_cast<unsigned long long>(passageAudit.centers),
static_cast<unsigned long long>(passageAudit.capsuleSamples),
static_cast<unsigned long long>(passageAudit.blocked),
static_cast<unsigned long long>(passageAudit.supportSamples),
static_cast<unsigned long long>(passageAudit.unsupported),
static_cast<unsigned long long>(passageAudit.gradeFailures),mouthsInContent?2:0,
mouthsInRadius?2:0,passageAudit.passed?"PASS":"FAIL");
std::printf("[PassageNaturalnessAudit] id=%s flat_run_max_m=%.3f limit_m=%.3f wall_relief_p2p_m=%.3f minimum_m=%.3f samples=%llu missing=%llu status=%s\n",
passage.stableId.c_str(),naturalAudit.maximumFlatRunMetres,MaximumFlatRunMetres,
naturalAudit.wallReliefPeakToPeakMetres,MinimumWallReliefMetres,
static_cast<unsigned long long>(naturalAudit.wallSamples),
static_cast<unsigned long long>(naturalAudit.missingWallSamples),
naturalAudit.passed?"PASS":"FAIL");
for(std::size_t i=0;i<passageAudit.firstBlockedCount;++i)
std::printf("[ResolvedPassageAuditSample] id=%s kind=blocked xyz_m=(%.3f,%.3f,%.3f) density=%.6f\n",
passage.stableId.c_str(),passageAudit.firstBlocked[i][0],passageAudit.firstBlocked[i][1],
passageAudit.firstBlocked[i][2],passageAudit.firstBlocked[i][3]);
for(std::size_t i=0;i<passageAudit.firstUnsupportedCount;++i)
std::printf("[ResolvedPassageAuditSample] id=%s kind=unsupported xyz_m=(%.3f,%.3f,%.3f) density=%.6f\n",
passage.stableId.c_str(),passageAudit.firstUnsupported[i][0],
passageAudit.firstUnsupported[i][1],passageAudit.firstUnsupported[i][2],
passageAudit.firstUnsupported[i][3]);
}
std::uint64_t routePoints=0,routePasses=0,routeWalkPasses=0,routeBindings=0,routeBindingFailures=0;
struct FRouteAuditInput
{
std::int32_t strateIndex=0;
std::vector<std::array<double,3>> path;
double supportStart=0.125,supportStep=0.125,supportMaximum=0.25,
supportProbeRadius=0.45;
std::uint32_t minimumSupportProbes=3;
};
std::vector<FRouteAuditInput> routeAuditInputs;
for(const auto& stratum:ResolvedLayout->strates)
{
std::vector<const VoxelForgeCore::ResolvedLayoutAnchorV2*> anchors;
for(const auto& anchor:stratum.anchors)
if(anchor.kind=="route_point"&&anchor.values.size()>=3)anchors.push_back(&anchor);
if(anchors.size()<2)continue;
std::vector<std::array<double,3>> route;route.reserve(anchors.size());
for(const auto* anchor:anchors)
{
route.push_back({qToMetres(anchor->values[0])/coreMetres,
qToMetres(anchor->values[1])/coreMetres,
qToMetres(anchor->values[2])/coreMetres});
++routePoints;
}
double supportStartMetres=0.125,supportStepMetres=0.125,
supportMaximumMetres=0.25,supportProbeRadiusMetres=0.45;
std::uint32_t minimumSupportProbes=3;
const VoxelForgeCore::WorldAssemblyRouteConstraintsV1* routeConstraints=nullptr;
if(Assembly)
{
const auto worldRoute=std::find_if(Assembly->plan.strates.begin(),
Assembly->plan.strates.end(),[&](const auto& candidate)
{return candidate.strateIndex==stratum.strateIndex;});
if(worldRoute!=Assembly->plan.strates.end()
&&worldRoute->routeConstraints.version==1)
routeConstraints=&worldRoute->routeConstraints;
const auto islandRoute=std::find_if(Assembly->floatingIslands.begin(),
Assembly->floatingIslands.end(),[&](const auto& candidate)
{return candidate.strateIndex==stratum.strateIndex;});
if(islandRoute!=Assembly->floatingIslands.end()
&&islandRoute->manifest.recipe.routeConstraints.version==1)
routeConstraints=&islandRoute->manifest.recipe.routeConstraints;
}
if(routeConstraints)
{
const double qMetres=coreMetres
/VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel;
minimumSupportProbes=std::clamp<std::uint32_t>(
routeConstraints->minimumSupportProbes,1,5);
supportProbeRadiusMetres=routeConstraints->supportProbeRadiusSubvoxels*qMetres;
if(stratum.generatorKind=="FloatingIslands")
{
supportStartMetres=(routeConstraints->minimumClearanceSubvoxels
+VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel/2)*qMetres;
supportStepMetres=VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel
*0.5*qMetres;
supportMaximumMetres=(routeConstraints->minimumClearanceSubvoxels
+routeConstraints->supportSearchDepthSubvoxels)*qMetres;
}
else
{
const std::int64_t spacing=std::min<std::int64_t>(
routeConstraints->sweepSpacingSubvoxels,
VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel/4);
supportStepMetres=std::max<std::int64_t>(1,spacing)*qMetres;
supportStartMetres=supportStepMetres;
supportMaximumMetres=routeConstraints->supportSearchDepthSubvoxels*qMetres;
}
}
const FWalkAudit routeAudit=auditPlayerPath(Shape,route,supportStartMetres,
supportStepMetres,supportMaximumMetres,minimumSupportProbes,
supportProbeRadiusMetres);
routeAuditInputs.push_back({stratum.strateIndex,route,supportStartMetres,
supportStepMetres,supportMaximumMetres,supportProbeRadiusMetres,
minimumSupportProbes});
bool binding=true;
for(const auto& passage:ResolvedLayout->passages)
{
const auto equalPosition=[](const auto& a,const auto& b)
{return a[0]==b[0]&&a[1]==b[1]&&a[2]==b[2];};
if(passage.upperStrateIndex==stratum.strateIndex)
{
const std::array<std::int64_t,3> departure{{anchors.back()->values[0],
anchors.back()->values[1],anchors.back()->values[2]}};
binding&=equalPosition(passage.upperMouthSubvoxels,
departure);
}
if(passage.lowerStrateIndex==stratum.strateIndex)
{
const std::array<std::int64_t,3> arrival{{anchors.front()->values[0],
anchors.front()->values[1],anchors.front()->values[2]}};
binding&=equalPosition(passage.lowerMouthSubvoxels,
arrival);
}
}
++routePasses;routeWalkPasses+=routeAudit.passed;
routeBindings+=binding;routeBindingFailures+=!binding;
std::printf("[ResolvedStrateRouteAudit] strate=%d route_points=%zu center_samples=%llu capsule_samples=%llu blocked=%llu support_samples=%llu unsupported=%llu grade_failures=%llu mouth_binding=%s status=%s\n",
stratum.strateIndex,anchors.size(),static_cast<unsigned long long>(routeAudit.centers),
static_cast<unsigned long long>(routeAudit.capsuleSamples),
static_cast<unsigned long long>(routeAudit.blocked),
static_cast<unsigned long long>(routeAudit.supportSamples),
static_cast<unsigned long long>(routeAudit.unsupported),
static_cast<unsigned long long>(routeAudit.gradeFailures),binding?"PASS":"FAIL",
routeAudit.passed&&binding?"PASS":"FAIL");
for(std::size_t i=0;i<routeAudit.firstBlockedCount;++i)
std::printf("[ResolvedStrateRouteAuditSample] strate=%d kind=blocked xyz_m=(%.3f,%.3f,%.3f) density=%.6f\n",
stratum.strateIndex,routeAudit.firstBlocked[i][0],routeAudit.firstBlocked[i][1],
routeAudit.firstBlocked[i][2],routeAudit.firstBlocked[i][3]);
for(std::size_t i=0;i<routeAudit.firstUnsupportedCount;++i)
std::printf("[ResolvedStrateRouteAuditSample] strate=%d kind=unsupported xyz_m=(%.3f,%.3f,%.3f) density=%.6f\n",
stratum.strateIndex,routeAudit.firstUnsupported[i][0],
routeAudit.firstUnsupported[i][1],routeAudit.firstUnsupported[i][2],
routeAudit.firstUnsupported[i][3]);
}
const auto controlSnapshot=CoreSnapshot.withoutResolvedLayoutPassages();
VoxelForgeCore::World blockedWorld(controlSnapshot);
std::string blockedCompileError;
const bool blockedCompiled=controlSnapshot
&&blockedWorld.compile(ShapeRequest,Scheduler,blockedCompileError);
if(blockedCompiled)
for(const auto& passage:ResolvedLayout->passages)
{
std::vector<std::array<double,3>> path;path.reserve(passage.controlPoints.size());
for(const auto& point:passage.controlPoints)
{
const double playerZ=static_cast<double>(point.positionSubvoxels[2]
-point.radiusSubvoxels)+1.13*VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel
*1000000.0/World.CoreVoxelSizeMicrons;
path.push_back({qToMetres(point.positionSubvoxels[0])/coreMetres,
qToMetres(point.positionSubvoxels[1])/coreMetres,playerZ/256.0});
}
const FWalkAudit blockedAudit=auditPlayerPath(blockedWorld,path,
0.125,0.125,0.25,3,0.45);
blockedControls+=blockedAudit.blocked>0&&!blockedAudit.passed;
std::printf("[ResolvedPassageBlockedControl] id=%s blocked_capsule_samples=%llu detected=%s\n",
passage.stableId.c_str(),static_cast<unsigned long long>(blockedAudit.blocked),
blockedAudit.blocked>0&&!blockedAudit.passed?"true":"false");
}
else
std::fprintf(stderr,"[ResolvedPassageBlockedControl] compile_failed=%s\n",blockedCompileError.c_str());
if(blockedCompiled)
for(const auto& input:routeAuditInputs)
{
const FWalkAudit controlRoute=auditPlayerPath(blockedWorld,input.path,
input.supportStart,input.supportStep,input.supportMaximum,
input.minimumSupportProbes,input.supportProbeRadius);
std::printf("[ResolvedStrateRouteBlockedControl] strate=%d blocked=%llu unsupported=%llu status=%s\n",
input.strateIndex,static_cast<unsigned long long>(controlRoute.blocked),
static_cast<unsigned long long>(controlRoute.unsupported),
controlRoute.passed?"PASS":"FAIL");
}
const bool l23SmoothWallDetected=!looksNatural(0.0,0.0);
std::printf("[PassageNaturalnessNegativeControl] source=L23_smooth_unrelieved_wall relief_p2p_m=0.000 threshold_m=%.3f detected=%s\n",
MinimumWallReliefMetres,l23SmoothWallDetected?"true":"false");
std::printf("[PassageNaturalnessSummary] passed=%llu/%llu l23_negative_control=%s flat_run_limit_m=%.3f wall_relief_min_m=%.3f status=%s\n",
static_cast<unsigned long long>(naturalPasses),static_cast<unsigned long long>(passageCount),
l23SmoothWallDetected?"DETECTED":"MISSED",MaximumFlatRunMetres,
MinimumWallReliefMetres,naturalPasses==passageCount&&l23SmoothWallDetected?"PASS":"FAIL");
const bool auditPassed=passageCount>0&&passagePasses==passageCount
&&naturalPasses==passageCount&&l23SmoothWallDetected
&&routePasses>0&&routePasses==routeWalkPasses&&routePasses==routeBindings
&&routeBindingFailures==0
&&blockedCompiled&&blockedControls==passageCount;
std::printf("[ResolvedPassageAuditSummary] interfaces=%llu passed=%llu natural=%llu/%llu strate_routes=%llu route_walkable=%llu route_points=%llu route_bindings=%llu route_binding_failures=%llu blocked_controls=%llu/%llu status=%s\n",
static_cast<unsigned long long>(passageCount),static_cast<unsigned long long>(passagePasses),
static_cast<unsigned long long>(naturalPasses),static_cast<unsigned long long>(passageCount),
static_cast<unsigned long long>(routePasses),static_cast<unsigned long long>(routeWalkPasses),
static_cast<unsigned long long>(routePoints),
static_cast<unsigned long long>(routeBindings),static_cast<unsigned long long>(routeBindingFailures),
static_cast<unsigned long long>(blockedControls),static_cast<unsigned long long>(passageCount),
auditPassed?"PASS":"FAIL");
if(!auditPassed)
{Streamer.Stop();return 10;}
}
if(bAuditResolvedLayoutBoundaries)
{
if(ResolvedLayout==nullptr)
{Streamer.Stop();std::fprintf(stderr,"[ResolvedLayoutProbe] missing plan-time snapshot\n");return 2;}
std::vector<std::int64_t> endpoints;
for(const auto& Stratum:ResolvedLayout->strates)
{
endpoints.push_back(Stratum.interiorBottomMicrometres);
endpoints.push_back(Stratum.interiorTopMicrometres);
endpoints.push_back(Stratum.ceiling.bottomMicrometres);
endpoints.push_back(Stratum.ceiling.topMicrometres);
endpoints.push_back(Stratum.bedrock.bottomMicrometres);
endpoints.push_back(Stratum.bedrock.topMicrometres);
}
for(std::size_t StratumIndex=0;StratumIndex+1<ResolvedLayout->strates.size();++StratumIndex)
{
const auto& Upper=ResolvedLayout->strates[StratumIndex];
if(Upper.transitionMode=="Hard"||Upper.transitionWidthMicrometres<=0)continue;
endpoints.push_back(Upper.interiorBottomMicrometres-Upper.transitionWidthMicrometres);
endpoints.push_back(Upper.interiorBottomMicrometres+Upper.transitionWidthMicrometres);
}
std::sort(endpoints.begin(),endpoints.end());
endpoints.erase(std::unique(endpoints.begin(),endpoints.end()),endpoints.end());
std::uint64_t probes=0,disagreements=0;
const double CoreVoxelMicrometres=std::max<std::uint32_t>(1,World.CoreVoxelSizeMicrons);
const auto expectedAt=[&](std::int64_t zMicrometres)
{
std::vector<std::string> candidates;
for(const auto& Stratum:ResolvedLayout->strates)
{
const auto contains=[zMicrometres](const VoxelForgeCore::ResolvedLayoutBandV2& Band)
{return Band.presentInCurrentField&&zMicrometres>=Band.bottomMicrometres
&&zMicrometres<Band.topMicrometres;};
if(contains(Stratum.ceiling))candidates.push_back(Stratum.generatorKind+"/ceiling");
if(contains(Stratum.content))candidates.push_back(Stratum.generatorKind+"/content");
if(contains(Stratum.bedrock))candidates.push_back(Stratum.generatorKind+"/bedrock");
}
return candidates;
};
const std::array<std::int64_t,3> offsets{{
-static_cast<std::int64_t>(World.CoreVoxelSizeMicrons),0,
static_cast<std::int64_t>(World.CoreVoxelSizeMicrons)}};
const std::int64_t stackMinimum=std::min_element(ResolvedLayout->strates.begin(),
ResolvedLayout->strates.end(),[](const auto& A,const auto& B)
{return A.bedrock.bottomMicrometres<B.bedrock.bottomMicrometres;})
->bedrock.bottomMicrometres;
const std::int64_t stackMaximum=std::max_element(ResolvedLayout->strates.begin(),
ResolvedLayout->strates.end(),[](const auto& A,const auto& B)
{return A.ceiling.topMicrometres<B.ceiling.topMicrometres;})
->ceiling.topMicrometres;
for(const std::int64_t Endpoint:endpoints)
for(const std::int64_t Offset:offsets)
{
const std::int64_t zMicrometres=Endpoint+Offset;
const double zVoxel=static_cast<double>(zMicrometres)/CoreVoxelMicrometres;
const VoxelForgeCore::Vec3d position{0.0,0.0,zVoxel};
const std::string actual=Shape.densityDispatchPathAt(position);
const auto expected=expectedAt(zMicrometres);
std::string expectedLabel;
std::vector<std::string> expectedGenerators;
for(const auto& Candidate:expected)
{
if(!expectedLabel.empty())expectedLabel+=',';
expectedLabel+=Candidate;
const auto Separator=Candidate.find('/');
const std::string Kind=Candidate.substr(0,Separator);
if(std::find(expectedGenerators.begin(),expectedGenerators.end(),Kind)==expectedGenerators.end())
expectedGenerators.push_back(Kind);
}
const float density=Shape.densityAt(position);
const bool solid=density<0.0f;
const bool outsideStack=zMicrometres<stackMinimum||zMicrometres>=stackMaximum;
if(expected.empty())expectedLabel=outsideStack?"outside-stack/air":"uncovered";
std::string actualGenerator;
if(actual=="SurfaceWorld-native"||actual=="SurfaceWorld-legacy")actualGenerator="SurfaceWorld";
else if(actual=="FloatingIslands-native")actualGenerator="FloatingIslands";
else if(actual.rfind("compiled-analytic/",0)==0)actualGenerator=actual.substr(18);
const bool mismatch=expected.empty()
?(!outsideStack||solid)
:std::find(expectedGenerators.begin(),expectedGenerators.end(),actualGenerator)==expectedGenerators.end();
++probes;disagreements+=mismatch?1u:0u;
std::printf("[ResolvedLayoutProbe] endpoint_um=%lld offset_um=%lld z_m=%.3f expected=%s actual=%s density=%.7g occupancy=%s disagreement=%s\n",
static_cast<long long>(Endpoint),static_cast<long long>(Offset),
static_cast<double>(zMicrometres)/1000000.0,expectedLabel.c_str(),actual.c_str(),density,
solid?"solid":"air",mismatch?"YES":"no");
}
std::printf("[ResolvedLayoutProbeSummary] probes=%llu disagreements=%llu status=%s\n",
static_cast<unsigned long long>(probes),static_cast<unsigned long long>(disagreements),
disagreements==0?"PASS":"DEVIATIONS_RECORDED");
Streamer.Stop();
return 0;
}
const auto ShapeReady=Clock::now();
const double ShapeSeconds=std::chrono::duration<double>(ShapeReady-ShapeBuildStart).count();
if(bAuditTileShapeReadiness)
@@ -1202,6 +696,7 @@ namespace StandaloneStreamBenchmark
VoxelForgeCore::TileGenerationOptions PageOptions=CaptureOptions;
PageOptions.auditUniformBlockProofs=true;
int32 CachePairs=0,CacheMismatches=0,EditCachePairs=0,EditCacheMismatches=0;
int32 BasePageMismatches=0,PageRoutesVerified=0;
std::uint64_t PageProofBlocks=0,PageProofSamples=0,PageProofFallbacks=0,
PageProofUnknown=0,PageProofViolations=0;
@@ -1261,6 +756,28 @@ namespace StandaloneStreamBenchmark
PageProofUnknown+=Page->diagnostics.uniformBlockProofUnknownBlocks;
PageProofViolations+=Page->diagnostics.uniformBlockProofViolations;
}
if(TileCache)
{
VoxelForgeCore::TileMesh Cached;
std::string CacheError;
bool bCacheReady=TileCache->LoadExpected(Row.Candidate.Key,CacheOptions,Cached,CacheError);
if(!bCacheReady&&Row.Base)
bCacheReady=TileCache->StoreAndLoadExplicit(*Row.Base,CacheOptions,
TileCache->identity(),Cached,CacheError);
const bool bCacheSame=bCacheReady&&Row.Base
&&SameTileOutput(*Row.Base,Cached)
&&StandaloneTileCachePrototype::SameExactMesh(*Row.Base,Cached);
++CachePairs;
if(!bCacheSame)++CacheMismatches;
std::printf("[RouteParityPair] route=base/disk-cache key=(%d,%d,%d,lod%d) same_density=%d same_mesh=%d same_payload=%d same_topology=%d exact_arrays=%d status=%s error=%s\n",
Row.Candidate.Key.coordinate.x,Row.Candidate.Key.coordinate.y,
Row.Candidate.Key.coordinate.z,Row.Candidate.Key.lod,
Row.Base&&Cached.densityHash==Row.Base->densityHash?1:0,
Row.Base&&Cached.meshHash==Row.Base->meshHash?1:0,
Row.Base&&Cached.payloadHash==Row.Base->payloadHash?1:0,
Row.Base&&Cached.topologyHash==Row.Base->topologyHash?1:0,
bCacheSame?1:0,bCacheSame?"PASS":"FAIL",CacheError.c_str());
}
std::printf("[RouteParityPair] route=base/page key=(%d,%d,%d,lod%d) page_requested=%d page_verified=%d same_density=%d same_mesh=%d same_payload=%d same_topology=%d samples=%llu max_abs_density_delta=%.9g sign_mismatches=%llu edge_crossing_mismatches=%llu shared_surface_edges=%llu max_surface_delta_vox=%.9g exact_query_mismatches=%llu base_native_float=%llu page_native_float=%llu first_density=(%.9g,%.9g) status=%s error=%s\n",
Row.Candidate.Key.coordinate.x,Row.Candidate.Key.coordinate.y,
Row.Candidate.Key.coordinate.z,Row.Candidate.Key.lod,
@@ -1444,6 +961,27 @@ namespace StandaloneStreamBenchmark
&&EditedPage->diagnostics.analyticRegionPageRoute;
const bool bEditSame=EditedBase&&EditedPage&&bEditPageVerified
&&SameTileOutput(*EditedBase,*EditedPage);
bool bEditCacheSame=false;
if(TileCache&&EditedBase&&Applied)
{
VoxelForgeCore::TileMesh CachedEdited;
std::string CacheError;
const auto EditedIdentity=TileCache->WithEdit(Transaction.sequence,Applied->digest);
bEditCacheSame=TileCache->StoreAndLoadExplicit(*EditedBase,CacheOptions,
EditedIdentity,CachedEdited,CacheError)
&&SameTileOutput(*EditedBase,CachedEdited);
++EditCachePairs;
if(!bEditCacheSame)++EditCacheMismatches;
std::printf("[RouteParityPair] route=edited-base/disk-cache key=(%d,%d,%d,lod%d) edit_sequence=%llu edit_digest=0x%016llx same_density=%d same_mesh=%d same_payload=%d same_topology=%d exact_arrays=%d status=%s error=%s\n",
Key.coordinate.x,Key.coordinate.y,Key.coordinate.z,Key.lod,
static_cast<unsigned long long>(Transaction.sequence),
static_cast<unsigned long long>(Applied->digest),
CachedEdited.densityHash==EditedBase->densityHash?1:0,
CachedEdited.meshHash==EditedBase->meshHash?1:0,
CachedEdited.payloadHash==EditedBase->payloadHash?1:0,
CachedEdited.topologyHash==EditedBase->topologyHash?1:0,
bEditCacheSame?1:0,bEditCacheSame?"PASS":"FAIL",CacheError.c_str());
}
const bool bEditPass=Before&&Applied&&EditedBase&&bEditPageBuilt
&&bEditPageVerified&&bEditChanged&&bEditSame&&EditComparison.valid
&&EditComparison.exactQueryMismatches==0;
@@ -1541,11 +1079,13 @@ namespace StandaloneStreamBenchmark
&&HistoryPairs==(bHasCameraStep&&bRegionCrossing?1:0)&&HistoryMismatches==0
&&PageRoutesVerified==static_cast<int32>(Rows.size())
&&NativeRoutesVerified==NativePairs&&PageProofViolations==0
&&PageExactMismatches==0&&NativeExactMismatches==0;
std::printf("[RouteParityAudit] seed=%d page_pairs=%zu page_verified=%d page_mismatches=%d native_only_pairs=%d native_verified=%d native_mismatches=%d higher_lod_exact_pairs=%d higher_lod_exact_mismatches=%d edit_pairs=%d edit_mismatches=%d history_pairs=%d history_mismatches=%d exact_query_samples=%llu exact_query_mismatches=%llu page_density_samples=%llu max_abs_density_delta=%.9g mean_abs_density_delta=%.9g sign_mismatches=%llu edge_crossing_mismatches=%llu shared_surface_edges=%llu max_surface_delta_vox=%.9g mean_surface_delta_vox=%.9g page_proof_blocks=%llu page_proof_samples=%llu page_proof_fallbacks=%llu page_proof_unknown=%llu page_proof_violations=%llu status=%s\n",
&&PageExactMismatches==0&&NativeExactMismatches==0
&&(!TileCache||(CachePairs>0&&CacheMismatches==0&&EditCachePairs==1&&EditCacheMismatches==0));
std::printf("[RouteParityAudit] seed=%d page_pairs=%zu page_verified=%d page_mismatches=%d native_only_pairs=%d native_verified=%d native_mismatches=%d higher_lod_exact_pairs=%d higher_lod_exact_mismatches=%d edit_pairs=%d edit_mismatches=%d history_pairs=%d history_mismatches=%d cache_pairs=%d cache_mismatches=%d edit_cache_pairs=%d edit_cache_mismatches=%d exact_query_samples=%llu exact_query_mismatches=%llu page_density_samples=%llu max_abs_density_delta=%.9g mean_abs_density_delta=%.9g sign_mismatches=%llu edge_crossing_mismatches=%llu shared_surface_edges=%llu max_surface_delta_vox=%.9g mean_surface_delta_vox=%.9g page_proof_blocks=%llu page_proof_samples=%llu page_proof_fallbacks=%llu page_proof_unknown=%llu page_proof_violations=%llu status=%s\n",
World.Seed,Rows.size(),PageRoutesVerified,BasePageMismatches,
NativePairs,NativeRoutesVerified,NativeMismatches,ExactQueryPairs,
ExactQueryMismatches,EditPairs,EditMismatches,HistoryPairs,HistoryMismatches,
CachePairs,CacheMismatches,EditCachePairs,EditCacheMismatches,
static_cast<unsigned long long>(PageExactSamples
+NativeExactSamples+ExactQuerySamples),
static_cast<unsigned long long>(PageExactMismatches
@@ -2185,10 +1725,12 @@ namespace StandaloneStreamBenchmark
const double WholeViewSeconds=std::chrono::duration<double>(WholeViewReady-ColdStart).count();
const double StreamSeconds=std::chrono::duration<double>(WholeViewReady-StreamStart).count();
const double FirstTileSeconds=std::chrono::duration<double>(FirstTileReady-ColdStart).count();
std::printf("[StreamPipeline] workers=%d shape=%.3fs first_tile_ready=%.3fs neighborhood_mesh=%.3fs neighborhood_ready=%.3fs full_detail_ready=%.3fs whole_view_ready=%.3fs neighborhood_tiles=%d/27 full_detail_tiles=%d/%d whole_tiles=%d/%zu stream_wall=%.3fs cache_hits=0 full_payload=1\n",
const std::uint64_t TileCacheHits=TileCache?TileCache->hitCount():Streamer.GetCacheHits();
std::printf("[StreamPipeline] workers=%d shape=%.3fs first_tile_ready=%.3fs neighborhood_mesh=%.3fs neighborhood_ready=%.3fs full_detail_ready=%.3fs whole_view_ready=%.3fs neighborhood_tiles=%d/27 full_detail_tiles=%d/%d whole_tiles=%d/%zu stream_wall=%.3fs cache_hits=%llu full_payload=1\n",
WorkerCount,ShapeSeconds,FirstTileSeconds,NeighborhoodMeshSeconds,NeighborhoodSeconds,
FullDetailSeconds,WholeViewSeconds,NeighborhoodFinished,
FullDetailFinished,FullDetailExpected,Finished,Desired.Tiles.size(),StreamSeconds);
FullDetailFinished,FullDetailExpected,Finished,Desired.Tiles.size(),StreamSeconds,
static_cast<unsigned long long>(TileCacheHits));
if(bReportMeshCoverage)
std::printf("[PipelineMeshCoverage] tiles=%d nonempty_mesh_tiles=%llu indexed_triangles=%llu\n",
Finished,static_cast<unsigned long long>(WholeNonEmptyMeshTiles),
@@ -2284,10 +1826,28 @@ namespace StandaloneStreamBenchmark
static_cast<unsigned long long>(ExactDetailHash),
static_cast<unsigned long long>(ExactCollisionHash));
}
bool bTileCacheSafetyPassing=true;
if(TileCache)
{
std::string CacheSafetyError;
bTileCacheSafetyPassing=TileCache->RunSafetyControls(CacheOptions,CacheSafetyError);
if(!bTileCacheSafetyPassing)
std::fprintf(stderr,"[TileCacheSafety] failed: %s\n",CacheSafetyError.c_str());
TileCache->PrintSummary();
TileCache->MeasureDiskReads();
const std::uint64_t CacheBytes=TileCache->bytesOnDisk();
std::printf("[TileCacheBudget] bytes=%llu maximum=%llu status=%s\n",
static_cast<unsigned long long>(CacheBytes),
static_cast<unsigned long long>(StandaloneTileCachePrototype::MaximumDiskBytes),
CacheBytes<=StandaloneTileCachePrototype::MaximumDiskBytes?"PASS":"FAIL");
bTileCacheSafetyPassing=bTileCacheSafetyPassing
&&CacheBytes<=StandaloneTileCachePrototype::MaximumDiskBytes;
}
return NeighborhoodFinished==static_cast<int32>(Neighborhood.size())
&&FullDetailFinished==FullDetailExpected&&Finished==Update.DesiredTiles&&bHashesPassing
&&(!bProfileColumnOverlap||bColumnOverlapCapturePassing)
&&(!bExportRequested||bSceneExportPassing)&&bScreenSpaceGatePassing
&&(!bAuditUniformBlockProofs||BlockProofViolations==0)?0:6;
&&(!bAuditUniformBlockProofs||BlockProofViolations==0)
&&bTileCacheSafetyPassing?0:6;
}
} // namespace StandaloneStreamBenchmark
+14 -4
View File
@@ -67,6 +67,10 @@ struct FStandaloneCpuTile
};
using FStandaloneCoreTileRoute = std::function<std::optional<VoxelForgeCore::TileMesh>(
const VoxelForgeCore::World&,const VoxelForgeCore::TileKey&,
const VoxelForgeCore::TileGenerationOptions&,bool&,std::string&)>;
inline uint64 HashStandaloneMeshPayload(const FVoxelMeshData& Mesh)
{
uint64 Hash=14695981039346656037ull;
@@ -430,14 +434,16 @@ public:
VoxelForgeCore::World* InCoreWorld=nullptr,
bool bInCaptureColumnCoordinates=false,
int32 InLod8HorizonInteriorStepVoxels=0,
bool bInSharedColumnCache=true)
bool bInSharedColumnCache=true,
FStandaloneCoreTileRoute InCoreTileRoute={})
:World(&InWorld),WorkerCount(FMath::Clamp(InWorkerCount,1,16)),bHashDensity(bInHashDensity),
MeshCache(InMeshCache),MaxLevelFilter(InMaxLevelFilter),
CoreWorld(InCoreWorld),bSkipUvAndColors(bInSkipUvAndColors),bSkipMaterialGroups(bInSkipMaterialGroups),
bSkipUV(bInSkipUV),bSkipColors(bInSkipColors),
bCaptureColumnCoordinates(bInCaptureColumnCoordinates),
bSharedColumnCache(bInSharedColumnCache),
Lod8HorizonInteriorStepVoxels(std::max(0,InLod8HorizonInteriorStepVoxels))
Lod8HorizonInteriorStepVoxels(std::max(0,InLod8HorizonInteriorStepVoxels)),
CoreTileRoute(std::move(InCoreTileRoute))
{
VoxelGenLOD::InitializeConsoleSwitches();
UVoxelMarchingCubesMesher::InitializeConsoleSwitches();
@@ -830,8 +836,11 @@ private:
Options.diagnosticColumnInterpolationStride=
std::max<std::uint32_t>(1,DiagnosticCellStride);
std::string Error;
auto Result=CoreWorld->generateTile(
{{Job.Key.Coord.X,Job.Key.Coord.Y,Job.Key.Coord.Z},Job.Key.Level},Options,Error);
const VoxelForgeCore::TileKey CoreKey{{Job.Key.Coord.X,Job.Key.Coord.Y,Job.Key.Coord.Z},Job.Key.Level};
bool bDiskCacheHit=false;
auto Result=CoreTileRoute
?CoreTileRoute(*CoreWorld,CoreKey,Options,bDiskCacheHit,Error)
:CoreWorld->generateTile(CoreKey,Options,Error);
if(!Result)
{
std::fprintf(stderr,"[VoxelForgeCore] tile generation failed: %s\n",Error.c_str());
@@ -1003,6 +1012,7 @@ private:
bool bCaptureColumnCoordinates=false;
bool bSharedColumnCache=true;
int32 Lod8HorizonInteriorStepVoxels=0;
FStandaloneCoreTileRoute CoreTileRoute;
bool bProfileMesherStages=false;
bool bAuditUniformBlockProofs=false;
std::atomic<uint64> CacheHitCount{0};
@@ -322,7 +322,7 @@ namespace
const FVector ChunkCenter(
(ChunkCoord.X + 0.5f) * (float)CHUNK_SIZE,
(ChunkCoord.Y + 0.5f) * (float)CHUNK_SIZE,
(ChunkCoord.Z + 0.5f) * Manager->GetStrateLayoutChunkWidthVoxels());
(ChunkCoord.Z + 0.5f) * (float)CHUNK_SIZE);
const float ChunkRadius = (float)CHUNK_SIZE * 0.8660254f + 3.0f;
const TArray<FVoxelPassage>& Passages = Manager->GetPassages();
Cache.FloorProjections.SetNum(Passages.Num());
@@ -1104,7 +1104,7 @@ static bool VF_FindWalkableTunnelAir(
const FIntVector ChunkCoord(
FMath::FloorToInt(Position.X / (float)CHUNK_SIZE),
FMath::FloorToInt(Position.Y / (float)CHUNK_SIZE),
FMath::FloorToInt(Position.Z / Manager->GetStrateLayoutChunkWidthVoxels()));
FMath::FloorToInt(Position.Z / (float)CHUNK_SIZE));
const TArray<int32>& Nearby = VF_GetNearbyPassages(Manager, ChunkCoord);
const TArray<FVoxelPassage>& Passages = Manager->GetPassages();
const FVoxelPassage* PassageData = Passages.GetData();
@@ -1139,7 +1139,7 @@ static bool VF_IsAnyPassageFloorAt(
const FIntVector ChunkCoord(
FMath::FloorToInt(Position.X / (float)CHUNK_SIZE),
FMath::FloorToInt(Position.Y / (float)CHUNK_SIZE),
FMath::FloorToInt(Position.Z / Manager->GetStrateLayoutChunkWidthVoxels()));
FMath::FloorToInt(Position.Z / (float)CHUNK_SIZE));
const TArray<int32>& Nearby = VF_GetNearbyPassages(Manager, ChunkCoord);
const TArray<FVoxelPassage>& Passages = Manager->GetPassages();
const FVoxelPassage* PassageData = Passages.GetData();
@@ -1170,17 +1170,6 @@ bool UVoxelStrateManager::Initialize(UVoxelSettings* Settings, int32 WorldSeed)
UE_LOG(LogTemp, Error, TEXT("[StrateManager] No settings provided!"));
return false;
}
if (!FMath::IsFinite(Settings->StrateLayoutChunkSizeMeters)
|| Settings->StrateLayoutChunkSizeMeters < 0.25f
|| Settings->StrateLayoutChunkSizeMeters > 64.0f)
{
UE_LOG(LogTemp, Error, TEXT("[StrateManager] StrateLayoutChunkSizeMeters must be in [0.25, 64] m."));
return false;
}
StrateLayoutChunkSizeMicrometres = static_cast<uint32>(std::llround(
static_cast<double>(Settings->StrateLayoutChunkSizeMeters) * 1000000.0));
StrateLayoutChunkWidthVoxels = static_cast<float>(
static_cast<double>(StrateLayoutChunkSizeMicrometres) / (10000.0 * VOXEL_SIZE));
FVoxelSeasonManifest SeasonManifest;
bool bUseSeason = false;
@@ -1354,10 +1343,10 @@ bool UVoxelStrateManager::Initialize(UVoxelSettings* Settings, int32 WorldSeed)
Slot.Definition->FloatingIslandParams = SeasonStrate.Params.FloatingIslandParams;
Slot.HeightInChunks = SeasonStrate.HeightInChunks;
Slot.TopChunkZ = SeasonStrate.TopWorldZ / FMath::RoundToInt(StrateLayoutChunkWidthVoxels) - 1;
Slot.BottomChunkZ = SeasonStrate.BottomWorldZ / FMath::RoundToInt(StrateLayoutChunkWidthVoxels);
if (SeasonStrate.TopWorldZ % FMath::RoundToInt(StrateLayoutChunkWidthVoxels) != 0
|| SeasonStrate.BottomWorldZ % FMath::RoundToInt(StrateLayoutChunkWidthVoxels) != 0
Slot.TopChunkZ = SeasonStrate.TopWorldZ / CHUNK_SIZE - 1;
Slot.BottomChunkZ = SeasonStrate.BottomWorldZ / CHUNK_SIZE;
if (SeasonStrate.TopWorldZ % CHUNK_SIZE != 0
|| SeasonStrate.BottomWorldZ % CHUNK_SIZE != 0
|| Slot.TopChunkZ != CurrentTopZ
|| Slot.BottomChunkZ != CurrentTopZ - (Slot.HeightInChunks - 1))
{
@@ -1537,8 +1526,8 @@ bool UVoxelStrateManager::SetComposerOverrideForStrate(
}
VF_SetComposerRuntimeBounds(
Override->Params,
(float)(TargetSlot->TopChunkZ + 1) * StrateLayoutChunkWidthVoxels,
(float)TargetSlot->BottomChunkZ * StrateLayoutChunkWidthVoxels);
(float)(TargetSlot->TopChunkZ + 1) * CHUNK_SIZE,
(float)TargetSlot->BottomChunkZ * CHUNK_SIZE);
Override->bUseRecipe = bUseRecipe;
if (Recipe != nullptr)
{
@@ -1557,8 +1546,8 @@ bool UVoxelStrateManager::SetComposerOverrideForStrate(
Override->bUseRegions = true;
Override->Regions = *InRegions;
VF_RekeyStrateRegionManifest(Override->Regions, CandidateSeed, StrateIndex);
Override->Regions.StrateTopWorldZ = (float)(TargetSlot->TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
Override->Regions.StrateBottomWorldZ = (float)TargetSlot->BottomChunkZ * StrateLayoutChunkWidthVoxels;
Override->Regions.StrateTopWorldZ = (float)(TargetSlot->TopChunkZ + 1) * CHUNK_SIZE;
Override->Regions.StrateBottomWorldZ = (float)TargetSlot->BottomChunkZ * CHUNK_SIZE;
VF_SetStrateArchetypeRuntimeBounds(Override->Params,
Override->Regions.StrateTopWorldZ,
Override->Regions.StrateBottomWorldZ);
@@ -1808,11 +1797,11 @@ void UVoxelStrateManager::GeneratePassages()
const FStratePassageConfig& Cfg = UpperDef->PassageConfig;
// Upper strate floor and lower strate ceiling (differ when there's a bedrock gap).
const float UpperTopZ = (float)(Upper.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
const float UpperBottomZ = (float)(Upper.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
const float LowerTopZ = (float)(Lower.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
const float UpperMax = (float)Upper.HeightInChunks * StrateLayoutChunkWidthVoxels * 0.9f;
const float LowerMax = (float)Lower.HeightInChunks * StrateLayoutChunkWidthVoxels * 0.9f;
const float UpperTopZ = (float)(Upper.TopChunkZ + 1) * CHUNK_SIZE;
const float UpperBottomZ = (float)(Upper.BottomChunkZ) * CHUNK_SIZE;
const float LowerTopZ = (float)(Lower.TopChunkZ + 1) * CHUNK_SIZE;
const float UpperMax = (float)Upper.HeightInChunks * CHUNK_SIZE * 0.9f;
const float LowerMax = (float)Lower.HeightInChunks * CHUNK_SIZE * 0.9f;
const float DistLo = FMath::Min(Cfg.DistanceMin, Cfg.DistanceMax);
const float DistHi = FMath::Max(Cfg.DistanceMin, Cfg.DistanceMax);
@@ -1942,7 +1931,7 @@ void UVoxelStrateManager::GeneratePassages()
LowerDef->FloatingIslandParams,
LowerQuerySeed,
LowerTopZ,
(float)(Lower.BottomChunkZ) * StrateLayoutChunkWidthVoxels,
(float)(Lower.BottomChunkZ) * CHUNK_SIZE,
PX,
PY,
MaxLateralSnap,
@@ -2002,7 +1991,7 @@ void UVoxelStrateManager::GeneratePassages()
if (bAimedLowerAtPlayerFitPoint)
{
const float LowerSealThickness = BoundarySealThicknessFor(*LowerDef);
const float LowerBottomZ = (float)(Lower.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
const float LowerBottomZ = (float)(Lower.BottomChunkZ) * CHUNK_SIZE;
const float InnerBottomZ = LowerBottomZ + LowerSealThickness;
const float InnerTopZ = LowerTopZ - LowerSealThickness;
if (VoxelMath::IsFinite(SuggestedLowerPoint.X)
@@ -2170,7 +2159,7 @@ void UVoxelStrateManager::GeneratePassages()
Cfg.MouthRadius,
LowerDoorDirection,
LowerTopZ,
(float)(Lower.BottomChunkZ) * StrateLayoutChunkWidthVoxels,
(float)(Lower.BottomChunkZ) * CHUNK_SIZE,
LowerDef ? BoundarySealThicknessFor(*LowerDef) : 0.0f,
bAimedLowerAtPlayerFitPoint);
Passage.UpperPoint = Passage.UpperLanding.StandingPoint;
@@ -2595,8 +2584,8 @@ void UVoxelStrateManager::GeneratePassages()
if (bOpenSurfaceEntry && OriginSpineRadius > 0.0f && StrateLayout.Num() > 0)
{
const FStrateSlot& Top = StrateLayout[0];
const float TopZ = (float)(Top.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
const float BottomZ = (float)Top.BottomChunkZ * StrateLayoutChunkWidthVoxels;
const float TopZ = (float)(Top.TopChunkZ + 1) * CHUNK_SIZE;
const float BottomZ = (float)Top.BottomChunkZ * CHUNK_SIZE;
const float TopSeal = Top.Definition
? BoundarySealThicknessFor(*Top.Definition) : 0.0f;
const VoxelPassageGeometry::FOriginLandingGeometry OriginLanding =
@@ -2619,7 +2608,7 @@ void UVoxelStrateManager::GeneratePassages()
// the top seal into the finite landing room; lower strate seals remain untouched.
Entry.Radius = FMath::Max(OriginSpineRadius,
VoxelPassageGeometry::MetersToVoxels(0.25f));
Entry.UpperPoint = FVector(0.0f, 0.0f, TopZ + StrateLayoutChunkWidthVoxels);
Entry.UpperPoint = FVector(0.0f, 0.0f, TopZ + CHUNK_SIZE);
// The capsule's lower tangent meets the room ceiling; it never bores through the
// room's floor or creates an origin column in strate 0.
Entry.LowerPoint = FVector(
@@ -2683,7 +2672,7 @@ float UVoxelStrateManager::EvaluateModifierSDF(float WorldX, float WorldY, float
const FIntVector ChunkCoord(
FMath::FloorToInt(WorldX / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldY / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldZ / StrateLayoutChunkWidthVoxels));
FMath::FloorToInt(WorldZ / (float)CHUNK_SIZE));
// The shortlist is rebuilt once for a (manager, version, chunk) and is shared by the tube,
// landing, and floor paths. No source-fit stencil or topology search is allowed below it.
@@ -2829,7 +2818,7 @@ void UVoxelStrateManager::ApplyPassageModifier(
const FIntVector ChunkCoord(
FMath::FloorToInt(WorldX / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldY / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldZ / StrateLayoutChunkWidthVoxels));
FMath::FloorToInt(WorldZ / (float)CHUNK_SIZE));
const TArray<int32>& Nearby = VF_GetNearbyPassages(this, ChunkCoord);
const FVoxelPassage* PassageData = Passages.GetData();
const FVector Position(WorldX, WorldY, WorldZ);
@@ -2922,7 +2911,7 @@ void UVoxelStrateManager::ApplyPassageLandingAir(
const FIntVector ChunkCoord(
FMath::FloorToInt(WorldX / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldY / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldZ / StrateLayoutChunkWidthVoxels));
FMath::FloorToInt(WorldZ / (float)CHUNK_SIZE));
const TArray<int32>& Nearby = VF_GetNearbyPassages(this, ChunkCoord);
if (Nearby.Num() == 0) return;
@@ -3033,7 +3022,7 @@ void UVoxelStrateManager::ApplyPassageLandingFloorMC(
const FIntVector ChunkCoord(
FMath::FloorToInt(WorldX / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldY / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldZ / StrateLayoutChunkWidthVoxels));
FMath::FloorToInt(WorldZ / (float)CHUNK_SIZE));
const TArray<int32>& Nearby = VF_GetNearbyPassages(this, ChunkCoord);
const FVoxelPassage* PassageData = Passages.GetData();
const FVector Position(WorldX, WorldY, WorldZ);
@@ -3129,7 +3118,7 @@ void UVoxelStrateManager::ApplyPassageStructuralPostsMC(
const FIntVector ChunkCoord(
FMath::FloorToInt(WorldX / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldY / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldZ / StrateLayoutChunkWidthVoxels));
FMath::FloorToInt(WorldZ / (float)CHUNK_SIZE));
const TArray<int32>& Nearby = VF_GetNearbyPassages(this, ChunkCoord);
if (Nearby.Num() == 0) return;
@@ -3256,7 +3245,7 @@ void UVoxelStrateManager::ApplyPassageNativeFloorMC(
const FIntVector ChunkCoord(
FMath::FloorToInt(WorldX / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldY / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldZ / StrateLayoutChunkWidthVoxels));
FMath::FloorToInt(WorldZ / (float)CHUNK_SIZE));
const TArray<int32>& Nearby = VF_GetNearbyPassages(this, ChunkCoord);
if (Nearby.Num() == 0
|| VoxelPassageGeometry::VerticalShaftConnectorAirMarker())
@@ -3447,7 +3436,7 @@ void UVoxelStrateManager::ApplyPassageLandingRoomFloorMC(
const FIntVector ChunkCoord(
FMath::FloorToInt(WorldX / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldY / (float)CHUNK_SIZE),
FMath::FloorToInt(WorldZ / StrateLayoutChunkWidthVoxels));
FMath::FloorToInt(WorldZ / (float)CHUNK_SIZE));
const TArray<int32>& Nearby = VF_GetNearbyPassages(this, ChunkCoord);
const FVoxelPassage* PassageData = Passages.GetData();
const FVector Position(WorldX, WorldY, WorldZ);
@@ -5921,8 +5910,8 @@ bool UVoxelStrateManager::AnyLandingFloorAtLattice(
for (const FStrateSlot& Slot : StrateLayout)
{
if (Slot.Definition == nullptr) continue;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * StrateLayoutChunkWidthVoxels;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * CHUNK_SIZE;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * CHUNK_SIZE;
const float Seal = VF_BoundarySealThicknessForDefinition(*Slot.Definition);
const VoxelPassageGeometry::FOriginLandingGeometry Geometry =
VoxelPassageGeometry::BuildOriginLandingGeometry(
@@ -5964,8 +5953,8 @@ bool UVoxelStrateManager::AnyOriginLandingNearBox(
for (const FStrateSlot& Slot : StrateLayout)
{
if (Slot.Definition == nullptr) continue;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * StrateLayoutChunkWidthVoxels;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * CHUNK_SIZE;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * CHUNK_SIZE;
if (VoxelPassageGeometry::OriginLandingRoomTouchesBox(
VoxelBox, TopZ, BottomZ,
VF_BoundarySealThicknessForDefinition(*Slot.Definition),
@@ -5985,8 +5974,8 @@ bool UVoxelStrateManager::AnyOriginLandingFloorNearBox(
for (const FStrateSlot& Slot : StrateLayout)
{
if (Slot.Definition == nullptr) continue;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * StrateLayoutChunkWidthVoxels;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * CHUNK_SIZE;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * CHUNK_SIZE;
if (VoxelPassageGeometry::OriginLandingFloorTouchesBox(
VoxelBox, TopZ, BottomZ,
VF_BoundarySealThicknessForDefinition(*Slot.Definition),
@@ -6010,8 +5999,8 @@ bool UVoxelStrateManager::AnyOriginLandingNearLattice(
for (const FStrateSlot& Slot : StrateLayout)
{
if (Slot.Definition == nullptr) continue;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * StrateLayoutChunkWidthVoxels;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * CHUNK_SIZE;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * CHUNK_SIZE;
const float Seal = VF_BoundarySealThicknessForDefinition(*Slot.Definition);
if (VoxelPassageGeometry::OriginLandingRoomTouchesLattice(
VoxelBox, LatticeOrigin, Step, TopZ, BottomZ, Seal, OriginSpineRadius,
@@ -6048,8 +6037,8 @@ bool UVoxelStrateManager::AnyOriginLandingAirNearLattice(
{
continue;
}
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * StrateLayoutChunkWidthVoxels;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * CHUNK_SIZE;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * CHUNK_SIZE;
const float Seal = VF_BoundarySealThicknessForDefinition(*Slot.Definition);
const VoxelPassageGeometry::FOriginLandingGeometry Geometry =
VoxelPassageGeometry::BuildOriginLandingGeometry(
@@ -6125,8 +6114,8 @@ bool UVoxelStrateManager::AnyOriginLandingFloorNearLattice(
for (const FStrateSlot& Slot : StrateLayout)
{
if (Slot.Definition == nullptr) continue;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * StrateLayoutChunkWidthVoxels;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
const float TopZ = (static_cast<float>(Slot.TopChunkZ) + 1.0f) * CHUNK_SIZE;
const float BottomZ = static_cast<float>(Slot.BottomChunkZ) * CHUNK_SIZE;
const float Seal = VF_BoundarySealThicknessForDefinition(*Slot.Definition);
if (VoxelPassageGeometry::OriginLandingFloorTouchesLattice(
VoxelBox, LatticeOrigin, Step, TopZ, BottomZ, Seal, OriginSpineRadius))
@@ -6160,7 +6149,7 @@ int32 UVoxelStrateManager::FindSlotIndexForChunkZ(int32 ChunkZ) const
UVoxelStrateDefinition* UVoxelStrateManager::GetStrateAt(float WorldZ) const
{
// Convert world Z to chunk Z coordinate
int32 ChunkZ = FMath::FloorToInt((WorldZ / VOXEL_SIZE) / StrateLayoutChunkWidthVoxels);
int32 ChunkZ = FMath::FloorToInt((WorldZ / VOXEL_SIZE) / CHUNK_SIZE);
int32 SlotIdx = FindSlotIndexForChunkZ(ChunkZ);
if (SlotIdx >= 0)
{
@@ -6171,7 +6160,7 @@ UVoxelStrateDefinition* UVoxelStrateManager::GetStrateAt(float WorldZ) const
int32 UVoxelStrateManager::GetStrateIndex(float WorldZ) const
{
int32 ChunkZ = FMath::FloorToInt((WorldZ / VOXEL_SIZE) / StrateLayoutChunkWidthVoxels);
int32 ChunkZ = FMath::FloorToInt((WorldZ / VOXEL_SIZE) / CHUNK_SIZE);
int32 SlotIdx = FindSlotIndexForChunkZ(ChunkZ);
if (SlotIdx >= 0)
{
@@ -6330,9 +6319,9 @@ FSlabGenerationParams UVoxelStrateManager::GetSlabParamsForChunk(const FIntVecto
// Fill in the runtime Z bounds (voxel coordinates, same convention as
// FStrateGenerationParams::StrateTopWorldZ / StrateBottomWorldZ).
// TopChunkZ+1 because the top chunk's CEILING is at (TopChunkZ+1)*StrateLayoutChunkWidthVoxels.
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
Result.StrateBottomWorldZ = (float)(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
// TopChunkZ+1 because the top chunk's CEILING is at (TopChunkZ+1)*CHUNK_SIZE.
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
Result.StrateBottomWorldZ = (float)(Slot.BottomChunkZ) * CHUNK_SIZE;
return Result;
}
@@ -6365,8 +6354,8 @@ FMazeGenerationParams UVoxelStrateManager::GetMazeParamsForChunk(const FIntVecto
}
}
#endif
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * StrateLayoutChunkWidthVoxels;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * CHUNK_SIZE;
return Result;
}
@@ -6392,8 +6381,8 @@ FSurfaceGenerationParams UVoxelStrateManager::GetSurfaceParamsForChunk(const FIn
}
}
#endif
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * StrateLayoutChunkWidthVoxels;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * CHUNK_SIZE;
return Result;
}
@@ -6419,8 +6408,8 @@ FVerticalShaftParams UVoxelStrateManager::GetVerticalShaftParamsForChunk(const F
}
}
#endif
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * StrateLayoutChunkWidthVoxels;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * CHUNK_SIZE;
return Result;
}
@@ -6446,8 +6435,8 @@ FFloatingIslandParams UVoxelStrateManager::GetFloatingIslandParamsForChunk(const
}
}
#endif
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * StrateLayoutChunkWidthVoxels;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * CHUNK_SIZE;
return Result;
}
@@ -6481,14 +6470,14 @@ FBiomeContext UVoxelStrateManager::GetBiomeContextForChunk(const FIntVector& Chu
bool UVoxelStrateManager::GetStrateUnrealZRange(float WorldZ, float& OutTopZ, float& OutBottomZ) const
{
const int32 ChunkZ = FMath::FloorToInt((WorldZ / VOXEL_SIZE) / StrateLayoutChunkWidthVoxels);
const int32 ChunkZ = FMath::FloorToInt((WorldZ / VOXEL_SIZE) / CHUNK_SIZE);
const int32 SlotIdx = FindSlotIndexForChunkZ(ChunkZ);
if (SlotIdx < 0) return false;
const FStrateSlot& Slot = StrateLayout[SlotIdx];
// Voxel-space Z bounds → Unreal units. Ceiling = top chunk's upper edge.
OutTopZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels * VOXEL_SIZE;
OutBottomZ = (float)(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels * VOXEL_SIZE;
OutTopZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE * VOXEL_SIZE;
OutBottomZ = (float)(Slot.BottomChunkZ) * CHUNK_SIZE * VOXEL_SIZE;
return true;
}
@@ -6501,8 +6490,8 @@ FStrateDisturbanceParams UVoxelStrateManager::GetDisturbanceParamsForChunk(const
}
const FStrateSlot& Slot = StrateLayout[SlotIdx];
FStrateDisturbanceParams Result = Slot.Definition->Disturbances;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
Result.StrateBottomWorldZ = (float)(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
Result.StrateBottomWorldZ = (float)(Slot.BottomChunkZ) * CHUNK_SIZE;
return Result;
}
@@ -6534,8 +6523,8 @@ float UVoxelStrateManager::GetWaterLevelWorldZForChunk(const FIntVector& ChunkCo
}
if (Rel <= 0.0f) return -FLT_MAX;
const float BottomZ = (float)(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
const float TopZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
const float BottomZ = (float)(Slot.BottomChunkZ) * CHUNK_SIZE;
const float TopZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
return FMath::Lerp(BottomZ, TopZ, FMath::Clamp(Rel, 0.0f, 1.0f));
}
@@ -6579,8 +6568,8 @@ FStrateGenerationParams UVoxelStrateManager::GetGenerationParams(const FIntVecto
FindComposerOverride(Slot.StrateIndex))
{
FStrateGenerationParams Result = Override->Params.TunnelNetworkParams;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * StrateLayoutChunkWidthVoxels;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * CHUNK_SIZE;
// A candidate is a hard replacement of this slot. Do not blend its rolled vector with an
// authored neighbour at a boundary; this is also how the offline fixture measures it.
return ResolveFinalParams(Result);
@@ -6590,8 +6579,8 @@ FStrateGenerationParams UVoxelStrateManager::GetGenerationParams(const FIntVecto
if (SeasonStrates.IsValidIndex(SlotIdx))
{
FStrateGenerationParams Result = SeasonStrates[SlotIdx].Params.TunnelNetworkParams;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * StrateLayoutChunkWidthVoxels;
Result.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
Result.StrateBottomWorldZ = (float)Slot.BottomChunkZ * CHUNK_SIZE;
// Season vectors are already final, measured slot records. Vertical structural posts own
// their boundary; blending them with another selected recipe would describe neither one.
return ResolveFinalParams(Result);
@@ -6606,17 +6595,10 @@ FStrateGenerationParams UVoxelStrateManager::GetGenerationParams(const FIntVecto
// to seal the top and bottom with solid rock. This prevents caves from
// carving through strate boundaries.
//
// TopChunkZ=0: top of the strate is one resolved layout chunk above zero.
// TopChunkZ=0, CHUNK_SIZE=32: top of the strate = chunk 0's top edge = voxel Z=32
// BottomChunkZ=-3: bottom of the strate = chunk -3's bottom edge = voxel Z=-3*32 = -96
BaseParams.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
BaseParams.StrateBottomWorldZ = (float)(Slot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
// Core composes one field per strate. For this assembly, Gradient and Interleaved
// metadata use the declared Hard fallback across legacy parameter lookups too.
if (bHardTransitionFallbackForAssembly)
{
return ResolveFinalParams(BaseParams);
}
BaseParams.StrateTopWorldZ = (float)(Slot.TopChunkZ + 1) * CHUNK_SIZE;
BaseParams.StrateBottomWorldZ = (float)(Slot.BottomChunkZ) * CHUNK_SIZE;
//=========================================================================
// BOUNDARY BLENDING (transition-type aware)
@@ -6689,8 +6671,8 @@ FStrateGenerationParams UVoxelStrateManager::GetGenerationParams(const FIntVecto
if (EffectiveBlend > 0 && DistFromBottom < EffectiveBlend)
{
FStrateGenerationParams BelowParams = BuildParamsFromDefinition(BelowSlot.Definition);
BelowParams.StrateTopWorldZ = (float)(BelowSlot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
BelowParams.StrateBottomWorldZ = (float)(BelowSlot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
BelowParams.StrateTopWorldZ = (float)(BelowSlot.TopChunkZ + 1) * CHUNK_SIZE;
BelowParams.StrateBottomWorldZ = (float)(BelowSlot.BottomChunkZ) * CHUNK_SIZE;
// Linear alpha: 0 at EffectiveBlend chunks away, 1 at the boundary
float Alpha = 1.0f - ((float)DistFromBottom / (float)EffectiveBlend);
@@ -6727,8 +6709,8 @@ FStrateGenerationParams UVoxelStrateManager::GetGenerationParams(const FIntVecto
if (DistFromBottom < CheckRange)
{
FStrateGenerationParams BelowParams = BuildParamsFromDefinition(BelowSlot.Definition);
BelowParams.StrateTopWorldZ = (float)(BelowSlot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
BelowParams.StrateBottomWorldZ = (float)(BelowSlot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
BelowParams.StrateTopWorldZ = (float)(BelowSlot.TopChunkZ + 1) * CHUNK_SIZE;
BelowParams.StrateBottomWorldZ = (float)(BelowSlot.BottomChunkZ) * CHUNK_SIZE;
// Sample 3D Perlin noise to warp the boundary position.
// XY frequency 0.15 gives medium-scale variation (~6-7 chunks per cycle).
@@ -6788,8 +6770,8 @@ FStrateGenerationParams UVoxelStrateManager::GetGenerationParams(const FIntVecto
if (EffectiveBlend > 0 && DistFromTop < EffectiveBlend)
{
FStrateGenerationParams AboveParams = BuildParamsFromDefinition(AboveSlot.Definition);
AboveParams.StrateTopWorldZ = (float)(AboveSlot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
AboveParams.StrateBottomWorldZ = (float)(AboveSlot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
AboveParams.StrateTopWorldZ = (float)(AboveSlot.TopChunkZ + 1) * CHUNK_SIZE;
AboveParams.StrateBottomWorldZ = (float)(AboveSlot.BottomChunkZ) * CHUNK_SIZE;
float Alpha = 1.0f - ((float)DistFromTop / (float)EffectiveBlend);
Alpha = FMath::Clamp(Alpha, 0.0f, 1.0f);
@@ -6810,8 +6792,8 @@ FStrateGenerationParams UVoxelStrateManager::GetGenerationParams(const FIntVecto
if (DistFromTop < CheckRange)
{
FStrateGenerationParams AboveParams = BuildParamsFromDefinition(AboveSlot.Definition);
AboveParams.StrateTopWorldZ = (float)(AboveSlot.TopChunkZ + 1) * StrateLayoutChunkWidthVoxels;
AboveParams.StrateBottomWorldZ = (float)(AboveSlot.BottomChunkZ) * StrateLayoutChunkWidthVoxels;
AboveParams.StrateTopWorldZ = (float)(AboveSlot.TopChunkZ + 1) * CHUNK_SIZE;
AboveParams.StrateBottomWorldZ = (float)(AboveSlot.BottomChunkZ) * CHUNK_SIZE;
// Same noise function but with a different seed offset to avoid
// symmetry between top and bottom boundaries of adjacent strates
@@ -41,27 +41,21 @@
// SealFactor > 0 et BaseDensity > 0, le résultat est solide GARANTI quelle qu'ait été l'entrée.
// C'est exactement ce qu'encode `IVoxelDensityOp::ClassifyBox` (voir VoxelDensityOp.h), et la
// raison pour laquelle cette méthode existe.
FORCEINLINE void VF_ApplyUpperBoundarySealValue(float& Density, float WorldZ,
float StrateTopZ, float Thickness, float BaseDensity)
{
const float DistTop = StrateTopZ - WorldZ;
if (DistTop >= 0.0f && DistTop < Thickness)
{
float SealFactor = 1.0f - (DistTop / Thickness);
SealFactor = SmoothStep01(SealFactor);
Density = FMath::Max(Density, SealFactor * BaseDensity);
}
}
FORCEINLINE void VF_ApplyBoundarySeal(float& Density, float WorldZ,
float StrateTopZ, float StrateBottomZ,
float Thickness, float BaseDensity)
{
if (VoxelDensityAblation::IsBoundarySealOff() || Thickness <= 0.0f) return;
const float DistTop = StrateTopZ - WorldZ; // + si on est sous le plafond
const float DistBot = WorldZ - StrateBottomZ; // + si on est au-dessus du sol
VF_ApplyUpperBoundarySealValue(Density, WorldZ, StrateTopZ, Thickness, BaseDensity);
if (DistTop >= 0.0f && DistTop < Thickness)
{
float SealFactor = 1.0f - (DistTop / Thickness);
SealFactor = SmoothStep01(SealFactor);
Density = FMath::Max(Density, SealFactor * BaseDensity);
}
if (DistBot >= 0.0f && DistBot < Thickness)
{
float SealFactor = 1.0f - (DistBot / Thickness);
@@ -70,16 +64,6 @@ FORCEINLINE void VF_ApplyBoundarySeal(float& Density, float WorldZ,
}
}
// The same structural seal, limited to a strate's upper boundary. Native finite fields use this
// when their lower boundary intentionally has no seal; keeping the math here makes that ceiling
// use the same shared density primitive as every two-sided strate seal.
FORCEINLINE void VF_ApplyUpperBoundarySeal(float& Density, float WorldZ,
float StrateTopZ, float Thickness, float BaseDensity)
{
if (VoxelDensityAblation::IsBoundarySealOff() || Thickness <= 0.0f) return;
VF_ApplyUpperBoundarySealValue(Density, WorldZ, StrateTopZ, Thickness, BaseDensity);
}
//=============================================================================
// CARVE DE PASSAGE / PASSAGE CARVING
//=============================================================================
@@ -391,11 +391,6 @@ public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Voxel|Strates", meta = (ClampMin = "0", ClampMax = "16"))
int32 InterStrateGapChunks = 0;
// Physical width of one vertical strate-layout chunk, independent of Core's 32^3 tile.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Voxel|Strates|World Assembly",
meta = (ClampMin = "0.25", ClampMax = "64.0", Units = "m"))
float StrateLayoutChunkSizeMeters = 8.0f;
//=========================================================================
// SPINE & INTER-STRATE CONNECTIONS (the (0,0) descent axis)
//=========================================================================
@@ -234,10 +234,6 @@ public:
*/
UFUNCTION(BlueprintCallable, Category = "Strate")
UVoxelStrateDefinition* GetStrateAt(float WorldZ) const;
float GetStrateLayoutChunkWidthVoxels() const { return StrateLayoutChunkWidthVoxels; }
uint32 GetStrateLayoutChunkSizeMicrometres() const { return StrateLayoutChunkSizeMicrometres; }
void SetHardTransitionFallbackForAssembly(bool bEnabled)
{ bHardTransitionFallbackForAssembly = bEnabled; }
/**
* Get the strate index at a world Z coordinate.
@@ -496,10 +492,6 @@ protected:
// The stacked strate layout (index 0 = topmost strate)
UPROPERTY()
TArray<FStrateSlot> StrateLayout;
// Resolved once from VoxelSettings::StrateLayoutChunkSizeMeters during Initialize().
float StrateLayoutChunkWidthVoxels = 32.0f;
uint32 StrateLayoutChunkSizeMicrometres = 8000000;
bool bHardTransitionFallbackForAssembly = false;
// Parallel to StrateLayout only while a cooked season is active. Plain immutable data is
// copied into worker-local caches on the existing layout-versioned refetch path.
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more