16 KiB
Architecture
This document describes the system as it exists in this checkout, plus the product vision that motivates it. For implementation-level detail see:
voxel-cache.md— pages, pointers, requests, eviction, tables.shaders.md— Slang/WGSL shader architecture and compilation.pipeline-and-producers.md— how data gets into the cache.
Temporary code:
src/main.rsandsrc/producers.rsare a playground/test harness built alongside the cache. They contain hardcoded parameters and blocking workarounds. Do not treat them as stable architecture, public API, or examples of intended concurrency. The durable system issrc/voxel_cache/*andshaders/.
1. What this project is
A Rust + wgpu voxel renderer built around a GPU-resident sparse voxel cache (GigaVoxels-style: Crassin et al.). The tree is a 4×4×4 N-tree — every node has 64 children — and nodes are stored in flat GPU page pools rather than a separate brick pool.
The renderer's goal is to display very large, addressable worlds while only a small working set of voxels is resident on the GPU. Rendering, request generation, page insertion, and eviction all run on the GPU; the CPU orchestrates passes and fulfils producer requests.
Product vision
- Voxel size around pebble scale (~5–10 cm) near the player.
- Render distance of tens of kilometres, with several valleys and mountain ranges visible at once.
- Billions to hundreds of billions of addressable voxels, with only a small working set resident.
- Interactive frame rates (the original target was ~60 fps at 1440p on mid-range hardware) with a stylized-voxel look but realistic large-scale terrain structure.
- Longer term: a renderer a real game can be built on — dynamic edits, entities, water, vegetation, lighting, tooling, a stable API.
Architectural principles
These principles are the yardstick for changes. They are not all satisfied yet.
- GPU-driven, CPU-light. The CPU orchestrates; it must not iterate over voxels or per-frame visibility. Prefer indirect dispatch and GPU-side compaction of request lists.
- Working-set bound, not world-size bound. Cost must scale with screen pixels and cache size, never with total world size. Flag anything that violates this.
- LOD is native to the structure. Ray marching terminates at a level chosen by projected voxel size (about one pixel or less). Coarser levels must carry well-filtered data.
- Asynchronous and latency-tolerant. Missing data must never stall the frame. Render with the best available coarser level and refine as data arrives. Avoid visible popping where possible (blending, hysteresis, prioritisation by screen coverage and distance).
- Producers are pluggable. The renderer only knows "request node/brick X at level L, give me payload". Procedural terrain, heightmap-derived data, edited chunks, and baked/disk-streamed data should sit behind the same interface.
- Measure first. No optimisation advice without a way to measure it (timestamp queries, counters in a debug buffer, RenderDoc/Nsight/RGP captures). Suggest instrumentation before suggesting rewrites.
Roadmap context
The roadmap below is from the original project notes and is not a commitment. Treat it as direction, not a specification.
- Near term: stabilise the cache + request pipeline, lighting/shadows, atmosphere, a real terrain producer, camera-relative coordinates.
- Mid term: world edits, entities and depth compositing, TAA, vegetation/props.
- Long term: engine API, tooling, physics integration, disk streaming.
2. Current state at a glance
Implemented and wired into the running demo:
- GPU voxel cache with 4×4×4 branching and configurable page/request counts.
- GPU-emitted requests based on per-child counters, top-K selection, and a descending radix sort.
- Page recycling driven by LRU timestamps, with deepest-first depth ties (see
voxel-cache.md). - External (structure-table) and internal (cache) insertion modes.
- Structure tables: a fixed dense table and a toroidal wrapper for an "infinite" block of chunks around the camera.
- Slang ray-marching shaders with pixel-footprint LOD, compiled ahead of time.
- WGSL cache-management shaders, specialised at runtime with generated constants.
- Procedural fixtures (
SdfGenerator,TerrainGenerator,BallGenerator) and a blocking host request-fulfilment loop inmain.rs.
Not wired in: the production/ subsystem, tree.rs, the older
host_production.rs trait, and VoxelGiPipeline (module compiles but is never
instantiated). See the module map below.
3. High-level data flow
flowchart LR
Cam[Camera / window] --> Render[Render compute pass<br/>voxel.slang]
Render -->|reads| Cache[(Voxel cache pages)]
Render -->|reads| Table[(Structure table)]
Render -->|increments| Req[(Per-page request counters)]
Table -->|increments| TReq[(Table request counters)]
Req --> Gather[gather_requests<br/>top-K + radix sort]
TReq --> TGather[table gather_requests]
Gather --> RBuffer[(Request buffer<br/>structure_id, anchor, node_id, child)]
TGather --> TRBuffer[(Table request buffer<br/>structure_id, anchor, slot)]
RBuffer --> Host[Host fulfils requests]
TRBuffer --> Host
Host -->|CacheInsertionData| Insert[VoxelCache::insert]
Host -->|structure insertion| TableInsert[ToroidalStructureTable::insert]
Insert -->|writes| Cache
Insert -->|recycles pages| Evict[Evictor]
TableInsert -->|root pointers| Table
Two request/response loops are visible:
- Structure-table loop. The table maps chunk coordinates to the root pointer of each chunk's tree in the cache. A miss requests a chunk root.
- Cache loop. During ray marching, the cache tracer requests missing children of nodes that are marked subdividable but not resident.
Both loops share the same request-buffer implementation and host download path.
4. Frame lifecycle (what the current driver does)
State::render in src/main.rs is the only driver. One iteration does roughly:
- Move the toroidal table to the camera position. Chunks leaving the block are invalidated; chunks entering are marked as needing a root pointer.
- Render pass (
ray_march_computeinvoxel.slang):- trace the toroidal chunk grid, then descend the voxel cache;
- write position/albedo/normal G-buffers;
- update per-page usage timestamps;
- increment request counters for missing children.
- GI pass (
gi.slang) — currently a stub that copies albedo. - Blit / UI — copy the selected debug texture, draw egui, download a usage histogram for the plot.
- Encode request gathering for both the cache and the structure table
(unless
Fis held): top-K, gather, radix sort, write request buffers, reset counters. - Submit and present.
- Read back timings asynchronously.
- Fulfil requests and insert (unless
Fis held):- start asynchronous downloads of both request buffers;
- busily poll the device until both callbacks have run;
- on the CPU, produce nodes for every request (parallel over requests);
- upload
CacheInsertionDatabuffers; - encode
VoxelCache::insertwith both an external insertion (table roots) and an internal insertion (cache children); - encode
ToroidalStructureTable::insertto point table entries at the new root pages; - submit.
Consequences agents should keep in mind:
- Inserted pages become visible on the next frame; the render pass of the current frame already ran.
- The host step is synchronous and blocking even though the download API is
callback-based. The
loop { device.poll(...) }at the end ofrenderis a workaround, not the intended design. - Holding
Ffreezes cache management so the resident set can be inspected. - Debug display keys:
Ttarget,Nnormals,Qalbedo,Pposition.
5. Module map
| Path | Role | Status |
|---|---|---|
src/main.rs |
Window, wgpu setup, frame loop, host fulfilment | Temporary playground |
src/producers.rs |
ChunkedProducer + procedural fixtures |
Temporary playground (trait is the useful part) |
src/voxel_cache.rs |
VoxelCache orchestrator, public API, raytrace bind group |
Active, durable |
src/voxel_cache/schema.rs |
Pointer bits, page structs, request structs | Active, durable |
src/voxel_cache/layout.rs |
Attribute descriptors and generated WGSL constants | Active, durable |
src/voxel_cache/attributes.rs |
Attribute page buffers and bind group | Active, durable |
src/voxel_cache/structure.rs |
Pointer/location/depth page buffers | Active, durable |
src/voxel_cache/requests.rs |
Request counters, request buffer, top-K/sort, host download | Active, durable |
src/voxel_cache/insertion.rs |
CacheInsertionData upload buffers |
Active, durable |
src/voxel_cache/eviction.rs |
Timestamp buffer and eviction ordering | Active, durable |
src/voxel_cache/pipelines.rs |
Write-requests, insertion, invalidation, write-pointers passes | Active, durable |
src/voxel_cache/tables.rs |
FixedStructureTable (dense root pointers) |
Active, durable |
src/terrain.rs |
ToroidalStructureTable wrapper around the fixed table |
Active, durable (name is misleading) |
src/gpu/ |
Radix sort, top-K, indirect dispatch, compaction helpers | Active infrastructure |
src/gpu_profiler/ |
Timestamp profiling and memory accounting wrappers | Active infrastructure |
src/gi_pipeline.rs (+ sparse_set.rs) |
Planned GI pipeline using cache attribute sets | Compiled but never instantiated |
src/production.rs |
Producer/structure IDs, StructureAnchor re-export, VoxelProducer trait |
Compiled; durable contract |
src/production/host_production.rs |
Rayon-based HostRequestHandler |
Compiled; fullfill still a stub |
src/production/tree_locator.rs |
Compact N-tree locator encoding | Compiled; inactive |
src/production/request_queue.rs |
Bounded, deduplicating, priority-ordered request queue | Compiled, unit-tested; not yet on the live async path |
src/host_production.rs |
Legacy ChunkVoxelProducer trait |
Inactive |
src/tree.rs |
CPU N-tree prototype | Inactive |
src/sparse_tree.rs |
Packed color helper and node locator used by producers | Active via main.rs/producers.rs |
Cargo.toml uses edition 2024 and nightly features (generic_const_exprs,
float_algebraic). Building requires a nightly toolchain.
6. Coordinate and tree model
The world is treated as a floating-point cube; the cache exploits float mantissas to derive tree levels.
- Branching factor
N = 4; a node hasN³ = 64children. - Child index is
x + 4*y + 16*z(x fastest). This matches the WGSLchild_indexand the Rust producer loops. - A node's level is encoded by
scale_exp:scale_exp = 23 - 2*depthfor single-precision floats. The root starts atscale_exp = 21(depth 1 in that mapping); each subdivision subtracts 2. - Because 23 mantissa bits are available, the tree has room for roughly
11 levels of 2-bit levels. The configured demo uses
chunk_power = 5, i.e. a chunk is4^5 = 1024voxels per axis. - Position-to-child conversion takes two mantissa bits at the current
scale_exp, so the tree is effectively spatially indexed by float bit patterns. This is why the tracer can descend without explicit bounding boxes.
VoxelTraceStack in voxel_cache.slang is a 5-entry stack indexed by
10 - scale_exp/2. That hardcodes the maximum supported depth and the
branching factor. It also assumes chunk_power = 5; changing chunk depth without
updating the stack breaks tracing.
The toroidal table is a dense 3D grid of chunk root pointers. It wraps with
imod, so moving the camera across a chunk boundary invalidates the departing
slab and reuses those slots for incoming chunks. Identity is kept separate from
placement: each slot carries a table-defined StructureAnchor (world position
plus a version word) and a stable StructureId. Anchors that stay in view keep
their id while their slot may change; anchors that leave retire their id, which
is never reused. In-flight root work carries the anchor and the latest slot, and
the GPU rejects an insertion whose anchor/id no longer matches the slot, so queue
invalidation is only a cancellation optimisation.
7. Shader split
There are two independent shader worlds, described fully in
shaders.md:
- Slang (
shaders/*.slang) for rendering. Built offline withslangcinto checked-inshaders/out/*.spv, embedded withinclude_spirv_source!, and loaded as passthrough modules. - WGSL (
src/voxel_cache/shaders/*.wgsl) for cache management. Concatenated at runtime with generated constants (CHILDREN_COUNT,PAGE_COUNT, attribute metadata) and compiled withinclude_wgsl!-style module creation.
The two worlds agree only by convention on data layout. Attribute order, page stride, child index, and pointer bits are load-bearing contracts between them.
8. Memory and performance envelope
The demo configuration is VoxelCache<4> with 150,000 pages and 1,024 maximum
requests, plus a 20×20×20 toroidal table.
Approximate steady-state GPU buffers (decimal units, CHILDREN_COUNT = 64):
| Buffer | Bytes per page | At 150k pages |
|---|---|---|
Pointer pages (u64 mask + 64×u32) |
264 | ~39.6 MB |
| Location pages (allocated at 264 B; see below) | 264 | ~39.6 MB |
| Depth pages | 4 | ~0.6 MB |
color attribute (1 word × 64) |
256 | ~38.4 MB |
normal attribute (3 words × 64) |
768 | ~115.2 MB |
Request counters (64×u32) |
256 | ~38.4 MB |
Sorted requests (64×u32) |
256 | ~38.4 MB |
Scratch (64×u32) |
256 | ~38.4 MB |
| Timestamps + LRU list | 8 | ~1.2 MB |
Total is roughly 400 MB before pipelines, bind groups, profiler buffers, and the separate structure-table allocations. The single largest avoidable waste is the location-page over-allocation described in the issues table.
Performance is dominated by ray marching, not by cache management in the current demo; the UI plots both a frame timer and a ray-march timer.
9. Known issues (architecture level)
| Symptom | Location | Impact | Confidence |
|---|---|---|---|
Location pages are sized with size_of::<StructurePage<N>>() (264 B at N=4) instead of LocationPage (28 B). |
src/voxel_cache/structure.rs:44 |
~39.6 MB allocated where ~4.2 MB is needed. | High — direct code read. |
The host request path busy-waits on device.poll, making a callback design behave synchronously. |
src/main.rs around the loop { ... poll ... } after request downloads |
Stalls the CPU on the render thread; prevents real pipelining/streaming. | High. |
VoxelTraceStack is 5 entries and indexes stack[10 - scale_exp/2], assuming N = 4 and chunk_power = 5. |
shaders/voxel_cache.slang:93-96,177,189,257 |
Changing branching or chunk depth silently corrupts tracing. | High. |
Slang hardcodes 64 children per node and attribute meanings (0 = packed color, 1 = 3-word normal). |
shaders/voxel_cache.slang, shaders/voxel.slang |
Any cache layout change must be mirrored in Slang; mismatches are not caught at compile time. | High. |
gi.slang is a stub that copies albedo and declares legacy bindings that do not match the Rust GI bind group. |
shaders/gi.slang, src/main.rs |
Works only because the declared bindings are unused; misleading as an example. | High. |
FixedStructureTable / ToroidalStructureTable naming: the toroidal wrapper delegates to the fixed table, and fixed_structure_table.slang is imported but unused by voxel.slang. |
src/terrain.rs, shaders/fixed_structure_table.slang, shaders/voxel.slang:3 |
Readers may look for toroidal logic in the wrong shader/module. | High. |
| Several subsystems are present but not wired into the binary (see module map). | src/production/*, src/tree.rs, src/host_production.rs, src/gi_pipeline.rs |
Dead code can be mistaken for current architecture; it does not compile into the binary unless declared. | High. |
fullfill_request hardcodes NTreeNodeLocator<4> and a +5000 chunk offset. |
src/main.rs:1762-1838 |
Not generic over the cache branching factor; offsets are demo-specific. | High. |