Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
82c952c6d8 | ||
|
|
6dedbbdb75 | ||
|
|
1117647ca7 |
@@ -0,0 +1,150 @@
|
||||
# AGENTS.md
|
||||
|
||||
Guidance for agents working in this repository. Read this first, then the
|
||||
relevant document under [`docs/`](./docs).
|
||||
|
||||
## What this is
|
||||
|
||||
`vxls` is a Rust + wgpu voxel renderer built around a GPU-resident sparse voxel
|
||||
cache (GigaVoxels-style). The tree is 4×4×4 (64 children per node), nodes live
|
||||
in fixed GPU page pools, and there is no separate brick pool. Rendering emits
|
||||
requests for missing nodes on the GPU; a producer fulfils them on the CPU and
|
||||
the cache inserts them.
|
||||
|
||||
The durable system is:
|
||||
|
||||
- `src/voxel_cache.rs` and `src/voxel_cache/*` — cache API and GPU passes.
|
||||
- `src/voxel_cache/shaders/*.wgsl` — runtime-specialised cache shaders.
|
||||
- `src/gpu/*` — radix sort, top-K, indirect dispatch, compaction.
|
||||
- `shaders/*.slang` — render-side ray marching, compiled ahead of time.
|
||||
- `src/voxel_cache/tables.rs` + `src/terrain.rs` — structure tables and the
|
||||
toroidal world wrapper.
|
||||
|
||||
> **Temporary code:** `src/main.rs` and `src/producers.rs` are 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 real system is `src/voxel_cache/*` and
|
||||
> `shaders/`.
|
||||
|
||||
## Build and run
|
||||
|
||||
Requirements: a **nightly** Rust toolchain (edition 2024, `generic_const_exprs`,
|
||||
`float_algebraic`) and `slangc` if you modify Slang shaders.
|
||||
|
||||
```sh
|
||||
make -C shaders # rebuild SPIR-V into shaders/out/ (checked in)
|
||||
cargo run # window + egui overlay
|
||||
cargo check # compile check
|
||||
```
|
||||
|
||||
SPIR-V files are embedded with `include_spirv_source!` / `include_spirv!` at
|
||||
Rust compile time, so after rebuilding shaders you must also rebuild Rust.
|
||||
|
||||
Debug keys: `F` pause cache management, `T` target, `N` normals, `Q` albedo,
|
||||
`P` position.
|
||||
|
||||
## Documentation map
|
||||
|
||||
| Document | Read it for |
|
||||
|---|---|
|
||||
| [`docs/architecture.md`](./docs/architecture.md) | Vision, principles, module map, frame lifecycle, data flow, memory envelope, architecture-level issues. |
|
||||
| [`docs/voxel-cache.md`](./docs/voxel-cache.md) | Page/pointer layouts, attributes, public API, request/insertion pipelines, eviction, structure tables, bind groups. |
|
||||
| [`docs/shaders.md`](./docs/shaders.md) | Slang vs WGSL split, build/embedding, tracing algorithm, LOD, shader contracts, shader-level issues. |
|
||||
| [`docs/pipeline-and-producers.md`](./docs/pipeline-and-producers.md) | Request/response contract, current host loop, generator fixtures, unwired production subsystem, adding a producer. |
|
||||
|
||||
Suggested read order for a new agent:
|
||||
`AGENTS.md` → `docs/architecture.md` → `docs/voxel-cache.md` →
|
||||
`docs/shaders.md` → `docs/pipeline-and-producers.md`.
|
||||
|
||||
## Load-bearing conventions
|
||||
|
||||
Do not change these casually; they are contracts between Rust, WGSL, and Slang.
|
||||
|
||||
1. **Pointer bits:** bit 31 = subdividable, bit 30 = available, bits 0..29 =
|
||||
page index. `child_pointer_available` requires both high bits.
|
||||
2. **Child index:** `x + 4*y + 16*z` (x fastest), 64 children per node.
|
||||
3. **Page model:** one page = one node = 64 pointers + occupancy mask + location
|
||||
+ depth + attributes. No separate brick pool.
|
||||
4. **Request/insertion order:** request slot `i` corresponds to insertion slot
|
||||
`i`. `write_pointers` and table insertion rely on this.
|
||||
5. **Attribute order:** Slang hardcodes attribute 0 as packed RGBA color and
|
||||
attribute 1 as a 3-word normal, with stride 64. The demo's `CacheLayout`
|
||||
order is load-bearing.
|
||||
6. **`N` is overloaded:** Rust `VoxelCache<N>` / `VoxelCacheInsertion<N>` use `N`
|
||||
as the branching factor; Slang `VoxelCacheParameters<N>` uses `N` as the
|
||||
attribute count. Read the surrounding type before assuming.
|
||||
7. **Depth assumptions:** `VoxelTraceStack` holds 5 entries and indexes
|
||||
`stack[10 - scale_exp/2]`, assuming branching 4 and `chunk_power = 5`.
|
||||
Changing either breaks tracing silently.
|
||||
8. **Generated WGSL constants:** `CHILDREN_COUNT`, `PAGE_COUNT`, and attribute
|
||||
metadata are injected at runtime by `pipelines.rs`. Edit the Rust generator,
|
||||
not a generated copy.
|
||||
9. **SPIR-V is generated:** never edit `shaders/out/*.spv`; edit `.slang` and run
|
||||
`make -C shaders`.
|
||||
10. **Eviction order:** timestamp-major (least recently used first), depth-minor
|
||||
(deepest first). The depth pass runs descending and the timestamp pass runs
|
||||
stable so equal timestamps keep the deepest-first order.
|
||||
|
||||
## Where to look for common tasks
|
||||
|
||||
| Task | Start at |
|
||||
|---|---|
|
||||
| Change page/pointer layout | `src/voxel_cache/schema.rs`, `src/voxel_cache/shaders/cache_common.wgsl`, `src/voxel_cache/shaders/common.wgsl` |
|
||||
| Add/change a cache attribute | `src/voxel_cache/layout.rs`, `src/voxel_cache/attributes.rs`, `src/voxel_cache/shaders/insertion.wgsl`, Slang `fetch_*` in `shaders/voxel.slang` |
|
||||
| Change request prioritisation | `src/voxel_cache/requests.rs`, `src/gpu/top_k.rs`, `src/gpu/radix_sort.rs` |
|
||||
| Change eviction | `src/voxel_cache/eviction.rs`, `src/voxel_cache/shaders/eviction.wgsl`, `src/voxel_cache/shaders/insertion.wgsl` |
|
||||
| Change insertion semantics | `src/voxel_cache.rs` (`insert`), `src/voxel_cache/pipelines.rs`, `src/voxel_cache/shaders/insertion.wgsl`, `write_pointers.wgsl` |
|
||||
| Change world/chunk lookup | `src/voxel_cache/tables.rs`, `src/terrain.rs`, `shaders/toroidal_structure_table.slang` |
|
||||
| Change ray marching/LOD | `shaders/voxel.slang`, `shaders/voxel_cache.slang`, `shaders/lod_policies.slang` |
|
||||
| Add a producer | `src/producers.rs` (interface), `src/main.rs` (`fullfill_request`), [`docs/pipeline-and-producers.md`](./docs/pipeline-and-producers.md) |
|
||||
|
||||
## Current demo configuration
|
||||
|
||||
```text
|
||||
VoxelCache<4> branching 64
|
||||
150_000 pages
|
||||
1_024 max requests
|
||||
attributes: color (1 word), normal (3 words), both External
|
||||
SdfGenerator<4>::new(5) chunk_power 5 => 4^5 = 1024 voxels/axis per chunk cell
|
||||
20 x 20 x 20 toroidal chunk extent
|
||||
request buffers: 1024 (cache), 128 (structure table)
|
||||
```
|
||||
|
||||
In render space one structure-table cell is a unit cube; the cache subdivides
|
||||
that cube and the producer decides how many voxels it packs into it.
|
||||
|
||||
## Known gaps and traps
|
||||
|
||||
The full tables live in the docs. The most important ones:
|
||||
|
||||
- **Location pages are over-allocated** at `size_of::<StructurePage<N>>()` per
|
||||
page instead of `LocationPage` (≈39.6 MB vs ≈1.2 MB at 150k pages).
|
||||
- **The first insertion is a no-op** because of the timestamp guard
|
||||
(`0 >= new_timestamp - 1` on the first call).
|
||||
- **The host producer path busy-waits** on `device.poll`, so "async" request
|
||||
fulfilment blocks the render thread.
|
||||
- **Insertion can silently drop pages** (`destination_indices == 0xFFFFFFFF`)
|
||||
with no signal to the producer.
|
||||
- **Several modules are not wired in:** `src/production/*`, `src/tree.rs`,
|
||||
`src/host_production.rs`, and `VoxelGiPipeline`. Mark them as inactive rather
|
||||
than treating them as current behaviour.
|
||||
- **`gi.slang` is a stub** with legacy bindings that do not match the Rust GI
|
||||
bind group.
|
||||
- **`fixed_structure_table.slang` is imported but unused**; the active path is
|
||||
the toroidal wrapper around Rust's `FixedStructureTable`.
|
||||
|
||||
## Working conventions
|
||||
|
||||
- **Ask before guessing** when behaviour or intent is undocumented. This repo
|
||||
contains experimental code and contradictory comments; prefer evidence from
|
||||
source over inference.
|
||||
- **Preserve the Rust/WGSL/Slang contract.** If you change a layout, update all
|
||||
three sides and the docs.
|
||||
- **Measure before optimising.** Timestamp queries and the memory profiler are
|
||||
already available (`src/gpu_profiler`).
|
||||
- **Do not "fix" dead code by assuming it is live.** Check `mod` declarations in
|
||||
`src/main.rs` first.
|
||||
- **Keep the playground separate from the engine.** New durable logic belongs in
|
||||
`src/voxel_cache/*`, `src/gpu/*`, or `shaders/*`, not in `main.rs`.
|
||||
- **Document discrepancies as observations.** If code and comments disagree,
|
||||
state what the code does, what the comment claims, and your confidence.
|
||||
@@ -0,0 +1,299 @@
|
||||
# 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`](./voxel-cache.md) — pages, pointers, requests, eviction, tables.
|
||||
- [`shaders.md`](./shaders.md) — Slang/WGSL shader architecture and compilation.
|
||||
- [`pipeline-and-producers.md`](./pipeline-and-producers.md) — how data gets into the cache.
|
||||
|
||||
> **Temporary code:** `src/main.rs` and `src/producers.rs` are 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 is `src/voxel_cache/*`
|
||||
> and `shaders/`.
|
||||
|
||||
---
|
||||
|
||||
## 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.
|
||||
|
||||
1. **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.
|
||||
2. **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.
|
||||
3. **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.
|
||||
4. **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).
|
||||
5. **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.
|
||||
6. **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`](./voxel-cache.md#7-eviction-policy--timestamp-major-deepest-first-ties)).
|
||||
- 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 in `main.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
|
||||
|
||||
```mermaid
|
||||
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, node_id, child)]
|
||||
TGather --> TRBuffer[(Table request buffer)]
|
||||
|
||||
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:
|
||||
|
||||
1. **Move the toroidal table** to the camera position. Chunks leaving the block
|
||||
are invalidated; chunks entering are marked as needing a root pointer.
|
||||
2. **Render pass** (`ray_march_compute` in `voxel.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.
|
||||
3. **GI pass** (`gi.slang`) — currently a stub that copies albedo.
|
||||
4. **Blit / UI** — copy the selected debug texture, draw egui, download a usage
|
||||
histogram for the plot.
|
||||
5. **Encode request gathering** for both the cache and the structure table
|
||||
(unless `F` is held): top-K, gather, radix sort, write request buffers, reset
|
||||
counters.
|
||||
6. **Submit and present.**
|
||||
7. **Read back timings** asynchronously.
|
||||
8. **Fulfil requests and insert** (unless `F` is 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 `CacheInsertionData` buffers;
|
||||
- encode `VoxelCache::insert` with both an external insertion (table roots)
|
||||
and an internal insertion (cache children);
|
||||
- encode `ToroidalStructureTable::insert` to 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 of `render` is a
|
||||
workaround, not the intended design.
|
||||
- Holding `F` freezes cache management so the resident set can be inspected.
|
||||
- Debug display keys: `T` target, `N` normals, `Q` albedo, `P` position.
|
||||
|
||||
---
|
||||
|
||||
## 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 and `VoxelProducer` trait | **Not declared in `main.rs`; inactive** |
|
||||
| `src/production/host_production.rs` | Rayon-based `HostRequestHandler` | **Inactive** |
|
||||
| `src/production/tree_locator.rs` | Compact N-tree locator encoding | **Inactive** |
|
||||
| `src/production/request_queue.rs` | WIP request queue | **Untracked / WIP, inactive** |
|
||||
| `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 has `N³ = 64` children.
|
||||
- Child index is `x + 4*y + 16*z` (x fastest). This matches the WGSL
|
||||
`child_index` and the Rust producer loops.
|
||||
- A node's level is encoded by `scale_exp`: `scale_exp = 23 - 2*depth` for
|
||||
single-precision floats. The root starts at `scale_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 is `4^5 = 1024` voxels 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.
|
||||
|
||||
---
|
||||
|
||||
## 7. Shader split
|
||||
|
||||
There are two independent shader worlds, described fully in
|
||||
[`shaders.md`](./shaders.md):
|
||||
|
||||
- **Slang** (`shaders/*.slang`) for rendering. Built offline with `slangc` into
|
||||
checked-in `shaders/out/*.spv`, embedded with `include_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 with `include_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` (8 B). | `src/voxel_cache/structure.rs:44` | ~39.6 MB allocated where ~1.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. |
|
||||
@@ -0,0 +1,418 @@
|
||||
# Pipeline and producers
|
||||
|
||||
This document follows data from a GPU-emitted request to a resident cache page,
|
||||
and describes the producer interface. It also marks which producer code is
|
||||
durable and which is throwaway.
|
||||
|
||||
> **Temporary code:** `src/main.rs` and `src/producers.rs` are 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 `ChunkedProducer` shape and the
|
||||
> insertion/data-flow contract are the durable parts; the concrete generators
|
||||
> (including `SdfGenerator` and `TerrainGenerator`) are throwaway fixtures and
|
||||
> should be replaced.
|
||||
|
||||
---
|
||||
|
||||
## 1. End-to-end sequence
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant R as Render pass (GPU)
|
||||
participant C as Voxel cache (GPU)
|
||||
participant T as Structure table (GPU)
|
||||
participant H as Host (main.rs)
|
||||
participant I as Insertion passes (GPU)
|
||||
|
||||
R->>C: descend pages, mark usage, increment missing-child counters
|
||||
R->>T: trace chunk cells, increment missing-root counters
|
||||
Note over C,T: end of draw
|
||||
C->>C: top-K + gather + descending radix sort
|
||||
T->>T: top-K + gather + descending radix sort
|
||||
C-->>H: request buffer (structure_id, node_id, child)
|
||||
T-->>H: table request buffer (slot, 0, 0)
|
||||
H->>H: produce one node per request (parallel)
|
||||
H->>I: upload CacheInsertionData (info, locations, attributes, count)
|
||||
I->>C: recycle pages, write pages, invalidate stale pointers
|
||||
I->>C: write new child pointers
|
||||
I->>T: point table slots at new root pages
|
||||
Note over R: next frame sees the new pages
|
||||
```
|
||||
|
||||
Timing detail: in the current driver the render pass runs **before** request
|
||||
gathering and insertion in the same `render()` call. Therefore pages produced in
|
||||
response to frame N are first visible in frame N+1.
|
||||
|
||||
---
|
||||
|
||||
## 2. The request/response contract
|
||||
|
||||
### 2.1 Request
|
||||
|
||||
```rust
|
||||
struct RequestInformation {
|
||||
structure_id: u32, // which structure (chunk/table slot)
|
||||
node_id: u32, // locator of the *parent* node
|
||||
children_index: u32, // which child is missing
|
||||
}
|
||||
|
||||
struct RequestMeta {
|
||||
page_index: u32, // parent page (internal) or sentinel (external)
|
||||
children_index: u32,
|
||||
depth: u32,
|
||||
}
|
||||
```
|
||||
|
||||
- The producer only sees `RequestInformation`. `RequestMeta` stays on the GPU
|
||||
and is used by `write_pointers` / table insertion.
|
||||
- For external requests from a structure table: `node_id = 0`,
|
||||
`children_index = 0`, and `structure_id` is the table slot.
|
||||
- Requests are sorted by demand (highest counter first) and capped at
|
||||
`max_requests`.
|
||||
|
||||
### 2.2 Response
|
||||
|
||||
One `CacheInsertionData` entry per request, in the **same order**:
|
||||
|
||||
```rust
|
||||
struct InsertionInformation<N> {
|
||||
children: [ChildInformation; 64], // bit 31 subdividable, bit 30 occupied
|
||||
}
|
||||
|
||||
struct LocationPage {
|
||||
structure_id: u32,
|
||||
node_id: u32,
|
||||
}
|
||||
```
|
||||
|
||||
Plus one attribute payload per page (color and normal in the demo).
|
||||
|
||||
The cache fills `destination_indices[i]` with the page that received slot `i`,
|
||||
or `0xFFFFFFFF` if it could not insert. The producer does not need to read it in
|
||||
the current demo, but a real implementation should, because the cache can silently
|
||||
drop pages when it is full or when candidate pages were used in the previous
|
||||
frame.
|
||||
|
||||
### 2.3 Why order matters
|
||||
|
||||
`write_pointers.wgsl` and `fixed_table/insertion.wgsl` assume:
|
||||
|
||||
```text
|
||||
request_informations[i] <-> insertion_data[i] <-> destination_indices[i]
|
||||
```
|
||||
|
||||
If a producer reorders, filters, or duplicates requests, pages will be linked to
|
||||
the wrong parents. There is no validation.
|
||||
|
||||
---
|
||||
|
||||
## 3. The durable producer shape
|
||||
|
||||
`src/producers.rs` defines:
|
||||
|
||||
```rust
|
||||
pub trait ChunkedProducer<const N: usize>
|
||||
where [(); N * N * N]:,
|
||||
{
|
||||
fn produce_node(
|
||||
&self,
|
||||
depth: usize,
|
||||
nx: usize,
|
||||
ny: usize,
|
||||
nz: usize,
|
||||
chunk_pos: (usize, usize, usize),
|
||||
) -> ProducedChunk<N>;
|
||||
}
|
||||
|
||||
pub struct ProducedChunk<const N: usize> {
|
||||
pub children: [ChildInformation; N * N * N],
|
||||
pub colors: [u32; N * N * N], // packed RGBA
|
||||
pub normals: [[f32; 3]; N * N * N],
|
||||
}
|
||||
```
|
||||
|
||||
Interpretation:
|
||||
|
||||
- `depth` is the node depth inside a chunk (root = 0).
|
||||
- `(nx, ny, nz)` is the node's position in the depth-specific coordinate space
|
||||
(`0 .. N^depth`), i.e. the node's grid coordinate at that depth, not a voxel
|
||||
coordinate.
|
||||
- `chunk_pos` is the chunk's grid position in the world.
|
||||
- The producer must fill one entry per child. Each child says whether it can be
|
||||
subdivided further and whether it is occupied, and supplies its attribute
|
||||
words.
|
||||
- A leaf is `subdividable = false`. A node that should be refined later is
|
||||
`subdividable = true`. Occupancy controls hit testing and coarse skipping.
|
||||
|
||||
This shape is independent of the cache layout only up to the attribute buffers:
|
||||
the demo's `colors` / `normals` arrays correspond exactly to the two configured
|
||||
attributes. A general design should produce `word_count` words per attribute per
|
||||
child instead of hardcoding color/normal.
|
||||
|
||||
### 3.1 Fulfilling a request
|
||||
|
||||
The demo's `fullfill_request` (`src/main.rs`) does:
|
||||
|
||||
1. Map `structure_id` to an absolute chunk coordinate using
|
||||
`ToroidalStructureTable::get_request_position`.
|
||||
2. Add the playground offset `+5000` to x and z and take `abs()` of y.
|
||||
3. If `node_id == 0`, produce the chunk root at depth 0 and emit the root
|
||||
locator.
|
||||
4. Otherwise:
|
||||
- decode the parent `NTreeNodeLocator<4>` from `node_id`;
|
||||
- decode `children_index` into `(child_x, child_y, child_z)` with x fastest;
|
||||
- compute the child locator;
|
||||
- produce the child node at `parent_depth + 1` with the child's node
|
||||
coordinates;
|
||||
- emit the child locator as the new `LocationPage.node_id`.
|
||||
|
||||
The `+5000` offset and the hardcoded `<4>` are playground artifacts. They assume
|
||||
chunk dimensions of 20×20×20 and a 4-ary tree.
|
||||
|
||||
### 3.2 Locators
|
||||
|
||||
Two locator implementations exist:
|
||||
|
||||
- **`NTreeNodeLocator<N>`** (`src/sparse_tree.rs`) — used by the demo. A packed
|
||||
`usize`; supports `root`, `from_usize`, `depth`, `child`, `node_location`,
|
||||
`as_usize`, `parent`, `children`.
|
||||
- **`TreeLocator<N>`** (`src/production/tree_locator.rs`) — the unwired
|
||||
production subsystem's version. Three base-N accumulators (`x`, `y`, `z`) with
|
||||
a leading `1` digit; root is `(1,1,1)`; `depth = ilog_N(x)`; `parent` divides
|
||||
each coordinate by `N`; `child` multiplies by `N` and adds the child digit.
|
||||
`StructureLocator` is a flat interleaved form.
|
||||
|
||||
Both encode "path from root" and can be converted to/from application-level
|
||||
coordinates. Whichever is used, it must round-trip through the 32-bit
|
||||
`node_id`.
|
||||
|
||||
---
|
||||
|
||||
## 4. The current driver, step by step
|
||||
|
||||
Relevant code: `State::render` and `fullfill_request` in `src/main.rs`.
|
||||
|
||||
1. **Render** writes G-buffers and request counters.
|
||||
2. **Gather** encodes both request pipelines (cache + table) into the same
|
||||
command buffer, then submits and presents.
|
||||
3. **Download** starts two asynchronous reads per request buffer (count and
|
||||
informations).
|
||||
4. **Busy-wait**:
|
||||
|
||||
```rust
|
||||
loop {
|
||||
if finished.load(Relaxed) >= 2 { break; }
|
||||
let _ = self.device.poll(wgpu::wgt::PollType::Poll);
|
||||
}
|
||||
```
|
||||
|
||||
`finished` counts completed callbacks (one cache, one table), so completion
|
||||
does not require all four reads to land independently.
|
||||
5. **Produce** on the CPU with rayon: one `fullfill_request` per request. The
|
||||
results are copied into dense vectors, then uploaded with
|
||||
`queue.write_buffer` into:
|
||||
- `insertion_information_buffer()`
|
||||
- `location_pages_buffer()`
|
||||
- `attributes_buffers()[0]` (color)
|
||||
- `attributes_buffers()[1]` (normal)
|
||||
- `page_count_buffer()`
|
||||
6. **Insert** encodes:
|
||||
|
||||
```rust
|
||||
cache.insert(&device, &mut encoder, &mut [
|
||||
&mut VoxelCacheInsertion::ExternalRequest(
|
||||
&structure_table_cache_insertion, &mut *structure_table),
|
||||
&mut VoxelCacheInsertion::InternalRequest(
|
||||
&cache_insertion, &request_buffer),
|
||||
]);
|
||||
structure_table.insert(&device, &mut encoder,
|
||||
&structure_table_cache_insertion, &structure_table_request_buffer);
|
||||
```
|
||||
|
||||
One eviction preparation is shared by both batches. It orders pages by
|
||||
timestamp first (least recently used first) and depth second (deepest first
|
||||
among equal timestamps).
|
||||
7. **Submit** and read back the insertion profile.
|
||||
|
||||
Because the external insertion is processed first, newly produced chunk roots
|
||||
are resident before the internal child insertion links them. The table insertion
|
||||
then points the slot at the root page.
|
||||
|
||||
### 4.1 Problems this creates
|
||||
|
||||
- The render thread blocks on the CPU producer; there is no overlap between
|
||||
production and rendering.
|
||||
- Request buffers are read back every frame even when empty.
|
||||
- `finished >= 2` is a coarse synchronization; it assumes exactly two buffers
|
||||
and no retries.
|
||||
- The producer runs on the same thread that owns the event loop, so a slow
|
||||
producer directly reduces frame rate.
|
||||
- No backpressure or prioritisation beyond the top-K request cap.
|
||||
|
||||
These are acceptable for a playground and are the first things to redesign for a
|
||||
real engine.
|
||||
|
||||
---
|
||||
|
||||
## 5. Generators in `src/producers.rs`
|
||||
|
||||
All are fixtures. They exist to exercise the cache and should not be treated as
|
||||
stable.
|
||||
|
||||
| Generator | Status | What it does |
|
||||
|---|---|---|
|
||||
| `SdfGenerator<N>` | Used by the demo | Signed-distance field from FBM simplex noise plus procedural "trees"; derives normal by finite differences; packs color from normal. |
|
||||
| `TerrainGenerator<N>` | Supported but commented out | Loads a TIFF heightmap and a JPEG/PNG colormap; builds low-resolution mips; produces nodes from min/max height spans. |
|
||||
| `BallGenerator<N>` | Unused | Implements the older `Producer<N>` trait (not `ChunkedProducer`), draws a sphere; useful as a minimal example. |
|
||||
|
||||
`TerrainGenerator` is the closest thing to a realistic producer, but it is
|
||||
single-threaded at load time and uses hardcoded mip factors (8×). It also has
|
||||
branching logic based on `depth <= 2`.
|
||||
|
||||
`SdfGenerator` demonstrates the attribute math:
|
||||
|
||||
- `alpha = 0` above the surface, `1` below;
|
||||
- `subdivided = depth < chunk_power - 1` near the surface;
|
||||
- normal from four SDF samples;
|
||||
- color derived from the normal with a small random tint.
|
||||
|
||||
---
|
||||
|
||||
## 6. The unwired production subsystem
|
||||
|
||||
These files are **not declared as modules in `main.rs`**, so they are not part of
|
||||
the running binary. They represent earlier or planned designs. Treat them as
|
||||
reference material, not current architecture.
|
||||
|
||||
### 6.1 `src/production.rs`
|
||||
|
||||
Defines a more ambitious interface:
|
||||
|
||||
```rust
|
||||
pub struct ProducerId(pub u32);
|
||||
pub struct StructureId(pub u32);
|
||||
pub struct StructureLocator(pub u32);
|
||||
|
||||
pub trait VoxelAttributes<const N: usize> {
|
||||
fn attribute_count() -> usize;
|
||||
fn attribute(&self, attribute_index: usize) -> &[u32];
|
||||
}
|
||||
|
||||
pub trait VoxelProducer<const N: usize> {
|
||||
type Output: VoxelAttributes<N>;
|
||||
fn produce(
|
||||
&self,
|
||||
producer_id: ProducerId,
|
||||
id: StructureId,
|
||||
locator: StructureLocator,
|
||||
) -> (InsertionInformation<N>, [Self::Output; N * N * N]);
|
||||
}
|
||||
```
|
||||
|
||||
Differences from the demo interface:
|
||||
|
||||
- A node carries a `producer_id`, so one cache can mix multiple producers.
|
||||
- Attributes are abstracted behind `VoxelAttributes`, avoiding hardcoded
|
||||
color/normal buffers.
|
||||
- The producer receives a `StructureLocator` rather than depth + coordinates,
|
||||
pushing locator arithmetic into the producer.
|
||||
|
||||
### 6.2 `src/production/host_production.rs`
|
||||
|
||||
`HostRequestHandler<N, P: VoxelProducer<N>>` owns a rayon `ThreadPool` and a
|
||||
producer, and is intended to fulfil requests on the CPU. Note that its
|
||||
`fullfill` method is a stub: it downloads the request buffer with an empty
|
||||
callback. `produce_requests` does the real parallel mapping.
|
||||
|
||||
### 6.3 `src/production/tree_locator.rs`
|
||||
|
||||
`TreeLocator<N>` (described in §3.2) plus `From<StructureLocator>` /
|
||||
`Into<StructureLocator>` conversions.
|
||||
|
||||
### 6.4 `src/production/request_queue.rs`
|
||||
|
||||
Untracked WIP. Do not depend on it.
|
||||
|
||||
### 6.5 `src/host_production.rs`
|
||||
|
||||
An older, simpler trait:
|
||||
|
||||
```rust
|
||||
pub trait ChunkVoxelProducer {
|
||||
fn produce_voxel(&mut self, depth, chunk_position, voxel_position);
|
||||
}
|
||||
```
|
||||
|
||||
It has no return value and no cache insertion types; it predates the current
|
||||
request/response pipeline.
|
||||
|
||||
### 6.6 `src/tree.rs`
|
||||
|
||||
A CPU `NTree<N>` prototype backed by a `HashMap<NTreeLocator<N>, NTreeNode<N>>`,
|
||||
with `constant`, `get`, `set`, array conversion, and explicit-structure export.
|
||||
Useful for understanding the tree, not used by the renderer.
|
||||
|
||||
### 6.7 `src/gi_pipeline.rs` + `sparse_set.rs`
|
||||
|
||||
Compiles (declared in `main.rs`) but `VoxelGiPipeline` is never instantiated. It
|
||||
adds `DontTouch` attributes for a leaf list and radiance, and a `GpuSparseSet`
|
||||
for resident leaves. It is a sketch of a future GI integration, not working
|
||||
code.
|
||||
|
||||
---
|
||||
|
||||
## 7. Adding a producer
|
||||
|
||||
Minimum viable path with the current demo interface:
|
||||
|
||||
1. Implement `ChunkedProducer<N>`:
|
||||
|
||||
```rust
|
||||
impl ChunkedProducer<4> for MyProducer {
|
||||
fn produce_node(&self, depth, nx, ny, nz, chunk_pos) -> ProducedChunk<4> { ... }
|
||||
}
|
||||
```
|
||||
|
||||
2. For each child, compute:
|
||||
- `subdividable`: can this child be refined?
|
||||
- `occupied`: can it produce a hit?
|
||||
- attribute words in the cache layout order.
|
||||
3. Wire the producer into `fullfill_request` (or replace that function).
|
||||
Request → coordinates:
|
||||
- external: `node_id == 0`, produce chunk root;
|
||||
- internal: decode `node_id`, decode `children_index`, produce child at
|
||||
`depth + 1`.
|
||||
4. Emit a `LocationPage` matching the produced node. For internal requests,
|
||||
it must be `parent.child(child_x, child_y, child_z)`.
|
||||
5. Ensure the output order matches the request order and the batch size matches
|
||||
`page_count_buffer`.
|
||||
6. Update the size passed to `CacheInsertionData::new` if the maximum batch can
|
||||
exceed `max_requests`.
|
||||
|
||||
A production-ready producer should additionally:
|
||||
|
||||
- use the unwired `VoxelProducer`/`VoxelAttributes` abstraction (or an
|
||||
equivalent) so attributes are not hardcoded;
|
||||
- run on a worker thread and stream results without blocking the render loop;
|
||||
- handle `destination_indices == 0xFFFFFFFF` by retrying the request;
|
||||
- implement filtering/mip generation for coarser levels so LOD stops do not
|
||||
alias;
|
||||
- support multiple structures/producers per cache via IDs.
|
||||
|
||||
---
|
||||
|
||||
## 8. Known issues
|
||||
|
||||
| Symptom | Location | Impact | Confidence |
|
||||
|---|---|---|---|
|
||||
| The host request path busy-waits on `device.poll`; production blocks the render thread. | `src/main.rs` (`loop { ... poll ... }` in `render`) | No overlap, frame stalls, no streaming. | High |
|
||||
| `fullfill_request` hardcodes `NTreeNodeLocator<4>`, x/y/z child unpacking with `4` and `16`, and a `+5000` chunk offset. | `src/main.rs:1762-1838` | Not generic; offsets only make sense for the demo terrain. | High |
|
||||
| `page_count_buffer` is set to `request_informations.len()`, which may exceed `CacheInsertionData`'s `max_page_count` (1024) if `max_requests` is raised without resizing. | `src/main.rs` (write of `page_count_buffer`), `CacheInsertionData::new` | Buffer overrun / truncated production. | High |
|
||||
| If `destination_indices[i] == 0xFFFFFFFF`, the producer is not told; the cache will re-request the node later. | `insertion.wgsl`, host callback | Wasted work and repeated requests; no metric for dropped pages. | High |
|
||||
| The external table insertion consumes the same eviction list as the cache insertion; if it inserts fewer roots than requested, the table has missing entries with no host-visible signal. | `VoxelCache::insert`, `fixed_table/insertion.wgsl` | Silent holes in the world. | Medium |
|
||||
| `TerrainGenerator` uses hardcoded mip factor 8 and `depth <= 2` special cases. | `src/producers.rs:207-263,330` | Not robust to different chunk resolutions. | High |
|
||||
| `BallGenerator` implements the old `Producer` trait, not `ChunkedProducer`. | `src/producers.rs:31-116` | Copying it as a template will not work with the current driver. | High |
|
||||
| The `production/` subsystem is not compiled into the binary but looks authoritative. | `src/production.rs`, `src/production/*` | Agents may "fix" dead code or assume it is live. | High |
|
||||
| `src/production/request_queue.rs` is untracked WIP. | same | Brittle; may change or disappear. | High |
|
||||
| The demo uploads all attribute payloads with `bytemuck::cast_slice` of Rust arrays, so layout mismatches (padding, alignment) are not checked. | `src/main.rs` upload section | Silent corruption if the Rust struct layout diverges from the WGSL/Slang layout. | Medium |
|
||||
| The `+5000` offset plus `chunk_y.abs()` means negative chunk coordinates fold onto positive ones. | `src/main.rs:1785-1789` | Duplicate chunks / visual artifacts at negative y. | Medium |
|
||||
+518
@@ -0,0 +1,518 @@
|
||||
# Shaders
|
||||
|
||||
The project uses two shader languages for two different jobs:
|
||||
|
||||
| | Slang (`shaders/*.slang`) | WGSL (`src/voxel_cache/shaders/*.wgsl`) |
|
||||
|---|---|---|
|
||||
| Used for | Rendering / ray marching | Cache management passes |
|
||||
| Compilation | Offline via `slangc`, SPIR-V checked in | Runtime via wgpu |
|
||||
| Specialisation | Compile-time types and generics | Runtime string concatenation + generated `const`s |
|
||||
| Embedded with | `include_spirv_source!` / `include_spirv!` | `include_str!` into a generated module |
|
||||
| Rust entry point | `main.rs` passthrough shader modules | `pipelines.rs`, `requests.rs`, `eviction.rs`, `tables.rs` |
|
||||
|
||||
> **Temporary code:** bind-group and pipeline setup in `src/main.rs` is part of
|
||||
> the playground driver. Read shader contracts from the Rust cache/table
|
||||
> wrappers (`src/voxel_cache/*`) and this document, not from `main.rs` alone.
|
||||
|
||||
---
|
||||
|
||||
## 1. Slang build model
|
||||
|
||||
`shaders/Makefile`:
|
||||
|
||||
```make
|
||||
all: clean voxel.spv compaction.spv gi.spv radix_sort.spv radix_reduce.spv
|
||||
|
||||
clean:
|
||||
rm -f out/*.spv
|
||||
|
||||
%.spv: %.slang
|
||||
slangc $< -O3 -g0 -fp-mode fast -emit-spirv-directly -fvk-use-entrypoint-name -target spirv -o out/$@
|
||||
```
|
||||
|
||||
Build with:
|
||||
|
||||
```sh
|
||||
make -C shaders
|
||||
```
|
||||
|
||||
Generated files live in `shaders/out/` and are **checked in**. Do not hand-edit
|
||||
them; edit the `.slang` source and rebuild.
|
||||
|
||||
### How SPIR-V reaches wgpu
|
||||
|
||||
- Rendering shaders are loaded with
|
||||
`create_shader_module_passthrough` (requires `PASSTHROUGH_SHADERS`), which
|
||||
avoids wgpu's shader validation and requires explicit entry-point workgroup
|
||||
sizes:
|
||||
- `shaders/out/voxel.spv` → entry `ray_march_compute`, workgroup `(16,16,1)`
|
||||
- `shaders/out/gi.spv` → entry `gi`, workgroup `(16,16,1)`
|
||||
- Utility shaders are loaded with ordinary `include_spirv!`:
|
||||
- `shaders/out/radix_sort.spv` in `src/gpu/radix_sort.rs`
|
||||
- `shaders/out/compaction.spv` in `src/gpu/buffer_compactor.rs`
|
||||
- `radix_reduce.spv` is built by the Makefile but currently not referenced by
|
||||
Rust source.
|
||||
|
||||
The declared entry-point name must match `-fvk-use-entrypoint-name`; otherwise
|
||||
module creation fails.
|
||||
|
||||
---
|
||||
|
||||
## 2. Slang module graph
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
V[voxel.slang<br/>ray_march_compute] --> VC[voxel_cache.slang<br/>VoxelCacheTracer]
|
||||
V --> VT[voxel_tracing.slang<br/>Tracer / interfaces]
|
||||
V --> TST[toroidal_structure_table.slang<br/>ToroidalStructureTableTracer]
|
||||
V --> LOD[lod_policies.slang<br/>PixelFootprintLod]
|
||||
V -. unused import .-> FST[fixed_structure_table.slang]
|
||||
VC --> VT
|
||||
TST --> VT
|
||||
TST --> VC
|
||||
```
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| `voxel_tracing.slang` | `Ray`, `Span`, `Cell`, `Hit`; `IStructure`, `IVoxelCache`, `ILodPolicy`; generic `Tracer`. |
|
||||
| `voxel_cache.slang` | `StructurePointer`, `StructureElement`, `VoxelCacheParameters`, `VoxelTraceStack`, `VoxelCacheTracer`, attribute helpers. |
|
||||
| `toroidal_structure_table.slang` | Dense wrapped chunk grid; produces cache entry cells. |
|
||||
| `lod_policies.slang` | `PixelFootprintLod`. |
|
||||
| `fixed_structure_table.slang` | Non-wrapping chunk grid; imported by `voxel.slang` but not used. |
|
||||
| `voxel.slang` | Push constants, G-buffer bindings, `ColorHit`, `ray_march_compute`. |
|
||||
| `gi.slang` | Stub GI pass (copies albedo). |
|
||||
| `compaction.slang`, `radix_sort.slang`, `radix_reduce.slang` | GPU utility kernels. |
|
||||
|
||||
---
|
||||
|
||||
## 3. Bindings and immediates (rendering)
|
||||
|
||||
`voxel.slang` declares:
|
||||
|
||||
```slang
|
||||
[[vk::push_constant]] uniform PushConstants constants;
|
||||
|
||||
ParameterBlock<VoxelCacheParameters<2>> cache_parameters; // group 0
|
||||
ParameterBlock<ToroidalStructureTable> table_parameters; // group 1
|
||||
|
||||
[[vk::binding(0,2)]] WTexture2D<float4> gbuffer_position; // group 2
|
||||
[[vk::binding(1,2)]] WTexture2D<float4> gbuffer_albedo;
|
||||
[[vk::binding(2,2)]] WTexture2D<float4> gbuffer_normal;
|
||||
```
|
||||
|
||||
### Group 0 — cache (`VoxelCacheParameters<N>`)
|
||||
|
||||
| Binding | Contents |
|
||||
|---|---|
|
||||
| 0 | `structure_pool`: pointer pages (`StructureElement`) |
|
||||
| 1 | `request_buffer`: per-child atomic counters (`RequestBufferElement`) |
|
||||
| 2 | `usage_buffer`: per-page timestamp |
|
||||
| 3 | `attributes_pool[N]`: attribute pages (N = attribute count = 2 here) |
|
||||
|
||||
### Group 1 — structure table
|
||||
|
||||
| Binding | Contents |
|
||||
|---|---|
|
||||
| 0 | `structure_table_pointer`: one `StructurePointer` per chunk slot |
|
||||
| 1 | `structure_table_request_buffer`: one atomic counter per slot |
|
||||
|
||||
### Group 2 — G-buffers
|
||||
|
||||
Three `rgba32f` storage textures written by the main pass; `gi.slang` binds
|
||||
target + position + albedo + normal instead.
|
||||
|
||||
### Push constants / immediates
|
||||
|
||||
```slang
|
||||
struct PushConstants {
|
||||
float4x4 view_proj;
|
||||
float3 cam_pos;
|
||||
uint32_t frame_timestamp;
|
||||
uint32_t width;
|
||||
uint32_t height;
|
||||
uint32_t chunk_width;
|
||||
uint32_t chunk_height;
|
||||
uint32_t chunk_alt;
|
||||
}
|
||||
```
|
||||
|
||||
Rust passes `camera.view_proj().inverse()` in `view_proj`, while the shader does
|
||||
`mul(constants.view_proj, ndc)`. The pair reconstructs a world-space ray
|
||||
direction. `chunk_*` feeds the toroidal table extent; in the demo all three are
|
||||
20, which hides an ordering inconsistency in the naming (Rust passes
|
||||
`(width, alt, height)` to the table but `(width, height, alt)` to the shader).
|
||||
|
||||
`frame_timestamp` must equal `VoxelCache::current_timestamp()` when the render
|
||||
pass is recorded; it is used both for usage reporting and for deciding which
|
||||
pages were touched this frame.
|
||||
|
||||
---
|
||||
|
||||
## 4. Tracing interfaces
|
||||
|
||||
`voxel_tracing.slang` defines the composition pattern:
|
||||
|
||||
```slang
|
||||
public interface IStructure {
|
||||
associatedtype Cursor;
|
||||
Cursor begin(Ray worldRay, Span s);
|
||||
bool next(inout Cursor c, out Cell cell);
|
||||
}
|
||||
|
||||
public interface IVoxelCache {
|
||||
associatedtype GroupSharedData;
|
||||
bool trace<L : ILodPolicy>(
|
||||
uint32_t root, inout GroupSharedData data, Ray r, L lod, float offset_t, out Hit v);
|
||||
}
|
||||
|
||||
public interface ILodPolicy {
|
||||
bool shouldStop(float t, float nodeSize);
|
||||
}
|
||||
|
||||
public struct Tracer<S : IStructure, C : IVoxelCache, L : ILodPolicy> {
|
||||
S structure; C cache; L lod;
|
||||
bool trace(inout C.GroupSharedData gsData, out Hit h, Ray r, Span s);
|
||||
}
|
||||
```
|
||||
|
||||
`Tracer::trace` walks structure cells and asks the cache to trace each one. Any
|
||||
interface can be replaced without touching the others; this is the main
|
||||
extensibility point on the render side.
|
||||
|
||||
---
|
||||
|
||||
## 5. `VoxelCacheTracer` algorithm
|
||||
|
||||
`voxel_cache.slang`. The tracer descends a 4-ary tree encoded by float mantissas.
|
||||
|
||||
### 5.1 Ray mirroring
|
||||
|
||||
To make the DDA always move toward increasing coordinates, the ray is reflected
|
||||
into the positive octant:
|
||||
|
||||
1. `r.origin += 1` and clamp to `[1, 2)`.
|
||||
2. For each axis with positive direction, flip the mantissa bits
|
||||
(`asuint(origin) ^ 0x007fffff`).
|
||||
3. Build `child_mirror`, which flips the 2-bit child coordinate per axis.
|
||||
|
||||
Hit locations are mirrored back before being returned.
|
||||
|
||||
### 5.2 Tree levels
|
||||
|
||||
```slang
|
||||
uint32_t scale_exp = 23 - 2; // root level
|
||||
uint32_t child_index = get_children_index(pos, scale_exp) ^ child_mirror;
|
||||
```
|
||||
|
||||
`get_children_index` extracts two mantissa bits:
|
||||
|
||||
```slang
|
||||
cell_position = (asuint(position) >> scale_exp) & 3;
|
||||
child_index = x + y*4 + z*16;
|
||||
```
|
||||
|
||||
Each subdivision does `scale_exp -= 2`. `node_size(scale_exp)` reconstructs the
|
||||
world-space node size from the exponent/mantissa.
|
||||
|
||||
### 5.3 Main loop
|
||||
|
||||
Per iteration (max 500):
|
||||
|
||||
1. Read the current child pointer.
|
||||
2. **Descend** while the pointer is `subdivided_valid()` (bits 31 and 30 set)
|
||||
and the LOD policy says the node is still too large:
|
||||
- `scale_exp -= 2`, `current_node_index = pointer()`, push onto the
|
||||
`VoxelTraceStack`, report usage.
|
||||
3. **Request** if the LOD still wants detail, the pointer is subdividable, and
|
||||
it is not resident:
|
||||
`requests[current_node_index][child_index] += 1`.
|
||||
4. **Hit test** using the occupancy mask and `IVoxelHit::shouldHit`.
|
||||
5. **DDA step**:
|
||||
- If the coarser 2×2×2 neighbourhood is empty
|
||||
(`(occupancy >> (child_index & 0b101010)) & 0x00330033 == 0`), advance one
|
||||
extra level (`adv_scale_exp++`) to skip empty space.
|
||||
- Compute the next face intersection from the mirrored ray, step `pos` to the
|
||||
face (clamped by the neighbour maximum).
|
||||
- Find the most common ancestor of old and new positions via XOR and
|
||||
`firstbithigh`, then restore `scale_exp` and pop the stack to that level.
|
||||
|
||||
### 5.4 Stack
|
||||
|
||||
```slang
|
||||
public struct VoxelTraceStack { public uint32_t stack[5]; }
|
||||
```
|
||||
|
||||
`voxel.slang` allocates one per thread in groupshared memory:
|
||||
|
||||
```slang
|
||||
groupshared VoxelTraceStack stacks[256]; // 16x16 workgroup
|
||||
```
|
||||
|
||||
The index `stack[10 - scale_exp / 2]` hardcodes the supported depth. With
|
||||
`N = 4` and `chunk_power = 5`, the deepest level used is 5, so the stack must
|
||||
hold entries for levels 1..5. Changing the branching factor or chunk depth
|
||||
requires changing both the stack size and this index formula.
|
||||
|
||||
### 5.5 Hit test
|
||||
|
||||
`voxel.slang` defines `ColorHit<2>`:
|
||||
|
||||
```slang
|
||||
bool shouldHit(VoxelCacheParameters<N> cache, uint32_t node_index, uint32_t child_index) {
|
||||
return ByteColor(cache.attributes_pool[0][node_index * 64 + child_index]).byte_a != 0;
|
||||
}
|
||||
```
|
||||
|
||||
So a child is a hit when the alpha byte of its packed color is non-zero. The hit
|
||||
result exposes `node_index`, `child_index`, and a mirrored-back
|
||||
`hit_location`.
|
||||
|
||||
---
|
||||
|
||||
## 6. Structure traversal
|
||||
|
||||
### 6.1 Toroidal tracer
|
||||
|
||||
`toroidal_structure_table.slang` walks unit cells (one cell per structure slot):
|
||||
|
||||
- `begin`: `current_voxel = floor(origin)`, `offset = current_voxel - extent/2`.
|
||||
It initialises the 3D DDA `t` values from the ray direction.
|
||||
- `next`, while the current cell is inside the block:
|
||||
- compute wrapped local coordinates with `imod`;
|
||||
- compute the slot index
|
||||
`x + z*extent.x + y*extent.x*extent.z`;
|
||||
- if the slot pointer is resident, emit a `Cell` with
|
||||
`local_ray.origin = position - current_voxel` (fractional position inside the
|
||||
unit cell), and return it;
|
||||
- if the slot is subdividable but not resident, increment its request counter;
|
||||
- step the DDA to the next cell.
|
||||
|
||||
In shader space one cell is a unit cube. The producer decides how many voxels
|
||||
that cube contains (`chunk_power = 5` means `4^5 = 1024` voxels per axis in the
|
||||
demo). The cache tracer subdivides the unit cube; it never sees the producer's
|
||||
voxel count directly.
|
||||
|
||||
The `min_mask` + `sign(direction)` stepping means the traversal advances one
|
||||
cell per axis crossing; it does not skip empty chunks based on occupancy.
|
||||
|
||||
### 6.2 `fixed_structure_table.slang`
|
||||
|
||||
A non-wrapping version of the same idea. It is imported by `voxel.slang` but not
|
||||
instantiated; the Rust `FixedStructureTable` is used through the toroidal
|
||||
wrapper instead.
|
||||
|
||||
---
|
||||
|
||||
## 7. LOD
|
||||
|
||||
```slang
|
||||
struct PixelFootprintLod : ILodPolicy {
|
||||
float pixelAngle; // angular size of one pixel (radians)
|
||||
float pixelThreshold; // pixels a node may cover before we stop
|
||||
float coneRadius0; // footprint at t = 0
|
||||
|
||||
float footprint(float t) { return coneRadius0 + t * pixelAngle; }
|
||||
|
||||
bool shouldStop(float t, float nodeSize) {
|
||||
return nodeSize <= footprint(t) * pixelThreshold;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`create(fovYRadians, imageHeightPixels, pixelThreshold, coneRadius0)` computes
|
||||
`pixelAngle = 2*tan(fovY/2)/imageHeightPixels`.
|
||||
|
||||
Demo call:
|
||||
|
||||
```slang
|
||||
PixelFootprintLod lod = PixelFootprintLod.create((100.f * 3.14f) / 180.f, 1080.f, 2.f);
|
||||
```
|
||||
|
||||
Interpretation:
|
||||
|
||||
- `pixelThreshold = 1.0` → stop when a node is about one pixel wide.
|
||||
- `2.0` (the demo) → stop when a node is two pixels wide, i.e. coarser/faster.
|
||||
- `coneRadius0 = 0` is a pinhole camera; secondary rays should inherit a
|
||||
non-zero footprint from their parent bounce.
|
||||
|
||||
---
|
||||
|
||||
## 8. Main render entry point
|
||||
|
||||
`voxel.slang`:
|
||||
|
||||
```slang
|
||||
[shader("compute")]
|
||||
[numthreads(16,16,1)]
|
||||
void ray_march_compute(uint32_t3 location : SV_DispatchThreadID,
|
||||
uint32_t3 local_location : SV_GroupThreadID)
|
||||
```
|
||||
|
||||
1. Bounds-check against `constants.width/height`.
|
||||
2. Build a `VoxelCacheTracer<2, ColorHit<2>>` with usage + request reporting and
|
||||
the frame timestamp.
|
||||
3. Build a `ToroidalStructureTableTracer` with
|
||||
`extent = (chunk_width, chunk_alt, chunk_width)`.
|
||||
4. Build a `Tracer` and call `trace` with the per-thread stack.
|
||||
5. On hit, fetch normal and color from attribute pools and store position,
|
||||
normal, and albedo G-buffers.
|
||||
6. On miss, store zero albedo.
|
||||
|
||||
`fetch_color` and `fetch_normal` hardcode the demo layout:
|
||||
|
||||
```slang
|
||||
attributes_pool[0][node * 64 + child] // color
|
||||
attributes_pool[1][node * 64*3 + child*3 + 0..2] // normal
|
||||
```
|
||||
|
||||
This is the most important cross-language contract in the repo. If you reorder
|
||||
or resize attributes in `CacheLayout`, update these functions and `ColorHit`.
|
||||
|
||||
---
|
||||
|
||||
## 9. WGSL cache shaders
|
||||
|
||||
### 9.1 Composition
|
||||
|
||||
Cache management shaders are assembled at runtime from concatenated strings:
|
||||
|
||||
```text
|
||||
common.wgsl // structs, pointer helpers, enable wgpu_binding_array
|
||||
<generated constants> // CHILDREN_COUNT, PAGE_COUNT, attribute metadata
|
||||
cache_common.wgsl // PointerPage, InsertionInformation, index helpers
|
||||
<pass file> // entry point(s)
|
||||
```
|
||||
|
||||
`programmatic_common_wgsl!` in `pipelines.rs` generates:
|
||||
|
||||
```wgsl
|
||||
const CHILDREN_COUNT: u32 = 64; // N*N*N
|
||||
const PAGE_COUNT: u32 = 150000;
|
||||
const ATTRIBUTE_COUNT: u32 = 2;
|
||||
const ATTRIBUTE_WORD_COUNTS: array<u32,2> = ...;
|
||||
const ATTRIBUTE_COPY: array<bool,2> = ...;
|
||||
```
|
||||
|
||||
Structure-table shaders use a simpler concatenation:
|
||||
`common.wgsl` + pass file.
|
||||
|
||||
`common.wgsl` starts with `enable wgpu_binding_array;` and defines the shared
|
||||
`CacheIndex`, `RequestInformation`, `RequestMeta`, `AttributeArray`,
|
||||
`LocationPage`, and child-pointer helpers so the Rust and WGSL sides share names.
|
||||
|
||||
### 9.2 WGSL modules and entry points
|
||||
|
||||
| File | Entry point(s) | Purpose |
|
||||
|---|---|---|
|
||||
| `shaders/requests.wgsl` | `reset_requests` | Zero all per-child request counters. |
|
||||
| `shaders/gather_requests.wgsl` | `gather_requests` | Copy selected top-K counts/indices into radix key/value buffers. |
|
||||
| `shaders/write_requests.wgsl` | `write_requests` | Convert sorted flat indices into `RequestInformation`/`RequestMeta`. |
|
||||
| `shaders/insertion.wgsl` | `insertion`, `consume` | Recycle pages, write pointer/location/depth/attributes, advance consumed count. |
|
||||
| `shaders/invalidation.wgsl` | `invalidation` | Clear cache pointers that reference pages recycled this insert. |
|
||||
| `shaders/write_pointers.wgsl` | `write_pointers` | Link internal insertion results into parent pages. |
|
||||
| `shaders/eviction.wgsl` | `reset_lru_list`, `indirect_copy` | Build the eviction candidate list: descending depth sort, then gather timestamps for the stable timestamp sort. |
|
||||
| `fixed_table/write_requests.wgsl` | `write_requests` | Emit root requests for table slots. |
|
||||
| `fixed_table/insertion.wgsl` | `insertion` | Point table slots at inserted root pages. |
|
||||
| `fixed_table/invalidation.wgsl` | `invalidation` | Clear table slots pointing at recycled pages. |
|
||||
| `terrain/shaders/toroidal_structure.wgsl` | `invalidate_new` | Reset table slots whose world position changed. |
|
||||
|
||||
All compute workgroups are `(256,1,1)` except `toroidal_structure.wgsl`, which
|
||||
uses `(4,4,4)`.
|
||||
|
||||
### 9.3 Bind-group conventions
|
||||
|
||||
Cache shaders consistently bind:
|
||||
|
||||
- group 0 — cache structure (pointer, location, depth pages), except
|
||||
`insertion.wgsl` where group 0 is attributes and group 1 is structure;
|
||||
- group 1 — request handler, evictor, or request buffer depending on the pass;
|
||||
- group 2 — request buffer, insertion data, or scratch buffer;
|
||||
- group 3 — evictor or insertion data;
|
||||
- group 4 — inserted-count atomic.
|
||||
|
||||
The authoritative table is in [`voxel-cache.md`](./voxel-cache.md#9-bind-groups).
|
||||
|
||||
### 9.4 Immediates
|
||||
|
||||
WGSL passes use `var<immediate>` for a small `u32`:
|
||||
|
||||
- `insertion.wgsl`: `new_timestamp` (the frame timestamp assigned to new pages).
|
||||
- `invalidation.wgsl`: `new_timestamp` (marks which pages are dirty this pass).
|
||||
- `toroidal_structure.wgsl`: a struct of `extent`, `previous_offset`, `offset`.
|
||||
|
||||
Rust sets these with `pass.set_immediates(0, ...)`; the pipeline layouts declare
|
||||
`immediate_size` accordingly.
|
||||
|
||||
### 9.5 Attribute copy contract
|
||||
|
||||
`insertion.wgsl` copies attributes for each page slot:
|
||||
|
||||
```wgsl
|
||||
for (attribute_index in 0..ATTRIBUTE_COUNT) {
|
||||
if (!ATTRIBUTE_COPY[attribute_index]) { continue; }
|
||||
page_stride = CHILDREN_COUNT * ATTRIBUTE_WORD_COUNTS[attribute_index];
|
||||
dest_offset = page_stride * page_index;
|
||||
src_offset = page_stride * insertion_slot;
|
||||
for (word in 0..page_stride) {
|
||||
cache_attributes[attribute_index].values[dest_offset + word]
|
||||
= insertion_data_attributes[attribute_index].values[src_offset + word];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
So attribute buffers are always `page_count * 64 * word_count` words, and the
|
||||
insertion batch is indexed by request slot.
|
||||
|
||||
---
|
||||
|
||||
## 10. Changing shaders: checklist
|
||||
|
||||
### Adding or resizing a cache attribute
|
||||
|
||||
1. Add it to `CacheLayout` in the caller (order matters).
|
||||
2. If the renderer reads it, update `VoxelCacheParameters` usage and
|
||||
`fetch_*` functions in `voxel_cache.slang` / `voxel.slang`.
|
||||
3. Update `ColorHit` if the hit criterion changes.
|
||||
4. Check the `VoxelCacheParameters<N>` attribute count `N` (not the branching
|
||||
factor).
|
||||
5. Rebuild Slang if you changed `.slang` files.
|
||||
|
||||
### Changing the branching factor
|
||||
|
||||
Do not do this casually. Required changes include:
|
||||
|
||||
- `VoxelCache<N>` / producer `N` and all 64-element assumptions;
|
||||
- `get_children_index` (`*4`, `*16`) and the child-mirror shifts;
|
||||
- `VoxelTraceStack` size and `10 - scale_exp/2` indexing;
|
||||
- `StructureElement.pointers[64]`;
|
||||
- `fetch_color`/`fetch_normal` strides (`*64`, `*64*3`);
|
||||
- generated WGSL `CHILDREN_COUNT`;
|
||||
- the `0b101010` / `0x00330033` empty-neighbourhood test.
|
||||
|
||||
### Rebuilding
|
||||
|
||||
```sh
|
||||
make -C shaders # regenerates shaders/out/*.spv
|
||||
cargo run # wgpu embeds the checked-in SPIR-V at compile time
|
||||
```
|
||||
|
||||
Because SPIR-V is embedded with `include_*!`, changing `.spv` requires a Rust
|
||||
rebuild. CI or fresh checkouts must either commit the `.spv` files or run the
|
||||
Makefile before building.
|
||||
|
||||
---
|
||||
|
||||
## 11. Known issues
|
||||
|
||||
| Symptom | Location | Impact | Confidence |
|
||||
|---|---|---|---|
|
||||
| `voxel.slang` imports `fixed_structure_table` but never uses it. | `shaders/voxel.slang:3` | Misleads readers; increases compile surface. | High |
|
||||
| `gi.slang` declares legacy bindings (`structure_pool`, `attributes_pool`, request/usage buffers, table buffers) that do not match the GI bind group Rust actually creates. | `shaders/gi.slang:17-45`, `src/main.rs:563-611` | Works only because the mismatched bindings are unused. Any real GI work will hit validation errors. | High |
|
||||
| `PixelFootprintLod` demo parameters are hardcoded (100° FOV, 1080 px, threshold 2). | `shaders/voxel.slang:149` | LOD does not follow the window/FOV; resizing the window changes effective LOD. | High |
|
||||
| `VoxelTraceStack` size and indexing assume `N = 4` and `chunk_power = 5`. | `shaders/voxel_cache.slang:93-96,177,189,257` | Branching/depth changes silently break tracing. | High |
|
||||
| `fetch_color` / `fetch_normal` hardcode stride 64 and attribute indices 0/1. | `shaders/voxel.slang:68-79` | Cache layout changes break rendering with no compile-time error. | High |
|
||||
| The child-index and child-mirror arithmetic hardcodes `4` and `16`. | `shaders/voxel_cache.slang:103-108,154-165` | Not generic over branching factor. | High |
|
||||
| The toroidal tracer walks one unit cell per axis crossing with no empty-chunk skip. | `shaders/toroidal_structure_table.slang:62-101` | Cost scales with traversed grid cells, not just occupied chunks. | Medium |
|
||||
| `chunk_*` immediate field naming/order differs between Rust (`width, height, alt`) and the table extent (`width, alt, height`). | `src/main.rs:1049-1062`, `shaders/voxel.slang:140` | Hidden because the demo uses 20×20×20; non-cubic extents would mismatch. | Medium |
|
||||
| `radix_reduce.spv` is built and checked in but unused. | `shaders/Makefile:1` | Confusing build artifact. | High |
|
||||
| `voxel.slang` uses `groupshared VoxelTraceStack stacks[256]` but `create_shader_module_passthrough` bypasses wgpu validation. | `shaders/voxel.slang:118`, `src/main.rs:477-498` | Layout/limit errors appear as driver errors, not friendly validation messages. | Medium |
|
||||
@@ -0,0 +1,626 @@
|
||||
# Voxel cache
|
||||
|
||||
`src/voxel_cache.rs` and `src/voxel_cache/*` implement a GPU-resident sparse
|
||||
voxel cache. This document covers the page model, pointer encoding, public API,
|
||||
request/insertion pipelines, eviction, and the structure tables that provide
|
||||
entry points into the cache.
|
||||
|
||||
> **Temporary caller:** the public `VoxelCache` surface is intended API;
|
||||
> `src/main.rs` is only one caller and currently uses it in a blocking,
|
||||
> single-threaded playground way. See [`pipeline-and-producers.md`](./pipeline-and-producers.md).
|
||||
|
||||
---
|
||||
|
||||
## 1. Model
|
||||
|
||||
- An N-tree with branching factor `N` (`N = 4` in the demo). One node has
|
||||
`N³ = 64` children.
|
||||
- The cache owns a fixed pool of **pages**. A page stores everything about one
|
||||
node: its 64 child pointers, a 64-bit occupancy mask, its location tag, its
|
||||
depth, and the node's attributes. There is **no separate brick pool**.
|
||||
- Pages are recycled. When a page is reused, every pointer that targeted it
|
||||
must be invalidated.
|
||||
- The unit of transfer is a page (one node's worth of data), not a single voxel
|
||||
or a brick.
|
||||
|
||||
Key invariants:
|
||||
|
||||
1. `page_index` must fit in 30 bits (`CachePointer` stores it in bits 0..29).
|
||||
2. Request index `i` and insertion slot `i` are **one-to-one**. The producer
|
||||
fills `CacheInsertionData` in the same order as the request buffer, and
|
||||
`write_pointers.wgsl` relies on that.
|
||||
3. Slang consumers assume a child count of 64 and the demo attribute order.
|
||||
Changing the cache layout requires editing the Slang shaders.
|
||||
4. A page's `LocationPage` must describe the node the page represents, not its
|
||||
parent.
|
||||
|
||||
---
|
||||
|
||||
## 2. Page layouts
|
||||
|
||||
### 2.1 Pointer page
|
||||
|
||||
```text
|
||||
struct PointerPage { // WGSL (cache_common.wgsl)
|
||||
occupancy_low: u32,
|
||||
occupancy_high: u32,
|
||||
pointers: array<u32, 64>,
|
||||
}
|
||||
```
|
||||
|
||||
```rust
|
||||
struct StructurePage<N> { // Rust (schema.rs), used for sizing only
|
||||
occupancy_mask: u64,
|
||||
pointers: [CachePointer; N*N*N],
|
||||
}
|
||||
```
|
||||
|
||||
`occupancy_low`/`occupancy_high` are the low/high halves of the same 64-bit
|
||||
mask as `StructurePage::occupancy_mask` on little-endian hardware. Bit `i` means
|
||||
child `i` is occupied (may produce a hit). The occupancy mask lets the tracer
|
||||
skip empty regions and coalesce DDA steps.
|
||||
|
||||
The Rust `StructurePage` is only used to size `pointer_pages`; the authoritative
|
||||
layout is the WGSL `PointerPage`. Keep them in sync.
|
||||
|
||||
For `N = 4`, a pointer page is `8 + 64*4 = 264` bytes.
|
||||
|
||||
### 2.2 Location page
|
||||
|
||||
```rust
|
||||
struct LocationPage {
|
||||
structure_id: u32, // which structure (world chunk, etc.)
|
||||
node_id: u32, // application-defined locator within that structure
|
||||
}
|
||||
```
|
||||
|
||||
The cache never interprets these values; they are copied from insertion data and
|
||||
returned in requests so the producer knows which node is missing. In the demo,
|
||||
`node_id` is an `NTreeNodeLocator` and `structure_id` is a toroidal table slot.
|
||||
|
||||
### 2.3 Depth page
|
||||
|
||||
```rust
|
||||
struct DepthPage(u32); // u32::MAX = unused
|
||||
```
|
||||
|
||||
- External insertions start at depth 0.
|
||||
- Internal insertions get parent depth + 1.
|
||||
- Unused pages use `u32::MAX`.
|
||||
- Depth is the eviction tie-breaker: pages are sorted deepest-first before the
|
||||
stable timestamp sort, so deeper pages win ties (see §7).
|
||||
|
||||
### 2.4 Attribute pages
|
||||
|
||||
Each attribute is its own buffer:
|
||||
|
||||
```text
|
||||
attribute buffer layout (per attribute)
|
||||
┌────────────────────────────── page 0 ──────────────────────────────┐
|
||||
│ child 0 words[0..W] │ child 1 words[0..W] │ ... │ child 63 words[0..W] │
|
||||
├────────────────────────────── page 1 ──────────────────────────────┤
|
||||
│ ... │
|
||||
└────────────────────────────────────────────────────────────────────┘
|
||||
total size = page_count * 64 * W * 4 bytes
|
||||
```
|
||||
|
||||
An attribute is described by `CacheAttribute`:
|
||||
|
||||
```rust
|
||||
pub struct CacheAttribute {
|
||||
pub label: Option<&'static str>,
|
||||
pub word_count: u32,
|
||||
pub init: CacheAttributeInit,
|
||||
}
|
||||
|
||||
pub enum CacheAttributeInit {
|
||||
External, // copied from insertion data
|
||||
DontTouch, // cache never writes it; application owns it
|
||||
}
|
||||
```
|
||||
|
||||
`CacheLayout::add_attribute` returns the attribute index. The layout generates
|
||||
WGSL constants used by the insertion shader:
|
||||
|
||||
```wgsl
|
||||
const ATTRIBUTE_COUNT: u32 = ...;
|
||||
const ATTRIBUTE_WORD_COUNTS: array<u32, ...> = ...;
|
||||
const ATTRIBUTE_COPY: array<bool, ...> = ...; // true for External
|
||||
```
|
||||
|
||||
The demo layout is:
|
||||
|
||||
| Index | Label | Words | Meaning |
|
||||
|---|---|---:|---|
|
||||
| 0 | `color` | 1 | packed RGBA bytes |
|
||||
| 1 | `normal` | 3 | three floats |
|
||||
|
||||
Slang hardcodes these meanings (color at index 0, normal at index 1, stride 64).
|
||||
`CacheAttributeInit::DontTouch` exists for application-computed data such as GI
|
||||
or a leaf list; `VoxelGiPipeline` intended to use it but is not wired in.
|
||||
|
||||
---
|
||||
|
||||
## 3. Pointer encoding
|
||||
|
||||
```text
|
||||
bit 31 30 29 .. 0
|
||||
┌───────────┬──────────┬────────────────────────┐
|
||||
│subdividable│available │ page pointer (30 bits) │
|
||||
└───────────┴──────────┴────────────────────────┘
|
||||
```
|
||||
|
||||
| Bits 31/30 | Meaning |
|
||||
|---|---|
|
||||
| `0/0` | Leaf: cannot be subdivided. No payload. |
|
||||
| `1/0` | Subdividable but not resident. A request may be issued. |
|
||||
| `1/1` | Subdividable, resident. Bits 0..29 are the page index. |
|
||||
|
||||
Rust API: `CachePointer::new(Option<Option<u32>>)`.
|
||||
|
||||
| Argument | Bits | Meaning |
|
||||
|---|---|---|
|
||||
| `None` | `0x00000000` | leaf / unsubdividable |
|
||||
| `Some(None)` | `0x80000000` | subdividable, unavailable |
|
||||
| `Some(Some(p))` | `0xC0000000 \| p` | subdividable, available at page `p` |
|
||||
|
||||
WGSL helpers in `src/voxel_cache/shaders/common.wgsl`:
|
||||
|
||||
- `child_pointer_empty(subdivisible)`
|
||||
- `child_pointer_subdivided(pointer)`
|
||||
- `child_pointer_available(pointer)` — checks both bits
|
||||
- `child_pointer_pointer(pointer)` — masks to 30 bits
|
||||
- `child_pointer_make_available(pointer)`
|
||||
|
||||
Child index convention (Rust and WGSL):
|
||||
|
||||
```text
|
||||
child_index = x + 4*y + 16*z // x fastest
|
||||
```
|
||||
|
||||
`pointer_index_to_cache_index(i)` decomposes a flat request index into
|
||||
`page_index = i / 64`, `children_index = i % 64`.
|
||||
|
||||
---
|
||||
|
||||
## 4. Public API
|
||||
|
||||
### 4.1 Construction
|
||||
|
||||
```rust
|
||||
impl<const N: usize> VoxelCache<N>
|
||||
where [(); N * N * N]:,
|
||||
{
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
page_count: usize,
|
||||
max_requests: usize,
|
||||
layout: &CacheLayout,
|
||||
) -> Self;
|
||||
|
||||
pub fn gather_requests(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
request_buffer: &CacheRequestBuffer,
|
||||
);
|
||||
|
||||
pub fn insert(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
insertions: &mut [&mut VoxelCacheInsertion<N>],
|
||||
);
|
||||
|
||||
pub fn current_timestamp(&self) -> u32;
|
||||
pub fn raytrace_bind_group_layout(&self) -> &BindGroupLayout;
|
||||
pub fn raytrace_bind_group(&self) -> &BindGroup;
|
||||
|
||||
// debug
|
||||
pub fn usage_timestamps(&self) -> &wgpu::Buffer;
|
||||
}
|
||||
```
|
||||
|
||||
`page_count` fixes every pool size. `max_requests` fixes the top-K capacity and
|
||||
the request buffer capacity. Both are immutable after construction.
|
||||
|
||||
`N` is the branching factor, so `N=4` means 64 children. This is a different `N`
|
||||
from the `N` in Slang's `VoxelCacheParameters<N>`, which is the **attribute
|
||||
count** (2 in the demo). This naming collision is a common source of confusion.
|
||||
|
||||
### 4.2 Insertion modes
|
||||
|
||||
```rust
|
||||
pub enum VoxelCacheInsertion<'a, const N: usize> {
|
||||
ExternalRequest(&'a CacheInsertionData<N>, &'a mut dyn CacheInvalidable),
|
||||
InternalRequest(&'a CacheInsertionData<N>, &'a CacheRequestBuffer),
|
||||
}
|
||||
```
|
||||
|
||||
- **External** — bring brand-new pages into the cache (e.g. a structure root).
|
||||
After insertion, the external owner is told to invalidate any of its pointers
|
||||
that targeted recycled pages.
|
||||
- **Internal** — respond to cache-emitted requests. After insertion, the cache
|
||||
writes the new page indices into the requesting pages' child pointers.
|
||||
|
||||
You can pass several insertions in one call; they share one eviction
|
||||
preparation pass and one timestamp.
|
||||
|
||||
`CacheInvalidable` is implemented by the structure tables:
|
||||
|
||||
```rust
|
||||
pub trait CacheInvalidable {
|
||||
fn invalidate(
|
||||
&mut self,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
cache_evictor: &CacheEvictor,
|
||||
invalid_timestamp: u32,
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 4.3 Insertion data
|
||||
|
||||
`CacheInsertionData::new(device, max_page_count, layout)` allocates:
|
||||
|
||||
| Buffer | Contents |
|
||||
|---|---|
|
||||
| `page_count` | number of pages in this batch |
|
||||
| `insertion_information` | dense `InsertionInformation<N>` per page |
|
||||
| `location_pages` | dense `LocationPage` per page |
|
||||
| `destination_indices` | filled by the cache: destination page or `0xFFFFFFFF` |
|
||||
| attribute buffers | dense per-page attribute payloads |
|
||||
|
||||
`InsertionInformation<N>` is just `children: [ChildInformation; 64]`, where each
|
||||
`ChildInformation` uses the four-state encoding below.
|
||||
|
||||
```text
|
||||
bit 31 = subdividable
|
||||
bit 30 = occupied
|
||||
```
|
||||
|
||||
The insertion shader converts child information into a `PointerPage`:
|
||||
|
||||
- every child pointer starts as `empty(subdividable)`;
|
||||
- the occupancy mask bits are assembled from `occupied`;
|
||||
- attributes are copied for `External` attributes only.
|
||||
|
||||
`destination_indices` is an output used by `write_pointers` and by the structure
|
||||
table insertion pass. `0xFFFFFFFF` means "not inserted" (out of capacity or too
|
||||
recently used).
|
||||
|
||||
---
|
||||
|
||||
## 5. Request pipeline
|
||||
|
||||
### 5.1 Where requests come from
|
||||
|
||||
- **During rendering**, `VoxelCacheTracer::trace` descends nodes. If a child is
|
||||
subdividable, not resident, and the LOD says "keep going", it does
|
||||
`request_buffer[current_node_index].requests[child_index].add(1)`.
|
||||
- The structure tracer does the same for table slots whose root pointer is
|
||||
subdividable but unavailable.
|
||||
- Every invocation also writes `usage_buffer[page] = frame_timestamp` for pages
|
||||
it touches (if usage reporting is enabled).
|
||||
|
||||
The request-counter buffers are indexed **per child**, not per page:
|
||||
`request_counts_pages[page_index * 64 + child_index]`.
|
||||
|
||||
### 5.2 `VoxelCache::gather_requests`
|
||||
|
||||
Encoded in this order:
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[request_counts_pages<br/>9.6M u32] --> B[top-K select<br/>k = max_requests]
|
||||
B --> C[gather<br/>keys = counts<br/>values = indices]
|
||||
C --> D[radix sort<br/>descending by count]
|
||||
D --> E[write_requests.wgsl]
|
||||
E --> F[(CacheRequestBuffer)]
|
||||
B -.->|reset| A
|
||||
```
|
||||
|
||||
1. **Top-K** (`TopKSelector::select`): selects up to `k` of the flat
|
||||
`page*64 + child` counters with the highest counts. `k` is
|
||||
`request_buffer.max_requests` (1024 in the demo).
|
||||
`selected_count` is written to a buffer; a zero count means no dispatch.
|
||||
2. **Gather** (`gather_requests.wgsl`): copies the selected counts into the
|
||||
shared scratch buffer as radix keys and the selected flat indices into
|
||||
`sorted_requests` as radix values. Dispatch is indirect from
|
||||
`selected_count`.
|
||||
3. **Radix sort** (`RadixSorter::sort`, descending): sorts the selected requests
|
||||
by request count, highest first.
|
||||
4. **Write requests** (`write_requests.wgsl`): for each sorted index, converts
|
||||
the flat index to `(page_index, children_index)`, looks up the page's
|
||||
`LocationPage`, and writes:
|
||||
|
||||
```rust
|
||||
struct RequestInformation {
|
||||
structure_id: u32, // from LocationPage
|
||||
node_id: u32, // from LocationPage (the parent node)
|
||||
children_index: u32, // requested child
|
||||
}
|
||||
|
||||
struct RequestMeta {
|
||||
page_index: u32, // parent page, or 0xFFFFFFFF if external
|
||||
children_index: u32,
|
||||
depth: u32, // parent depth
|
||||
}
|
||||
```
|
||||
|
||||
5. **Reset** (`requests.wgsl`): zeroes all request counters for the next frame.
|
||||
|
||||
`request_count` is copied from `top_k.selected_count` and then clamped in
|
||||
`write_requests.wgsl` to the request-buffer capacity.
|
||||
|
||||
### 5.3 Host download
|
||||
|
||||
`CacheRequestBuffer::host_download_requests(device, queue, callback)` uses two
|
||||
`DownloadBuffer::read_buffer` calls (count + informations). A small
|
||||
`RequestMapState` waits for both and invokes the callback with
|
||||
`&request_informations[0..count]`.
|
||||
|
||||
The callback is asynchronous by API, but the demo blocks on it with a
|
||||
`device.poll` loop. See [`pipeline-and-producers.md`](./pipeline-and-producers.md).
|
||||
|
||||
### 5.4 What a producer receives
|
||||
|
||||
For an **internal** request:
|
||||
|
||||
- `structure_id` and `node_id` identify the **parent** node.
|
||||
- `children_index` identifies which child is missing.
|
||||
- The producer must generate that child node and emit a `LocationPage` for the
|
||||
child (typically `parent_locator.child(x, y, z)`).
|
||||
- The output order must match the request order.
|
||||
|
||||
For an **external** (structure-table) request:
|
||||
|
||||
- `structure_id` is the table slot.
|
||||
- `node_id` and `children_index` are 0.
|
||||
- The producer must generate a chunk root and emit its `LocationPage`.
|
||||
|
||||
---
|
||||
|
||||
## 6. Insertion pipeline
|
||||
|
||||
`VoxelCache::insert` runs these stages in one encoder:
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[prepare eviction list] --> B[insertion pass<br/>one per insertion]
|
||||
B --> C[external invalidation]
|
||||
C --> D[cache invalidation]
|
||||
D --> E[write pointers<br/>internal insertions only]
|
||||
E --> F[frame_timestamp += 1]
|
||||
```
|
||||
|
||||
### 6.1 Eviction preparation
|
||||
|
||||
`CacheEvictor::prepare_eviction_list`:
|
||||
|
||||
1. `reset_lru_list`: `lru_list[i] = i`, `consumed_count = 0`.
|
||||
2. Copy `depth_pages` into the scratch buffer and radix-sort **descending** with
|
||||
`lru_list` as values. `lru_list` is now page indices ordered **deepest
|
||||
first**.
|
||||
3. `indirect_copy`: `scratch[i] = timestamp_pages[lru_list[i]]`, rearranging
|
||||
timestamps into depth order.
|
||||
4. Radix-sort `scratch` **ascending** with `lru_list` as values. This sort is
|
||||
stable, so equal timestamps keep the deepest-first order from step 2.
|
||||
|
||||
The resulting order is **timestamp-major, depth-minor**: least recently used
|
||||
first, with deeper pages first among equal timestamps. See §7.
|
||||
|
||||
### 6.2 Insertion
|
||||
|
||||
For each insertion, `CacheInsertionPass::encode`:
|
||||
|
||||
1. Dispatches `insertion` indirectly from `page_count`.
|
||||
2. Computes `available_amount = min(page_count_free - consumed, batch_size)`.
|
||||
3. For slot `i`:
|
||||
- if `i >= available_amount`, mark `destination_indices[i] = 0xFFFFFFFF`;
|
||||
- pick `page_index = lru_list[i + consumed_count]`;
|
||||
- if `timestamp_pages[page_index] >= new_timestamp - 1`, do not insert
|
||||
(protects pages touched in the previous frame). **Note:** on the very
|
||||
first `insert` call, `new_timestamp` is 1 and unused pages have timestamp 0,
|
||||
so `0 >= 0` rejects every page. The first insertion is therefore a no-op
|
||||
and the cache only starts filling on the second call. See §11;
|
||||
- otherwise mark the page, increment `pass_inserted_count`, write location,
|
||||
pointer page, timestamp, depth 0, and copy external attributes.
|
||||
4. Dispatch `consume` (1 workgroup): `consumed_count += inserted_count`, then
|
||||
reset `inserted_count`.
|
||||
|
||||
Each insertion in the same `insert` call sees the updated `consumed_count`
|
||||
because the passes are ordered, so multiple batches consume disjoint pages.
|
||||
|
||||
### 6.3 External invalidation
|
||||
|
||||
For each `ExternalRequest`, the cache calls `invalidable.invalidate(...)`.
|
||||
`FixedStructureTable`/`ToroidalStructureTable` scan their pointer arrays and
|
||||
clear any pointer whose target page has `timestamp == new_timestamp` (i.e. was
|
||||
just recycled).
|
||||
|
||||
### 6.4 Cache invalidation
|
||||
|
||||
`invalidation.wgsl` scans every page's 64 pointers. If a pointer is available
|
||||
and points at a page whose timestamp equals `new_timestamp`, the pointer is reset
|
||||
to `empty(subdividable = true)` — i.e. the node becomes "missing again" and can
|
||||
be requested later.
|
||||
|
||||
### 6.5 Write pointers
|
||||
|
||||
For each internal insertion, `write_pointers.wgsl`:
|
||||
|
||||
```wgsl
|
||||
structure_pointer_pages[meta.page_index].pointers[meta.children_index]
|
||||
= child_pointer_make_available(destination_index);
|
||||
structure_depth_pages[destination_index] = meta.depth + 1;
|
||||
```
|
||||
|
||||
This is the step that actually links the new pages into the tree. It relies on
|
||||
request index == insertion index.
|
||||
|
||||
### 6.6 Timestamp advance
|
||||
|
||||
At the end of `insert`, `frame_timestamp += 1`. The renderer reads this value
|
||||
via `current_timestamp()` and passes it to the shader as `frame_timestamp`, so
|
||||
usage reporting and "dirty last frame" detection share one clock.
|
||||
|
||||
---
|
||||
|
||||
## 7. Eviction policy — timestamp-major, deepest-first ties
|
||||
|
||||
The eviction order is built in two radix passes:
|
||||
|
||||
1. **Depth, descending.** Pages are sorted deepest first. This is the
|
||||
tie-breaker, not the primary key.
|
||||
2. **Timestamp, ascending and stable.** Pages are sorted by last-use timestamp.
|
||||
Because the radix sort is stable, equal timestamps keep the deepest-first
|
||||
order from pass 1.
|
||||
|
||||
Final order:
|
||||
|
||||
- **Primary:** least recently used first (oldest timestamp).
|
||||
- **Tie-break:** deepest first (largest depth).
|
||||
|
||||
Consumption is in list order, so the oldest pages are reused first. The
|
||||
deepest-first tie-break means that, among pages last used at the same time, a
|
||||
page's resident children (which are deeper) appear earlier in the list and are
|
||||
reused first. This avoids recycling a parent and orphaning a subtree that is
|
||||
still resident, assuming the children's timestamps are equal or older.
|
||||
|
||||
Additional details:
|
||||
|
||||
- Unused pages have depth `u32::MAX` and initial timestamp 0, so they lead both
|
||||
orderings and are normally consumed before resident data.
|
||||
- The insertion shader additionally rejects pages with
|
||||
`timestamp >= new_timestamp - 1`, so pages touched in the immediately previous
|
||||
frame are skipped even if selected.
|
||||
- For pages with distinct timestamps, the depth tie-break has no effect; the
|
||||
result behaves like a pure LRU list.
|
||||
|
||||
---
|
||||
|
||||
## 8. Structure tables
|
||||
|
||||
The cache needs an entry point: given a world/chunk coordinate, where is the
|
||||
root page? Structure tables answer that and emit requests when it is missing.
|
||||
|
||||
### 8.1 `FixedStructureTable`
|
||||
|
||||
`src/voxel_cache/tables.rs`.
|
||||
|
||||
- Backing buffer: one `CachePointer` per slot, initialised to
|
||||
`subdividable, unavailable`.
|
||||
- One request counter per slot (`CacheRequestHandler<1>`).
|
||||
- `raytrace_bind_group`: bindings `[pointers, request_counts]` (group 1 in the
|
||||
render pipeline).
|
||||
- `gather_requests`: top-K + sort + `fixed_table/write_requests.wgsl`; emits
|
||||
`structure_id = slot`, `node_id = 0`, `children_index = 0`.
|
||||
- `insert`: `fixed_table/insertion.wgsl` reads
|
||||
`request_informations[i].structure_id` and sets
|
||||
`pointers[slot] = available(destination_indices[i])`.
|
||||
- `invalidate`: clears slots pointing at pages recycled this insert.
|
||||
|
||||
The table is dense: allocation is `slot_count * 4` bytes for pointers plus
|
||||
`slot_count * 4` for request counters.
|
||||
|
||||
### 8.2 `ToroidalStructureTable`
|
||||
|
||||
`src/terrain.rs`. Wraps `FixedStructureTable` with a movable block of chunks.
|
||||
|
||||
- `extent = (x, y, z)` chunk counts.
|
||||
- Slot index from local coordinates:
|
||||
`x + z*extent.x + y*extent.x*extent.z` (shader) — note the y/z order.
|
||||
- `move_position` computes a new integer offset around the camera and runs
|
||||
`terrain/shaders/toroidal_structure.wgsl`: any slot whose world position
|
||||
changed is reset to `subdividable, unavailable`, so it will be re-requested.
|
||||
- `get_request_position(structure_id)` maps a slot back to an absolute chunk
|
||||
coordinate using the current offset and `rem_euclid`.
|
||||
- Everything else delegates to the fixed table.
|
||||
|
||||
The Slang module `toroidal_structure_table.slang` mirrors this indexing and walks
|
||||
the block of chunks (`ToroidalStructureTableTracer`). `fixed_structure_table.slang`
|
||||
is imported by `voxel.slang` but unused.
|
||||
|
||||
---
|
||||
|
||||
## 9. Bind groups
|
||||
|
||||
### 9.1 Raytrace bind group (group 0 of the render pipeline)
|
||||
|
||||
| Binding | Buffer | Access |
|
||||
|---|---|---|
|
||||
| 0 | `pointer_pages` | read-only storage |
|
||||
| 1 | `request_counts_pages` | read-write storage |
|
||||
| 2 | `timestamp_pages` (usage) | read-write storage |
|
||||
| 3 | attribute buffers (`binding_array`) | read-write storage |
|
||||
|
||||
The Slang `VoxelCacheParameters<2>` parameter block maps to these four bindings
|
||||
in this order.
|
||||
|
||||
### 9.2 `CacheStructure` bind group
|
||||
|
||||
| Binding | Buffer |
|
||||
|---|---|
|
||||
| 0 | pointer pages |
|
||||
| 1 | location pages |
|
||||
| 2 | depth pages |
|
||||
|
||||
Used by write-requests, insertion, invalidation, and write-pointers passes.
|
||||
|
||||
### 9.3 Other pass bind groups
|
||||
|
||||
| Pass | Group 0 | Group 1 | Group 2 | Group 3 | Group 4 |
|
||||
|---|---|---|---|---|---|
|
||||
| `WriteRequestsPass` | structure | request handler (count + sorted) | request buffer | — | — |
|
||||
| `CacheInsertionPass` | cache attributes | structure | insertion data | evictor | inserted count |
|
||||
| `CacheInvalidationPass` | structure | evictor | — | — | — |
|
||||
| `WritePointersPass` | structure | request buffer | insertion data | — | — |
|
||||
| Eviction reset / indirect copy | evictor | structure | scratch | — | — |
|
||||
|
||||
---
|
||||
|
||||
## 10. Configuration and sizing
|
||||
|
||||
The demo (`main.rs`) uses:
|
||||
|
||||
```rust
|
||||
let mut layout = CacheLayout::default();
|
||||
layout.add_attribute(CacheAttribute { label: Some("color"), word_count: 1, init: External });
|
||||
layout.add_attribute(CacheAttribute { label: Some("normal"), word_count: 3, init: External });
|
||||
|
||||
let request_buffer = CacheRequestBuffer::new(&device, 1024);
|
||||
let cache = VoxelCache::<4>::new(&device, 150_000, request_buffer.max_requests, &layout);
|
||||
let insertion = CacheInsertionData::new(&device, 1024, &layout);
|
||||
```
|
||||
|
||||
Scaling rules:
|
||||
|
||||
- Doubling `page_count` doubles every page pool, every attribute pool, the
|
||||
request counter array, the sorted request array, and the scratch buffer.
|
||||
- `page_count * N³` must fit in `u32` (the request handler asserts this).
|
||||
- `page_count` must be `< 2^30` because pointers use 30 bits.
|
||||
- `max_requests` bounds top-K and the host request buffers. It does **not** bound
|
||||
`InsertionData`; the demo keeps them equal by convention.
|
||||
- Each attribute adds `page_count * 64 * word_count * 4` bytes.
|
||||
- `DontTouch` attributes are allocated but never written by the cache, so the
|
||||
application must initialise and maintain them.
|
||||
|
||||
Memory example at 150k pages and 2 attributes is tabulated in
|
||||
[`architecture.md`](./architecture.md#8-memory-and-performance-envelope).
|
||||
|
||||
---
|
||||
|
||||
## 11. Known issues
|
||||
|
||||
| Symptom | Location | Impact | Confidence |
|
||||
|---|---|---|---|
|
||||
| `CacheStructure::new` allocates `location_pages` with `size_of::<StructurePage<N>>()` instead of `size_of::<LocationPage>()`. | `src/voxel_cache/structure.rs:44` | At N=4, 264 B/page instead of 8 B/page: ~39.6 MB instead of ~1.2 MB for 150k pages. No correctness issue because shaders index by `LocationPage` stride. | High |
|
||||
| `StructurePage` (Rust, `u64` mask) and `PointerPage` (WGSL, two `u32`) are duplicated layout definitions. | `src/voxel_cache/schema.rs:89-100`, `src/voxel_cache/shaders/cache_common.wgsl:3-8` | Little-endian compatible today; any field reorder breaks silently. `StructurePage` is only used for sizing. | High |
|
||||
| `request_buffer_count` is written by every invocation of `write_requests.wgsl` with the same value. | `src/voxel_cache/shaders/write_requests.wgsl:50` | Benign data race (identical writes), but unnecessary and confusing. | Medium |
|
||||
| Insertion relies on request index == insertion index; nothing validates the contract. | `write_pointers.wgsl`, `CacheInsertionData` construction | Silent wrong pointers if a producer reorders or drops requests. | High |
|
||||
| `CacheInsertionPass` can silently insert fewer pages than requested (`0xFFFFFFFF` slots) with no host feedback. | `src/voxel_cache/shaders/insertion.wgsl:59-75` | Producer believes data is resident; requests may repeat or data may be missing. | High |
|
||||
| The first `VoxelCache::insert` call inserts nothing: `new_timestamp = 1`, unused pages have timestamp 0, and the guard rejects `0 >= new_timestamp - 1` (`0 >= 0`). | `src/voxel_cache.rs:237`, `src/voxel_cache/shaders/insertion.wgsl:70-75` | One-frame startup delay; any external roots submitted in the first batch are dropped and must be re-requested. | High |
|
||||
| Pointer/page-count limits are implicit (`< 2^30`, total elements `< 2^32`). | `schema.rs`, `requests.rs:82-85` | Large configurations fail via asserts or truncation. | High |
|
||||
| `CacheAttributeInit::DontTouch` attributes can become stale after a page is recycled; the cache deliberately does not clear them. | `src/voxel_cache/shaders/insertion.wgsl:94-110` | Any consumer of such an attribute must tolerate garbage for recycled pages. | Medium |
|
||||
| The cache exposes `usage_timestamps()` for debugging only; timestamps are also used internally for invalidation and eviction. | `src/voxel_cache.rs:410-414` | Easy to corrupt cache behaviour by writing to that buffer. | Medium |
|
||||
+2
-1
@@ -23,6 +23,7 @@ where
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
cache_size: usize,
|
||||
max_requests: usize,
|
||||
cache_layout: &mut voxel_cache::CacheLayout,
|
||||
) -> Self
|
||||
{
|
||||
@@ -38,7 +39,7 @@ where
|
||||
init: voxel_cache::CacheAttributeInit::DontTouch,
|
||||
});
|
||||
|
||||
let voxel_cache = VoxelCache::new(device, cache_size, cache_layout);
|
||||
let voxel_cache = VoxelCache::new(device, cache_size, max_requests, cache_layout);
|
||||
|
||||
Self {
|
||||
voxel_cache,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
pub mod buffer_compactor;
|
||||
pub mod indirect_buffer;
|
||||
pub mod radix_sort;
|
||||
pub mod top_k;
|
||||
|
||||
// Utilities
|
||||
pub fn create_multi_buffers_bind_group_layout(
|
||||
|
||||
@@ -320,6 +320,11 @@ impl RadixSorter
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs a radix sort on the `key` based on the `values`.
|
||||
/// The keys are paired one-to-one with the values. At the end both keys and values are sorted.
|
||||
/// An indirect count can be passed in `indirect` as a buffer of a single u32 on GPU.
|
||||
/// A CPU side length can be passed in `direct_length`
|
||||
/// `sort_direction` dictates the direction of the sort.
|
||||
pub fn sort(
|
||||
&self,
|
||||
device: &Device,
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
// Top-k selection over a dense array of u32 request counts.
|
||||
//
|
||||
// The Rust side prepends the following constants:
|
||||
// const BIN_COUNT: u32;
|
||||
// const SUB_BINS: u32;
|
||||
// const LOG_SUB_BINS: u32;
|
||||
// const WORKGROUP_SIZE: u32;
|
||||
|
||||
@group(0) @binding(0) var<storage, read> requests: array<u32>;
|
||||
@group(0) @binding(1) var<storage, read_write> histogram: array<atomic<u32>>;
|
||||
@group(0) @binding(2) var<storage, read_write> threshold: i32;
|
||||
@group(0) @binding(3) var<storage, read_write> selected_count: atomic<u32>;
|
||||
@group(0) @binding(4) var<storage, read_write> selected_indices: array<u32>;
|
||||
|
||||
// Threshold fill state:
|
||||
// [0] = free slots for the threshold bin (k - above_count)
|
||||
// [1] = threshold-bin candidates claimed so far
|
||||
@group(0) @binding(5) var<storage, read_write> fill_state: array<atomic<u32>>;
|
||||
|
||||
struct TopKParams
|
||||
{
|
||||
element_count: u32,
|
||||
k: u32,
|
||||
}
|
||||
|
||||
var<immediate> params: TopKParams;
|
||||
|
||||
// Monotonic log-scale quantization. Counts of zero are never candidates, but
|
||||
// the function is kept total so it is safe to call with any value.
|
||||
fn quantize(count: u32) -> u32
|
||||
{
|
||||
if (count == 0u)
|
||||
{
|
||||
return 0u;
|
||||
}
|
||||
|
||||
let exponent = 31u - countLeadingZeros(count);
|
||||
var extra: u32;
|
||||
|
||||
if (exponent >= LOG_SUB_BINS)
|
||||
{
|
||||
extra = (count >> (exponent - LOG_SUB_BINS)) & (SUB_BINS - 1u);
|
||||
}
|
||||
else
|
||||
{
|
||||
extra = (count << (LOG_SUB_BINS - exponent)) & (SUB_BINS - 1u);
|
||||
}
|
||||
|
||||
return exponent * SUB_BINS + extra;
|
||||
}
|
||||
|
||||
// Pass 1: quantize every non-zero count and accumulate the global histogram.
|
||||
@compute
|
||||
@workgroup_size(WORKGROUP_SIZE, 1, 1)
|
||||
fn histogram_pass(@builtin(global_invocation_id) global_id: vec3<u32>)
|
||||
{
|
||||
let index = global_id.x;
|
||||
if (index >= params.element_count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let count = requests[index];
|
||||
if (count == 0u)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let bin = quantize(count);
|
||||
atomicAdd(&histogram[bin], 1u);
|
||||
}
|
||||
|
||||
// Pass 2: scan the histogram from the highest bin down until adding the
|
||||
// current bin would reach k. The current bin becomes the threshold.
|
||||
// A threshold of -1 means that every non-zero element is selected.
|
||||
//
|
||||
// `sum` is the number of elements in bins strictly above the threshold. It is
|
||||
// also the number of slots already guaranteed, so the threshold bin has
|
||||
// `k - sum` free slots left to fill.
|
||||
@compute
|
||||
@workgroup_size(1, 1, 1)
|
||||
fn threshold_pass()
|
||||
{
|
||||
var sum: u32 = 0u;
|
||||
var threshold_bin: i32 = -1;
|
||||
|
||||
for (var bin: u32 = BIN_COUNT; bin > 0u; bin = bin - 1u)
|
||||
{
|
||||
let count = atomicLoad(&histogram[bin - 1u]);
|
||||
|
||||
if (sum + count >= params.k)
|
||||
{
|
||||
threshold_bin = i32(bin - 1u);
|
||||
break;
|
||||
}
|
||||
|
||||
sum = sum + count;
|
||||
}
|
||||
|
||||
threshold = threshold_bin;
|
||||
atomicStore(&fill_state[0], params.k - min(params.k, sum));
|
||||
atomicStore(&fill_state[1], 0u);
|
||||
atomicStore(&selected_count, 0u);
|
||||
}
|
||||
|
||||
// Pass 3: emit every index whose quantized bin is strictly above the
|
||||
// threshold, then fill the remaining slots from the threshold bin in arbitrary
|
||||
// order. Together these emit exactly `min(k, non-zero count)` indices.
|
||||
@compute
|
||||
@workgroup_size(WORKGROUP_SIZE, 1, 1)
|
||||
fn select_pass(@builtin(global_invocation_id) global_id: vec3<u32>)
|
||||
{
|
||||
let index = global_id.x;
|
||||
if (index >= params.element_count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let count = requests[index];
|
||||
if (count == 0u)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let bin = i32(quantize(count));
|
||||
if (bin > threshold)
|
||||
{
|
||||
// Unconditionally selected.
|
||||
let slot = atomicAdd(&selected_count, 1u);
|
||||
selected_indices[slot] = index;
|
||||
}
|
||||
else if (bin == threshold)
|
||||
{
|
||||
// Fill the remaining slots from the threshold bin, in arbitrary order.
|
||||
let remaining = atomicLoad(&fill_state[0]);
|
||||
let offset = atomicAdd(&fill_state[1], 1u);
|
||||
if (offset < remaining)
|
||||
{
|
||||
let slot = atomicAdd(&selected_count, 1u);
|
||||
selected_indices[slot] = index;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,718 @@
|
||||
//! GPU top-k selection over a dense array of `u32` request counts.
|
||||
//!
|
||||
//! The selector runs three compute passes:
|
||||
//! 1. Quantize every non-zero count into [`BIN_COUNT`] log-scale bins and build
|
||||
//! a global histogram.
|
||||
//! 2. Scan the histogram from the highest bin down until adding the current bin
|
||||
//! would reach `k`, producing a threshold bin.
|
||||
//! 3. Emit every index whose bin is strictly above the threshold bin, then fill
|
||||
//! the remaining slots from the threshold bin.
|
||||
//!
|
||||
//! The number of selected elements is therefore exactly
|
||||
//! `min(k, number of non-zero elements)`. Elements taken from the threshold bin
|
||||
//! are chosen in arbitrary order; the caller is expected to sort the output if
|
||||
//! an ordering is required.
|
||||
//!
|
||||
//! The output list is unordered: indices are appended with atomics.
|
||||
//!
|
||||
//! The selector uses shader immediates, so the device must enable
|
||||
//! [`wgpu::Features::IMMEDIATES`] and expose a `max_immediate_size` of at least
|
||||
//! `size_of::<TopKParams>()` (8 bytes).
|
||||
|
||||
use bytemuck::bytes_of;
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePipeline;
|
||||
use wgpu::Device;
|
||||
use wgpu::ShaderStages;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
/// Number of quantization bins.
|
||||
pub const BIN_COUNT: u32 = 256;
|
||||
|
||||
/// Number of sub-bins per power-of-two octave.
|
||||
const SUB_BINS: u32 = BIN_COUNT / 32;
|
||||
|
||||
/// Number of mantissa bits kept by the quantizer.
|
||||
const LOG_SUB_BINS: u32 = SUB_BINS.trailing_zeros();
|
||||
|
||||
/// Threads per workgroup for the histogram and selection passes.
|
||||
const WORKGROUP_SIZE: u32 = 256;
|
||||
|
||||
const _: () = assert!(BIN_COUNT % 32 == 0);
|
||||
const _: () = assert!(SUB_BINS.is_power_of_two());
|
||||
|
||||
/// Parameters passed to the shader through immediates.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct TopKParams
|
||||
{
|
||||
element_count: u32,
|
||||
k: u32,
|
||||
}
|
||||
|
||||
/// GPU top-k selector over a dense array of request counts.
|
||||
///
|
||||
/// The selector owns its scratch and output buffers, so a single instance
|
||||
/// cannot be used for two overlapping selections. Create one instance per
|
||||
/// concurrent selection, or copy the results before the next call.
|
||||
pub struct TopKSelector
|
||||
{
|
||||
max_selected: u32,
|
||||
|
||||
histogram: Buffer,
|
||||
threshold: Buffer,
|
||||
selected_count: Buffer,
|
||||
selected_indices: Buffer,
|
||||
/// `[0]` free threshold-bin slots, `[1]` claimed threshold-bin candidates.
|
||||
fill_state: Buffer,
|
||||
|
||||
bind_group_layout: BindGroupLayout,
|
||||
histogram_pass: ComputePipeline,
|
||||
threshold_pass: ComputePipeline,
|
||||
select_pass: ComputePipeline,
|
||||
}
|
||||
|
||||
impl TopKSelector
|
||||
{
|
||||
/// Creates a selector that can output at most `max_selected` indices.
|
||||
pub fn new(device: &Device, max_selected: u32) -> Self
|
||||
{
|
||||
assert!(
|
||||
device.features().contains(wgpu::Features::IMMEDIATES),
|
||||
"TopKSelector requires the IMMEDIATES feature"
|
||||
);
|
||||
assert!(
|
||||
device.limits().max_immediate_size >= size_of::<TopKParams>() as u32,
|
||||
"TopKSelector requires a max_immediate_size of at least {} bytes",
|
||||
size_of::<TopKParams>()
|
||||
);
|
||||
|
||||
let histogram = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("TopKSelector::histogram"),
|
||||
size: (BIN_COUNT as u64) * (size_of::<u32>() as u64),
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let threshold = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("TopKSelector::threshold"),
|
||||
contents: bytes_of(&-1i32),
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
});
|
||||
|
||||
let selected_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("TopKSelector::selected_count"),
|
||||
contents: bytes_of(&0u32),
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
});
|
||||
|
||||
// Avoid zero-sized buffers when `max_selected == 0`.
|
||||
let selected_indices = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("TopKSelector::selected_indices"),
|
||||
size: (max_selected.max(1) as u64) * (size_of::<u32>() as u64),
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
// [0] free threshold-bin slots, [1] claimed threshold-bin candidates.
|
||||
// Both are reset by `threshold_pass` on every call.
|
||||
let fill_state = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("TopKSelector::fill_state"),
|
||||
contents: bytemuck::cast_slice(&[0u32; 2]),
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
});
|
||||
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("TopKSelector::bind_group_layout"),
|
||||
entries: &[
|
||||
// Requests: read-only dense array of counts
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: true },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Histogram
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Threshold bin
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Selected count
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 3,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Selected indices
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 4,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Threshold fill state
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 5,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("TopKSelector::pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&bind_group_layout)],
|
||||
immediate_size: size_of::<TopKParams>() as u32,
|
||||
});
|
||||
|
||||
// Inject the quantization constants so the Rust and WGSL sides cannot
|
||||
// drift apart.
|
||||
let header = format!(
|
||||
"const BIN_COUNT: u32 = {}u;\n\
|
||||
const SUB_BINS: u32 = {}u;\n\
|
||||
const LOG_SUB_BINS: u32 = {}u;\n\
|
||||
const WORKGROUP_SIZE: u32 = {}u;\n",
|
||||
BIN_COUNT, SUB_BINS, LOG_SUB_BINS, WORKGROUP_SIZE
|
||||
);
|
||||
|
||||
let mut shader_source = String::with_capacity(header.len() + 2048);
|
||||
shader_source.push_str(&header);
|
||||
shader_source.push_str(include_str!("./shaders/top_k.wgsl"));
|
||||
|
||||
let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("TopKSelector::shader_module"),
|
||||
source: wgpu::ShaderSource::Wgsl(shader_source.into()),
|
||||
});
|
||||
|
||||
let compilation_options = wgpu::PipelineCompilationOptions::default();
|
||||
|
||||
let histogram_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("TopKSelector::histogram_pass"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("histogram_pass"),
|
||||
compilation_options: compilation_options.clone(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let threshold_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("TopKSelector::threshold_pass"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("threshold_pass"),
|
||||
compilation_options: compilation_options.clone(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let select_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("TopKSelector::select_pass"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("select_pass"),
|
||||
compilation_options,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
max_selected,
|
||||
histogram,
|
||||
threshold,
|
||||
selected_count,
|
||||
selected_indices,
|
||||
fill_state,
|
||||
bind_group_layout,
|
||||
histogram_pass,
|
||||
threshold_pass,
|
||||
select_pass,
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the three top-k passes over `requests[0..element_count]`.
|
||||
///
|
||||
/// `k` is the requested number of elements and must not exceed the
|
||||
/// `max_selected` capacity given to [`TopKSelector::new`].
|
||||
///
|
||||
/// After this call:
|
||||
/// - [`Self::selected_count_buffer`] contains
|
||||
/// `min(k, number of non-zero elements)`.
|
||||
/// - [`Self::selected_indices_buffer`] contains that many indices, in an
|
||||
/// arbitrary order.
|
||||
/// - [`Self::threshold_buffer`] contains the threshold bin, or `-1` if all
|
||||
/// non-zero elements were selected.
|
||||
pub fn select(
|
||||
&self,
|
||||
device: &Device,
|
||||
encoder: &mut CommandEncoder,
|
||||
requests: &Buffer,
|
||||
element_count: u32,
|
||||
k: u32,
|
||||
)
|
||||
{
|
||||
assert!(
|
||||
k <= self.max_selected,
|
||||
"TopKSelector: k ({k}) exceeds the max_selected capacity ({})",
|
||||
self.max_selected
|
||||
);
|
||||
assert!(
|
||||
requests.size() >= (element_count as u64) * (size_of::<u32>() as u64),
|
||||
"TopKSelector: requests buffer is too small for {element_count} elements"
|
||||
);
|
||||
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("TopKSelector::bind_group"),
|
||||
layout: &self.bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: requests.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: self.histogram.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: self.threshold.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: self.selected_count.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: self.selected_indices.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 5,
|
||||
resource: self.fill_state.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// The histogram is rebuilt from scratch on every call.
|
||||
encoder.clear_buffer(&self.histogram, 0, None);
|
||||
|
||||
let params = TopKParams { element_count, k };
|
||||
let params_bytes = bytes_of(¶ms);
|
||||
let workgroup_count = element_count.div_ceil(WORKGROUP_SIZE).max(1);
|
||||
|
||||
let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("TopKSelector::select"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
compute_pass.set_bind_group(0, &bind_group, &[]);
|
||||
|
||||
compute_pass.set_pipeline(&self.histogram_pass);
|
||||
compute_pass.set_immediates(0, params_bytes);
|
||||
compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
|
||||
|
||||
compute_pass.set_pipeline(&self.threshold_pass);
|
||||
compute_pass.set_immediates(0, params_bytes);
|
||||
compute_pass.dispatch_workgroups(1, 1, 1);
|
||||
|
||||
compute_pass.set_pipeline(&self.select_pass);
|
||||
compute_pass.set_immediates(0, params_bytes);
|
||||
compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
|
||||
}
|
||||
|
||||
/// Number of indices emitted by the last [`Self::select`] call.
|
||||
pub fn selected_count_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.selected_count
|
||||
}
|
||||
|
||||
/// Indices emitted by the last [`Self::select`] call, in arbitrary order.
|
||||
pub fn selected_indices_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.selected_indices
|
||||
}
|
||||
|
||||
/// Threshold bin of the last [`Self::select`] call, or `-1` if every
|
||||
/// non-zero element was selected.
|
||||
pub fn threshold_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.threshold
|
||||
}
|
||||
|
||||
/// Maximum number of indices this selector can emit.
|
||||
pub fn max_selected(&self) -> u32
|
||||
{
|
||||
self.max_selected
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests
|
||||
{
|
||||
use super::*;
|
||||
|
||||
/// CPU mirror of the WGSL quantizer.
|
||||
fn quantize_cpu(count: u32) -> u32
|
||||
{
|
||||
if count == 0
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
let exponent = 31 - count.leading_zeros();
|
||||
let extra = if exponent >= LOG_SUB_BINS
|
||||
{
|
||||
(count >> (exponent - LOG_SUB_BINS)) & (SUB_BINS - 1)
|
||||
}
|
||||
else
|
||||
{
|
||||
(count << (LOG_SUB_BINS - exponent)) & (SUB_BINS - 1)
|
||||
};
|
||||
|
||||
exponent * SUB_BINS + extra
|
||||
}
|
||||
|
||||
/// CPU mirror of the three passes.
|
||||
fn select_cpu(counts: &[u32], k: u32) -> (Vec<u32>, i32)
|
||||
{
|
||||
let mut histogram = vec![0u32; BIN_COUNT as usize];
|
||||
|
||||
for &count in counts
|
||||
{
|
||||
if count != 0
|
||||
{
|
||||
histogram[quantize_cpu(count) as usize] += 1;
|
||||
}
|
||||
}
|
||||
|
||||
let mut sum = 0u32;
|
||||
let mut threshold = -1i32;
|
||||
|
||||
for bin in (0..BIN_COUNT as usize).rev()
|
||||
{
|
||||
let count = histogram[bin];
|
||||
|
||||
if sum + count >= k
|
||||
{
|
||||
threshold = bin as i32;
|
||||
break;
|
||||
}
|
||||
|
||||
sum += count;
|
||||
}
|
||||
|
||||
let remaining = k.saturating_sub(sum);
|
||||
|
||||
let mut selected = counts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|&(_, &count)| count != 0 && quantize_cpu(count) as i32 > threshold)
|
||||
.map(|(index, _)| index as u32)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Fill the remaining slots from the threshold bin. The GPU picks these
|
||||
// in arbitrary order; the CPU mirror fills them in index order so the
|
||||
// tests stay deterministic.
|
||||
if threshold >= 0
|
||||
{
|
||||
let mut slots = remaining;
|
||||
for (index, &count) in counts.iter().enumerate()
|
||||
{
|
||||
if slots == 0
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if count != 0 && quantize_cpu(count) as i32 == threshold
|
||||
{
|
||||
selected.push(index as u32);
|
||||
slots -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(selected, threshold)
|
||||
}
|
||||
|
||||
fn next_random(state: &mut u64) -> u32
|
||||
{
|
||||
*state ^= *state << 13;
|
||||
*state ^= *state >> 7;
|
||||
*state ^= *state << 17;
|
||||
(*state >> 32) as u32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quantize_is_monotonic()
|
||||
{
|
||||
let mut previous = 0;
|
||||
|
||||
for count in 1..100_000u32
|
||||
{
|
||||
let bin = quantize_cpu(count);
|
||||
assert!(bin >= previous, "quantize({count}) = {bin} < {previous}");
|
||||
assert!(bin < BIN_COUNT);
|
||||
previous = bin;
|
||||
}
|
||||
|
||||
let mut state = 0x1234_5678_9abc_def0u64;
|
||||
let mut values = (0..10_000)
|
||||
.map(|_| next_random(&mut state))
|
||||
.collect::<Vec<_>>();
|
||||
values.sort_unstable();
|
||||
|
||||
let mut previous = 0;
|
||||
for count in values
|
||||
{
|
||||
let bin = quantize_cpu(count);
|
||||
assert!(bin >= previous);
|
||||
assert!(bin < BIN_COUNT);
|
||||
previous = bin;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quantize_handles_zero_and_max()
|
||||
{
|
||||
assert_eq!(quantize_cpu(0), 0);
|
||||
assert!(quantize_cpu(u32::MAX) < BIN_COUNT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_selects_exactly_min_k_and_non_zero()
|
||||
{
|
||||
let mut state = 0x0ddc_0ffe_e15e_beefu64;
|
||||
|
||||
for _ in 0..100
|
||||
{
|
||||
let len = 1 + (next_random(&mut state) % 1000) as usize;
|
||||
let counts = (0..len)
|
||||
.map(|_| next_random(&mut state) % 64)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let non_zero = counts.iter().filter(|&&count| count != 0).count();
|
||||
|
||||
for k in 0..=20
|
||||
{
|
||||
let (selected, threshold) = select_cpu(&counts, k);
|
||||
|
||||
assert_eq!(selected.len(), (k as usize).min(non_zero));
|
||||
|
||||
let mut sorted = selected.clone();
|
||||
sorted.sort_unstable();
|
||||
sorted.dedup();
|
||||
assert_eq!(sorted.len(), selected.len(), "duplicate indices");
|
||||
|
||||
for &index in &selected
|
||||
{
|
||||
let count = counts[index as usize];
|
||||
assert!(count != 0);
|
||||
assert!(quantize_cpu(count) as i32 >= threshold);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_fills_threshold_bin_to_exactly_k()
|
||||
{
|
||||
let counts = [1, 5, 3, 5, 2];
|
||||
let (selected, _) = select_cpu(&counts, 3);
|
||||
|
||||
// The two 5s are above the threshold bin; the 3 fills the last slot.
|
||||
let mut sorted = selected;
|
||||
sorted.sort_unstable();
|
||||
assert_eq!(sorted, vec![1, 2, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_with_fewer_candidates_than_k()
|
||||
{
|
||||
let counts = [1, 0, 2, 0, 3];
|
||||
let (selected, threshold) = select_cpu(&counts, 10);
|
||||
|
||||
assert_eq!(threshold, -1);
|
||||
assert_eq!(selected.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_with_k_zero()
|
||||
{
|
||||
let counts = [1, 2, 3];
|
||||
let (selected, _) = select_cpu(&counts, 0);
|
||||
|
||||
assert!(selected.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_with_all_equal_counts_selects_k()
|
||||
{
|
||||
let counts = [7, 7, 7, 7];
|
||||
let (selected, threshold) = select_cpu(&counts, 2);
|
||||
|
||||
// Every element is in the threshold bin, so the first two are taken.
|
||||
assert_eq!(threshold, quantize_cpu(7) as i32);
|
||||
assert_eq!(selected, vec![0, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_with_all_zero_counts()
|
||||
{
|
||||
let counts = [0, 0, 0, 0];
|
||||
let (selected, threshold) = select_cpu(&counts, 2);
|
||||
|
||||
assert_eq!(threshold, -1);
|
||||
assert!(selected.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a GPU adapter with the IMMEDIATES feature"]
|
||||
fn gpu_selection_smoke_test()
|
||||
{
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
|
||||
let adapter =
|
||||
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default()))
|
||||
.expect("no GPU adapter available");
|
||||
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
|
||||
required_features: wgpu::Features::IMMEDIATES,
|
||||
required_limits: wgpu::Limits {
|
||||
max_immediate_size: 112,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
}))
|
||||
.expect("failed to create GPU device");
|
||||
|
||||
let counts: [u32; 5] = [1, 5, 3, 5, 2];
|
||||
let requests = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("TopKSelector::test_requests"),
|
||||
contents: bytemuck::cast_slice(&counts),
|
||||
usage: BufferUsages::STORAGE,
|
||||
});
|
||||
|
||||
let selector = TopKSelector::new(&device, 8);
|
||||
|
||||
// Run the selection twice to verify that the histogram and fill state
|
||||
// are reset between calls.
|
||||
for _ in 0..2
|
||||
{
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("TopKSelector::test_encoder"),
|
||||
});
|
||||
selector.select(&device, &mut encoder, &requests, counts.len() as u32, 3);
|
||||
queue.submit([encoder.finish()]);
|
||||
|
||||
let (count, indices) = read_selection(&device, &queue, &selector);
|
||||
|
||||
// The two 5s are above the threshold bin; the 3 fills the last slot.
|
||||
assert_eq!(count, 3);
|
||||
assert_eq!(indices, vec![1, 2, 3]);
|
||||
}
|
||||
|
||||
// All-equal counts: the threshold bin must fill every slot.
|
||||
let equal_counts: [u32; 4] = [7, 7, 7, 7];
|
||||
let equal_requests = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("TopKSelector::test_equal_requests"),
|
||||
contents: bytemuck::cast_slice(&equal_counts),
|
||||
usage: BufferUsages::STORAGE,
|
||||
});
|
||||
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("TopKSelector::test_encoder"),
|
||||
});
|
||||
selector.select(
|
||||
&device,
|
||||
&mut encoder,
|
||||
&equal_requests,
|
||||
equal_counts.len() as u32,
|
||||
2,
|
||||
);
|
||||
queue.submit([encoder.finish()]);
|
||||
|
||||
let (count, indices) = read_selection(&device, &queue, &selector);
|
||||
assert_eq!(count, 2);
|
||||
assert_eq!(indices.len(), 2);
|
||||
assert!(
|
||||
indices
|
||||
.iter()
|
||||
.all(|&index| index < equal_counts.len() as u32)
|
||||
);
|
||||
}
|
||||
|
||||
/// Reads back the selected count and the sorted selected indices.
|
||||
fn read_selection(
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
selector: &TopKSelector,
|
||||
) -> (u32, Vec<u32>)
|
||||
{
|
||||
let count = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||
let count_clone = count.clone();
|
||||
wgpu::util::DownloadBuffer::read_buffer(
|
||||
device,
|
||||
queue,
|
||||
&selector.selected_count_buffer().slice(..),
|
||||
move |buffer| {
|
||||
let bytes = buffer.unwrap();
|
||||
*count_clone.lock().unwrap() = Some(bytemuck::pod_read_unaligned::<u32>(&bytes));
|
||||
},
|
||||
);
|
||||
|
||||
let indices = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||
let indices_clone = indices.clone();
|
||||
wgpu::util::DownloadBuffer::read_buffer(
|
||||
device,
|
||||
queue,
|
||||
&selector.selected_indices_buffer().slice(..),
|
||||
move |buffer| {
|
||||
let bytes = buffer.unwrap();
|
||||
*indices_clone.lock().unwrap() =
|
||||
Some(bytemuck::pod_collect_to_vec::<u8, u32>(&bytes));
|
||||
},
|
||||
);
|
||||
|
||||
device
|
||||
.poll(wgpu::wgt::PollType::wait_indefinitely())
|
||||
.unwrap();
|
||||
|
||||
let count = *count.lock().unwrap().as_ref().unwrap();
|
||||
let mut indices = indices.lock().unwrap().as_ref().unwrap()[0..count as usize].to_vec();
|
||||
indices.sort_unstable();
|
||||
|
||||
(count, indices)
|
||||
}
|
||||
}
|
||||
+9
-3
@@ -361,8 +361,9 @@ impl State
|
||||
init: voxel_cache::CacheAttributeInit::External,
|
||||
});
|
||||
|
||||
let voxel_cache = VoxelCache::<4>::new(&device, 150_000, &layout);
|
||||
let request_buffer = CacheRequestBuffer::new(&device, 1024);
|
||||
let voxel_cache =
|
||||
VoxelCache::<4>::new(&device, 150_000, request_buffer.max_requests, &layout);
|
||||
let insertion_data = CacheInsertionData::new(&device, 1024, &layout);
|
||||
|
||||
//let terrain_generator = TerrainGenerator::<4>::new(5, "vxls_height.tif", 0.2, "img.jpg");
|
||||
@@ -395,13 +396,18 @@ impl State
|
||||
let mut chunk_pos_map = HashMap::new();
|
||||
let total_chunk_count = terrain_height * terrain_width * terrain_alt;
|
||||
|
||||
//let structure_table = FixedStructureTable::new(&device, total_chunk_count);
|
||||
let structure_table_request_buffer = CacheRequestBuffer::new(&device, 128);
|
||||
//let structure_table = FixedStructureTable::new(
|
||||
// &device,
|
||||
// total_chunk_count,
|
||||
// structure_table_request_buffer.max_requests,
|
||||
//);
|
||||
let structure_table = ToroidalStructureTable::new(
|
||||
&device,
|
||||
(terrain_width, terrain_alt, terrain_height),
|
||||
Vec3::ZERO,
|
||||
structure_table_request_buffer.max_requests,
|
||||
);
|
||||
let structure_table_request_buffer = CacheRequestBuffer::new(&device, 128);
|
||||
let structure_table_insertion_data = CacheInsertionData::new(&device, 128, &layout);
|
||||
let chunk_instances = (0..terrain_alt)
|
||||
.cartesian_product(0..terrain_height)
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
|
||||
use crate::voxel_cache::schema::InsertionInformation;
|
||||
|
||||
/// A structure locator format to locate node within an ntree
|
||||
pub mod tree_locator;
|
||||
|
||||
/// Facilities for voxel production on the host (CPU) side
|
||||
pub mod host_production;
|
||||
|
||||
/// This module contains definition and common logic to produce voxel data to feed a [`VoxelCache`]
|
||||
|
||||
/// A cache might hold data owned by multiple different producers. To discriminate where to route the
|
||||
/// request, a node is always tagged by a [`ProducerId`].
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Zeroable, Pod)]
|
||||
#[repr(transparent)]
|
||||
pub struct ProducerId(pub u32);
|
||||
|
||||
/// A producer can manage differnet independent voxel structure, with their own roots.
|
||||
/// As such a producer can tag, to its discretion, its own structure with an Id.
|
||||
///
|
||||
/// All node of a same tree thus share the same structure Id
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Zeroable, Pod)]
|
||||
#[repr(transparent)]
|
||||
pub struct StructureId(pub u32);
|
||||
|
||||
/// A request can come from anywhere inside the structure. The producer can thus tag each node with
|
||||
/// a locator, to know where the request was issued.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Zeroable, Pod)]
|
||||
#[repr(transparent)]
|
||||
pub struct StructureLocator(pub u32);
|
||||
|
||||
/// For structs which can be used as a voxel attribute source
|
||||
pub trait VoxelAttributes<const N: usize>: 'static + Clone + Send + Sync
|
||||
{
|
||||
/// The amount of attributes this struct holds
|
||||
fn attribute_count() -> usize;
|
||||
|
||||
/// Must returns the words for a single attribute.
|
||||
fn attribute(&self, attribute_index: usize) -> &[u32];
|
||||
}
|
||||
|
||||
/// Represents something that can produce a voxel node.
|
||||
pub trait VoxelProducer<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
/// The voxel data produced by this producer
|
||||
type Output: VoxelAttributes<N>;
|
||||
|
||||
/// A pure function that can produce a voxel node based on the owner produer id, requesting structure, and the
|
||||
/// requesting location within the structure
|
||||
fn produce(
|
||||
&self,
|
||||
producer_id: ProducerId,
|
||||
id: StructureId,
|
||||
locator: StructureLocator,
|
||||
) -> (InsertionInformation<N>, [Self::Output; N * N * N]);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
use rayon::ThreadPool;
|
||||
use rayon::iter::IndexedParallelIterator;
|
||||
use rayon::iter::IntoParallelRefIterator;
|
||||
use rayon::iter::IntoParallelRefMutIterator;
|
||||
use rayon::iter::ParallelIterator;
|
||||
|
||||
use crate::production::VoxelProducer;
|
||||
use crate::voxel_cache::insertion::CacheInsertionData;
|
||||
use crate::voxel_cache::requests::CacheRequestBuffer;
|
||||
use crate::voxel_cache::schema::InsertionInformation;
|
||||
use crate::voxel_cache::schema::RequestInformation;
|
||||
|
||||
/// Handles requests made by the cache on the host
|
||||
pub struct HostRequestHandler<const N: usize, P: VoxelProducer<N>>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
producer: P,
|
||||
thread_pool: ThreadPool,
|
||||
}
|
||||
|
||||
impl<const N: usize, P: VoxelProducer<N> + Sync> HostRequestHandler<N, P>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(producer: P, thread_pool: ThreadPool) -> Self
|
||||
{
|
||||
Self {
|
||||
producer,
|
||||
thread_pool,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fullfill(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
request_buffer: &CacheRequestBuffer,
|
||||
insertion: &CacheInsertionData<N>,
|
||||
)
|
||||
{
|
||||
request_buffer.host_download_requests(device, queue, |requests| {});
|
||||
}
|
||||
|
||||
pub fn produce_requests(
|
||||
&self,
|
||||
requests: &[RequestInformation],
|
||||
informations: &mut [InsertionInformation<N>],
|
||||
attributes: &mut [[P::Output; N * N * N]],
|
||||
)
|
||||
{
|
||||
self.thread_pool.install(|| {
|
||||
requests
|
||||
.par_iter()
|
||||
.zip(informations.par_iter_mut())
|
||||
.zip(attributes.par_iter_mut())
|
||||
.for_each(|((request, dest_information), dest_attributes)| {
|
||||
let (info, attributes) = self.producer.produce(
|
||||
super::ProducerId(0),
|
||||
super::StructureId(request.structure_id),
|
||||
super::StructureLocator(request.node_id),
|
||||
);
|
||||
|
||||
*dest_information = info;
|
||||
*dest_attributes = attributes;
|
||||
});
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::production::ProducerId;
|
||||
use crate::production::StructureId;
|
||||
use crate::production::StructureLocator;
|
||||
use crate::voxel_cache::schema::RequestInformation;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
||||
pub struct RequestKey
|
||||
{
|
||||
producer_id: ProducerId,
|
||||
structure_id: StructureId,
|
||||
structure_locator: StructureLocator,
|
||||
children_index: u32,
|
||||
}
|
||||
|
||||
pub enum JobState
|
||||
{
|
||||
Queued,
|
||||
InFlight,
|
||||
Ready,
|
||||
}
|
||||
|
||||
pub struct Job
|
||||
{
|
||||
state: JobState,
|
||||
priority: u32,
|
||||
emit_timestamp: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
|
||||
pub struct RequestPriority
|
||||
{
|
||||
priority: u32,
|
||||
key: RequestKey,
|
||||
}
|
||||
|
||||
pub struct RequestQueue
|
||||
{
|
||||
cap: usize,
|
||||
count: usize,
|
||||
jobs: HashMap<RequestKey, RequestKey>,
|
||||
priorities: BTreeSet<RequestPriority>,
|
||||
}
|
||||
|
||||
impl RequestQueue
|
||||
{
|
||||
pub fn new(cap: usize) -> Self
|
||||
{
|
||||
Self {
|
||||
cap,
|
||||
count: 0,
|
||||
jobs: HashMap::new(),
|
||||
priorities: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ingest(&mut self, timestamp: u32, requests: &[RequestInformation])
|
||||
{
|
||||
let mut new_requests = vec![];
|
||||
|
||||
for (i, request) in requests.iter().enumerate()
|
||||
{
|
||||
let key = RequestKey {
|
||||
producer_id: 0u32.into(), // TODO: Support produer ids
|
||||
structure_id: request.structure_id.into(),
|
||||
structure_locator: request.node_id.into(),
|
||||
children_index: request.children_index,
|
||||
};
|
||||
|
||||
// Check for exitence in the queue
|
||||
if self.jobs.contains_key(&key)
|
||||
{
|
||||
// Update priority
|
||||
self.priorities.remove(&key);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Brand new request, to add
|
||||
new_requests.push(i);
|
||||
}
|
||||
|
||||
// Insert new job
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
use itertools::Itertools;
|
||||
|
||||
use crate::production::StructureLocator;
|
||||
|
||||
/// Compact location of a specific node within a Voxel tree data strcutrure : depth + location
|
||||
///
|
||||
/// The location is encoded as one number per coordinate.
|
||||
/// A coordinate is interpreted as base `N` number.
|
||||
/// The base `N` digits represent the path take from the root down to the node, therminated by a
|
||||
/// `1` digit.
|
||||
///
|
||||
/// Thus a encoded location of `1` refers to the root : Only node of depth 0
|
||||
///
|
||||
/// an encoded location of `1032` for a 4-tree, refers to from the root : going into the 0th
|
||||
/// child, then 3rd child, then 2nd child. It refers to a node of depth 3.
|
||||
///
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct TreeLocator<const N: usize>
|
||||
{
|
||||
x: u32,
|
||||
y: u32,
|
||||
z: u32,
|
||||
}
|
||||
|
||||
impl<const N: usize> From<StructureLocator> for TreeLocator<N>
|
||||
{
|
||||
fn from(value: StructureLocator) -> Self
|
||||
{
|
||||
let mut value = value.0;
|
||||
let mut locator = Self::root();
|
||||
let n = N as u32;
|
||||
|
||||
while value != 1
|
||||
{
|
||||
let z = value % n;
|
||||
value /= n;
|
||||
let y = value % n;
|
||||
value /= n;
|
||||
let x = value % n;
|
||||
value /= n;
|
||||
|
||||
locator = locator.child(x, y, z)
|
||||
}
|
||||
locator
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> From<TreeLocator<N>> for StructureLocator
|
||||
{
|
||||
fn from(mut value: TreeLocator<N>) -> StructureLocator
|
||||
{
|
||||
let mut locator = 1u32;
|
||||
while !value.is_root()
|
||||
{
|
||||
let (x, y, z) = value.local_coords();
|
||||
value = value.parent().unwrap();
|
||||
|
||||
locator *= N as u32;
|
||||
locator += x;
|
||||
|
||||
locator *= N as u32;
|
||||
locator += y;
|
||||
|
||||
locator *= N as u32;
|
||||
locator += z;
|
||||
}
|
||||
|
||||
StructureLocator(locator)
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> TreeLocator<N>
|
||||
{
|
||||
pub const ROOT: TreeLocator<N> = TreeLocator { x: 1, y: 1, z: 1 };
|
||||
|
||||
pub fn root() -> Self
|
||||
{
|
||||
Self::ROOT
|
||||
}
|
||||
|
||||
/// Returns the locator of node at `depth`, with coordinates, in that depth coordinate space,
|
||||
/// `node_x` `node_y` `node_z`.
|
||||
///
|
||||
/// The `node_*` must be in the `0..N^depth` range.
|
||||
pub fn from_node_coords(depth: u32, node_x: u32, node_y: u32, node_z: u32) -> Self
|
||||
{
|
||||
// Check coordinate bounds
|
||||
assert!(
|
||||
node_x < N.pow(depth) as u32,
|
||||
"Node coordinates out of bounds."
|
||||
);
|
||||
assert!(
|
||||
node_y < N.pow(depth) as u32,
|
||||
"Node coordinates out of bounds."
|
||||
);
|
||||
assert!(
|
||||
node_z < N.pow(depth) as u32,
|
||||
"Node coordinates out of bounds."
|
||||
);
|
||||
|
||||
if depth == 0
|
||||
{
|
||||
return Self::ROOT;
|
||||
}
|
||||
|
||||
// Puts a one in base-N on the Nth digit
|
||||
let one = N.pow(depth) as u32;
|
||||
Self {
|
||||
x: one + node_x,
|
||||
y: one + node_y,
|
||||
z: one + node_z,
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes the maximum depth supported for this tree arity
|
||||
pub fn max_depth() -> u32
|
||||
{
|
||||
(u32::MAX as usize).ilog(N) - 1
|
||||
}
|
||||
|
||||
pub fn is_root(&self) -> bool
|
||||
{
|
||||
self.x == 1 && self.y == 1 && self.z == 1
|
||||
}
|
||||
|
||||
/// Returns the depth of the node located by `self`, 0 being the root
|
||||
pub fn depth(&self) -> u32
|
||||
{
|
||||
// A number k takes floor(log_n(k)) + 1 digits in base n
|
||||
|
||||
// This is digits - 1 as the locator contains a 1 on the front
|
||||
self.x.ilog(N as u32)
|
||||
}
|
||||
|
||||
/// Returns the size in voxels of this node considering that a node at `max_depth` represents 1
|
||||
/// voxel
|
||||
pub fn node_size(&self, max_depth: u32) -> u32
|
||||
{
|
||||
let depth = self.depth();
|
||||
|
||||
// 0 if voxel, max_depth if root
|
||||
let height = max_depth - depth;
|
||||
|
||||
N.pow(height) as u32
|
||||
}
|
||||
|
||||
/// Returns the locator of this node's parent, `None` if `self` is the root
|
||||
pub fn parent(&self) -> Option<Self>
|
||||
{
|
||||
if self.is_root()
|
||||
{
|
||||
None
|
||||
}
|
||||
else
|
||||
{
|
||||
Some(Self {
|
||||
x: self.x / N as u32,
|
||||
y: self.y / N as u32,
|
||||
z: self.z / N as u32,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the [`TreeLocator`] of the children of this node with coordinates `child_x`,
|
||||
/// `child_y`, `child_z` within this node.
|
||||
///
|
||||
/// The `child_*` coordinates must be in the `0..N` range.
|
||||
pub fn child(&self, child_x: u32, child_y: u32, child_z: u32) -> Self
|
||||
{
|
||||
// Check children bounds
|
||||
assert!(child_x < N as u32, "Out of bounds child coordinate.");
|
||||
assert!(child_y < N as u32, "Out of bounds child coordinate.");
|
||||
assert!(child_z < N as u32, "Out of bounds child coordinate.");
|
||||
|
||||
// Check depth bounds
|
||||
assert!(
|
||||
self.x.checked_mul(N as u32).is_some(),
|
||||
"TreeLocator too deep"
|
||||
);
|
||||
assert!(
|
||||
self.y.checked_mul(N as u32).is_some(),
|
||||
"TreeLocator too deep"
|
||||
);
|
||||
assert!(
|
||||
self.z.checked_mul(N as u32).is_some(),
|
||||
"TreeLocator too deep"
|
||||
);
|
||||
|
||||
let n = N as u32;
|
||||
Self {
|
||||
x: self.x * n + child_x,
|
||||
y: self.y * n + child_y,
|
||||
z: self.z * n + child_z,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an iterator on the children of this node
|
||||
pub fn children(&self) -> impl Iterator<Item = Self>
|
||||
{
|
||||
(0..N as u32)
|
||||
.cartesian_product(0..N as u32)
|
||||
.cartesian_product(0..N as u32)
|
||||
.map(|((x, y), z)| self.child(x, y, z))
|
||||
}
|
||||
|
||||
/// Returns the coordinate of this node inside its parent.
|
||||
/// The returned coordinate are in `0..N`
|
||||
pub fn local_coords(&self) -> (u32, u32, u32)
|
||||
{
|
||||
if self.is_root()
|
||||
{
|
||||
return (0, 0, 0);
|
||||
}
|
||||
|
||||
let x = self.x % N as u32;
|
||||
let y = self.y % N as u32;
|
||||
let z = self.z % N as u32;
|
||||
|
||||
(x, y, z)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests
|
||||
{
|
||||
use super::*;
|
||||
|
||||
fn raw<const N: usize>(l: TreeLocator<N>) -> (u32, u32, u32)
|
||||
{
|
||||
(l.x, l.y, l.z)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_is_depth_zero()
|
||||
{
|
||||
let r = TreeLocator::<4>::root();
|
||||
assert!(r.is_root());
|
||||
assert_eq!(r.depth(), 0);
|
||||
assert_eq!(raw(r), (1, 1, 1));
|
||||
assert!(r.parent().is_none());
|
||||
assert_eq!(r.local_coords(), (0, 0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn child_encoding_matches_doc_example()
|
||||
{
|
||||
// Doc: `1032` in base 4 => child 0, then 3, then 2 => depth 3.
|
||||
let l = TreeLocator::<4>::root()
|
||||
.child(0, 0, 0)
|
||||
.child(3, 3, 3)
|
||||
.child(2, 2, 2);
|
||||
|
||||
// 0b1032 in base 4 = 1*64 + 0*16 + 3*4 + 2 = 78
|
||||
assert_eq!(raw(l), (78, 78, 78));
|
||||
assert_eq!(l.depth(), 3);
|
||||
assert!(!l.is_root());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn child_uses_independent_coordinates()
|
||||
{
|
||||
let c = TreeLocator::<4>::root().child(1, 2, 3);
|
||||
assert_eq!(raw(c), (4 + 1, 4 + 2, 4 + 3));
|
||||
assert_eq!(c.depth(), 1);
|
||||
assert_eq!(c.local_coords(), (1, 2, 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parent_undoes_child()
|
||||
{
|
||||
let root = TreeLocator::<4>::root();
|
||||
let c = root.child(3, 0, 2);
|
||||
let gc = c.child(1, 1, 0);
|
||||
|
||||
assert_eq!(raw(gc.parent().unwrap()), raw(c));
|
||||
assert_eq!(raw(c.parent().unwrap()), raw(root));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_node_coords_depth_zero_is_root()
|
||||
{
|
||||
let l = TreeLocator::<4>::from_node_coords(0, 0, 0, 0);
|
||||
assert!(l.is_root());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_node_coords_matches_child_walk()
|
||||
{
|
||||
// Node (5, 2, 7) at depth 2 in a 4-tree (coords in 0..16).
|
||||
// Base 4: x = 11, y = 02, z = 13.
|
||||
let direct = TreeLocator::<4>::from_node_coords(2, 5, 2, 7);
|
||||
let walked = TreeLocator::<4>::root().child(1, 0, 1).child(1, 2, 3);
|
||||
|
||||
assert_eq!(raw(direct), raw(walked));
|
||||
assert_eq!(direct.depth(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_node_coords_parent_is_coarser_node()
|
||||
{
|
||||
let l = TreeLocator::<4>::from_node_coords(3, 37, 12, 63);
|
||||
let p = TreeLocator::<4>::from_node_coords(2, 37 / 4, 12 / 4, 63 / 4);
|
||||
assert_eq!(raw(l.parent().unwrap()), raw(p));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_via_local_coords()
|
||||
{
|
||||
let original = TreeLocator::<3>::from_node_coords(4, 50, 7, 80);
|
||||
|
||||
// Walk up to the root, collecting local coords at each level.
|
||||
let mut path = Vec::new();
|
||||
let mut cur = original;
|
||||
while let Some(parent) = cur.parent()
|
||||
{
|
||||
path.push(cur.local_coords());
|
||||
cur = parent;
|
||||
}
|
||||
assert!(cur.is_root());
|
||||
assert_eq!(path.len() as u32, original.depth());
|
||||
|
||||
// Walk back down and rebuild.
|
||||
let mut rebuilt = TreeLocator::<3>::root();
|
||||
for (x, y, z) in path.into_iter().rev()
|
||||
{
|
||||
rebuilt = rebuilt.child(x, y, z);
|
||||
}
|
||||
assert_eq!(raw(rebuilt), raw(original));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn children_are_complete_distinct_and_valid()
|
||||
{
|
||||
let parent = TreeLocator::<3>::root().child(2, 1, 0);
|
||||
let kids: Vec<_> = parent.children().collect();
|
||||
|
||||
assert_eq!(kids.len(), 27);
|
||||
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut locals = std::collections::HashSet::new();
|
||||
for k in &kids
|
||||
{
|
||||
assert_eq!(k.depth(), parent.depth() + 1);
|
||||
assert_eq!(raw(k.parent().unwrap()), raw(parent));
|
||||
assert!(seen.insert(raw(*k)), "duplicate child");
|
||||
locals.insert(k.local_coords());
|
||||
}
|
||||
// Every (x, y, z) in 0..3 appears exactly once as a local coordinate.
|
||||
assert_eq!(locals.len(), 27);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_size_scales_with_depth()
|
||||
{
|
||||
let max_depth = 3;
|
||||
let root = TreeLocator::<4>::root();
|
||||
assert_eq!(root.node_size(max_depth), 64); // 4^3
|
||||
assert_eq!(root.child(0, 0, 0).node_size(max_depth), 16); // 4^2
|
||||
assert_eq!(root.child(0, 0, 0).child(1, 1, 1).node_size(max_depth), 4);
|
||||
assert_eq!(
|
||||
root.child(0, 0, 0)
|
||||
.child(1, 1, 1)
|
||||
.child(2, 2, 2)
|
||||
.node_size(max_depth),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_depth_is_reachable_without_overflow()
|
||||
{
|
||||
// `max_depth` may be conservative, but it must always be safe to reach.
|
||||
fn check<const N: usize>()
|
||||
{
|
||||
let max = TreeLocator::<N>::max_depth();
|
||||
let last = N as u32 - 1;
|
||||
|
||||
let mut l = TreeLocator::<N>::root();
|
||||
for _ in 0..max
|
||||
{
|
||||
l = l.child(last, last, last);
|
||||
}
|
||||
assert_eq!(l.depth(), max);
|
||||
|
||||
// Largest coordinates at that depth must also be constructible.
|
||||
let top = (N as u32).pow(max) - 1;
|
||||
let direct = TreeLocator::<N>::from_node_coords(max, top, top, top);
|
||||
assert_eq!(raw(direct), raw(l));
|
||||
}
|
||||
|
||||
check::<2>();
|
||||
check::<3>();
|
||||
check::<4>();
|
||||
check::<8>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "Out of bounds child coordinate.")]
|
||||
fn child_rejects_out_of_range_coordinate()
|
||||
{
|
||||
TreeLocator::<4>::root().child(0, 4, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "Node coordinates out of bounds.")]
|
||||
fn from_node_coords_rejects_out_of_range_coordinate()
|
||||
{
|
||||
// Depth 2 in a 4-tree allows 0..16.
|
||||
TreeLocator::<4>::from_node_coords(2, 0, 16, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "TreeLocator too deep")]
|
||||
fn child_rejects_overflowing_depth()
|
||||
{
|
||||
let mut l = TreeLocator::<2>::root();
|
||||
for _ in 0..40
|
||||
{
|
||||
l = l.child(1, 1, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
-3
@@ -42,8 +42,12 @@ struct ToroidalInvalidationImmediates
|
||||
|
||||
impl ToroidalStructureTable
|
||||
{
|
||||
pub fn new(device: &wgpu::Device, extent: (usize, usize, usize), initial_position: Vec3)
|
||||
-> Self
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
extent: (usize, usize, usize),
|
||||
initial_position: Vec3,
|
||||
max_requests: usize,
|
||||
) -> Self
|
||||
{
|
||||
let size = extent.0 * extent.1 * extent.2;
|
||||
assert!(size <= (u32::MAX as usize));
|
||||
@@ -77,7 +81,7 @@ impl ToroidalStructureTable
|
||||
|
||||
ToroidalStructureTable {
|
||||
extent,
|
||||
fixed_structure_table: FixedStructureTable::new(device, size),
|
||||
fixed_structure_table: FixedStructureTable::new(device, size, max_requests),
|
||||
position: initial_position,
|
||||
current_offset,
|
||||
invalidation_pass,
|
||||
|
||||
+17
-5
@@ -130,7 +130,12 @@ impl<const N: usize> VoxelCache<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self
|
||||
pub fn new(
|
||||
device: &Device,
|
||||
page_count: usize,
|
||||
max_requests: usize,
|
||||
layout: &CacheLayout,
|
||||
) -> Self
|
||||
{
|
||||
let mut cache_memory_profile = MemoryProfile::new("VoxelCache");
|
||||
let mut mem_device = cache_memory_profile.begin(device);
|
||||
@@ -141,8 +146,11 @@ where
|
||||
layout,
|
||||
page_count,
|
||||
);
|
||||
let request_handler =
|
||||
CacheRequestHandler::new(&mut mem_device.group("CacheRequestHandler"), page_count);
|
||||
let request_handler = CacheRequestHandler::new(
|
||||
&mut mem_device.group("CacheRequestHandler"),
|
||||
page_count,
|
||||
max_requests as u32,
|
||||
);
|
||||
let evictor = CacheEvictor::new(&mut mem_device.group("CacheEvictor"), page_count, 0u32);
|
||||
let common_ressources =
|
||||
CacheRessources::new(&mut mem_device.group("CacheRessources"), page_count);
|
||||
@@ -193,8 +201,12 @@ where
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "gather_requests");
|
||||
|
||||
self.request_handler
|
||||
.sort_requests(device, &self.common_ressources, &mut encoder);
|
||||
self.request_handler.sort_requests(
|
||||
device,
|
||||
&self.common_ressources,
|
||||
&mut encoder,
|
||||
request_buffer.max_requests as u32,
|
||||
);
|
||||
|
||||
self.write_requests_pass.encode(
|
||||
&mut encoder,
|
||||
|
||||
@@ -16,7 +16,12 @@ use crate::voxel_cache::create_multi_buffers_bind_group_layout;
|
||||
use crate::voxel_cache::structure::CacheStructure;
|
||||
|
||||
/// Retains usage information about pages in the cache under the form of timestamps.
|
||||
/// Produces a list of LRU eviction order, from which the cache can pull pages to recycle
|
||||
/// Produces an eviction order from which the cache can pull pages to recycle.
|
||||
///
|
||||
/// The list is ordered by timestamp first (least recently used first). Ties are
|
||||
/// broken by depth, deepest first. This works because the timestamp pass is a
|
||||
/// stable radix sort applied after a descending depth sort: pages that share a
|
||||
/// timestamp keep the deepest-first order established by the depth pass.
|
||||
pub struct CacheEvictor
|
||||
{
|
||||
page_count: usize,
|
||||
@@ -24,7 +29,8 @@ pub struct CacheEvictor
|
||||
/// Contains a u32 timestamp per page, so that we know when a page was last used
|
||||
timestamp_pages: wgpu::Buffer,
|
||||
|
||||
/// Contains indices in LRU order, after sorting
|
||||
/// Contains page indices in eviction order: least recently used first.
|
||||
/// Among pages with equal timestamps, deeper pages come first.
|
||||
lru_list: wgpu::Buffer,
|
||||
|
||||
/// When reusing pages, count of lru pages consumed
|
||||
@@ -33,7 +39,7 @@ pub struct CacheEvictor
|
||||
/// To reset lru indices between insertions
|
||||
reset_lru_pass: wgpu::ComputePipeline,
|
||||
|
||||
/// To copy corresponding timestamp values after first depth sort
|
||||
/// To copy corresponding timestamp values after the descending depth sort
|
||||
indirect_copy_pass: wgpu::ComputePipeline,
|
||||
pipelines_dispatch_count: u32,
|
||||
|
||||
@@ -146,7 +152,15 @@ impl CacheEvictor
|
||||
reset_pass.dispatch_workgroups(self.pipelines_dispatch_count, 1, 1);
|
||||
}
|
||||
|
||||
// First sort nodes per depth
|
||||
// First sort nodes by depth, deepest first. This is the tie-breaker:
|
||||
// the timestamp sort below is stable, so it preserves this order for
|
||||
// pages that share a timestamp.
|
||||
//
|
||||
// Consuming the list in order then reuses the deepest pages first among
|
||||
// equal timestamps. Since a page's resident children are deeper, they
|
||||
// appear earlier in the list and are reused first (provided their
|
||||
// timestamp is equal or older), instead of being orphaned when the
|
||||
// parent is recycled.
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "depth radix");
|
||||
encoder.copy_buffer_to_buffer(
|
||||
@@ -164,7 +178,7 @@ impl CacheEvictor
|
||||
None,
|
||||
Some(self.page_count),
|
||||
&mut encoder,
|
||||
radix_sort::RadixSortDirection::Ascending,
|
||||
radix_sort::RadixSortDirection::Descending,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -182,6 +196,9 @@ impl CacheEvictor
|
||||
indirect_copy_pass.dispatch_workgroups(self.pipelines_dispatch_count, 1, 1);
|
||||
}
|
||||
|
||||
// Then sort by timestamp, oldest first. The radix sort is stable, so
|
||||
// equal timestamps retain the deepest-first order from the depth sort.
|
||||
// The resulting list is LRU-first with deepest-first ties.
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "timestamp radix");
|
||||
ressources.radix_sorter.sort(
|
||||
|
||||
+132
-22
@@ -9,9 +9,10 @@ use wgpu::Device;
|
||||
use wgpu::include_wgsl;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::gpu::buffer_compactor::NonZeroBufferCompactor;
|
||||
use crate::gpu::create_multi_buffers_bind_group;
|
||||
use crate::gpu::indirect_buffer::IndirectBuffer1D;
|
||||
use crate::gpu::radix_sort::{self};
|
||||
use crate::gpu::top_k::TopKSelector;
|
||||
use crate::gpu_profiler::ScopeEncoder;
|
||||
use crate::gpu_profiler::memory_profiler;
|
||||
use crate::gpu_profiler::{self};
|
||||
@@ -34,7 +35,16 @@ pub struct CacheRequestHandler<const N: usize>
|
||||
/// Number of requests
|
||||
request_count: wgpu::Buffer,
|
||||
|
||||
compactor: NonZeroBufferCompactor,
|
||||
/// Number of request counts in `request_counts_pages`
|
||||
element_count: u32,
|
||||
|
||||
/// Selects the most requested pages
|
||||
top_k: TopKSelector,
|
||||
|
||||
/// Gathers the selected counts and indices into contiguous sort buffers
|
||||
gather_pass: ComputePipeline,
|
||||
gather_pass_bind_group_layout: BindGroupLayout,
|
||||
gather_indirect_buffer: IndirectBuffer1D,
|
||||
|
||||
// Pass to reset the requests
|
||||
reset_pass_bind_group: BindGroup,
|
||||
@@ -66,18 +76,25 @@ pub struct CacheRequestBuffer
|
||||
|
||||
impl<const N: usize> CacheRequestHandler<N>
|
||||
{
|
||||
pub fn new(device: &mut memory_profiler::Device, page_count: usize) -> Self
|
||||
pub fn new(device: &mut memory_profiler::Device, page_count: usize, max_selected: u32) -> Self
|
||||
{
|
||||
let element_count = page_count * N * N * N;
|
||||
assert!(
|
||||
element_count <= u32::MAX as usize,
|
||||
"CacheRequestHandler: too many request pages ({element_count})"
|
||||
);
|
||||
let element_count = element_count as u32;
|
||||
|
||||
let request_counts_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheRequestHandler::request_counts_pages"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
contents: bytemuck::cast_slice(&vec![0u32; page_count * N * N * N]),
|
||||
contents: bytemuck::cast_slice(&vec![0u32; element_count as usize]),
|
||||
});
|
||||
|
||||
let sorted_requests = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheRequestHandler::sorted_requests"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
contents: bytemuck::cast_slice(&vec![0u32; page_count * N * N * N]),
|
||||
contents: bytemuck::cast_slice(&vec![0u32; element_count as usize]),
|
||||
});
|
||||
|
||||
let request_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
@@ -88,6 +105,25 @@ impl<const N: usize> CacheRequestHandler<N>
|
||||
contents: bytemuck::bytes_of(&0u32),
|
||||
});
|
||||
|
||||
let top_k = TopKSelector::new(device, max_selected);
|
||||
|
||||
let gather_pass_bind_group_layout = Self::create_gather_bind_group_layout(device);
|
||||
let gather_pass_pipeline_layout =
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("CacheRequestHandler::gather_pass_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&gather_pass_bind_group_layout)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let gather_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("CacheRequestHandler::gather_pass"),
|
||||
layout: Some(&gather_pass_pipeline_layout),
|
||||
module: &device.create_shader_module(include_wgsl!("./shaders/gather_requests.wgsl")),
|
||||
entry_point: Some("gather_requests"),
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let (reset_pass_bg_layout, reset_pass_bind_group) = create_multi_buffers_bg_bg_layout(
|
||||
device,
|
||||
&[&request_counts_pages],
|
||||
@@ -122,17 +158,46 @@ impl<const N: usize> CacheRequestHandler<N>
|
||||
request_counts_pages,
|
||||
sorted_requests,
|
||||
request_count,
|
||||
compactor: NonZeroBufferCompactor::new(device, page_count * N * N * N),
|
||||
element_count,
|
||||
top_k,
|
||||
gather_pass,
|
||||
gather_pass_bind_group_layout,
|
||||
gather_indirect_buffer: IndirectBuffer1D::new(device),
|
||||
|
||||
reset_pass_bind_group,
|
||||
reset_pass,
|
||||
reset_pass_dispatch: ((page_count * N * N * N) as u32).div_ceil(256),
|
||||
reset_pass_dispatch: element_count.div_ceil(256),
|
||||
|
||||
bind_group_layout,
|
||||
bind_group,
|
||||
}
|
||||
}
|
||||
|
||||
fn create_gather_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout
|
||||
{
|
||||
let entry = |binding: u32, read_only: bool| wgpu::BindGroupLayoutEntry {
|
||||
binding,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
};
|
||||
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("CacheRequestHandler::gather_pass_bind_group_layout"),
|
||||
entries: &[
|
||||
entry(0, true), // requests
|
||||
entry(1, true), // selected_indices
|
||||
entry(2, true), // selected_count
|
||||
entry(3, false), // keys
|
||||
entry(4, false), // values
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
/// Sorts the requests currently held by the request handler in order to process them.
|
||||
///
|
||||
/// Uses both the sorter and the scratch buffer in the ressources
|
||||
@@ -143,46 +208,91 @@ impl<const N: usize> CacheRequestHandler<N>
|
||||
device: &wgpu::Device,
|
||||
ressources: &CacheRessources<N>,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
k: u32,
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "RequestHandler::sort_requests");
|
||||
|
||||
// First perform a fast compaction sort
|
||||
// Select the most requested pages.
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "compaction");
|
||||
self.compactor.compact_buffer(
|
||||
gpu_profiler::begin_scope!(encoder, "top_k");
|
||||
self.top_k.select(
|
||||
device,
|
||||
&mut encoder,
|
||||
&self.request_counts_pages,
|
||||
&self.sorted_requests,
|
||||
Some(&ressources.scratch_buffer),
|
||||
self.element_count,
|
||||
k,
|
||||
);
|
||||
}
|
||||
|
||||
self.compactor
|
||||
.copy_count_to_buffer(&mut encoder, &self.request_count);
|
||||
// Gather the selected counts and indices into contiguous sort buffers.
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "gather");
|
||||
|
||||
// State:
|
||||
// At this point the `sorted_requests` buffer contains the compacted indices of the request counts
|
||||
// and the scratch buffer contains the associated values
|
||||
let gather_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("CacheRequestHandler::gather_bind_group"),
|
||||
layout: &self.gather_pass_bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: self.request_counts_pages.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: self.top_k.selected_indices_buffer().as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: self.top_k.selected_count_buffer().as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: ressources.scratch_buffer.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: self.sorted_requests.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// The indices can now be sorted using `sorted_requests` as values and
|
||||
// `ressources.scratch_buffer` as keys for a sort operation
|
||||
let gather_dispatch = self.gather_indirect_buffer.workgroup_count(
|
||||
device,
|
||||
&mut encoder,
|
||||
self.top_k.selected_count_buffer(),
|
||||
256,
|
||||
);
|
||||
|
||||
// We use the amount of non zero request as the indirect count so that we can sort only the
|
||||
// compacted, non-null requests
|
||||
let mut compute_pass = encoder.begin_profiled_compute_pass("gather");
|
||||
compute_pass.set_pipeline(&self.gather_pass);
|
||||
compute_pass.set_bind_group(0, &gather_bind_group, &[]);
|
||||
compute_pass.dispatch_workgroups_indirect(gather_dispatch, 0);
|
||||
}
|
||||
|
||||
// Sort the selected requests by descending request count. The scratch
|
||||
// buffer holds the keys (counts) and `sorted_requests` the values
|
||||
// (indices). `selected_count` is the indirect element count.
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "radix");
|
||||
ressources.radix_sorter.sort(
|
||||
device,
|
||||
&ressources.scratch_buffer,
|
||||
&self.sorted_requests,
|
||||
Some(&self.request_count),
|
||||
Some(self.top_k.selected_count_buffer()),
|
||||
None,
|
||||
&mut encoder,
|
||||
radix_sort::RadixSortDirection::Descending,
|
||||
);
|
||||
}
|
||||
|
||||
// Publish the amount of selected requests for downstream passes.
|
||||
encoder.copy_buffer_to_buffer(
|
||||
self.top_k.selected_count_buffer(),
|
||||
0,
|
||||
&self.request_count,
|
||||
0,
|
||||
size_of::<u32>() as u64,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout
|
||||
|
||||
@@ -119,9 +119,13 @@ pub struct LocationPage
|
||||
/// An external insertion gets the 0 depth.
|
||||
/// Internal insertions get the parent's depth plus one.
|
||||
///
|
||||
/// As such, when inserting pages in the cache, we first sort the lru pages
|
||||
/// by depth. This prevents replacing a high page that pointed to a deeper tree strucutre
|
||||
/// effectively invalidating the minimum amount of data.
|
||||
/// As such, when inserting pages in the cache, we first sort the lru pages by
|
||||
/// depth, deepest first, then apply a stable radix sort by timestamp. The final
|
||||
/// order is least-recently-used first, with deepest pages first among equal
|
||||
/// timestamps. Reusing deepest pages first means that a page's resident children
|
||||
/// are deeper, so they appear earlier in the list and are reused first (provided
|
||||
/// their timestamp is equal or older) instead of being orphaned when their
|
||||
/// parent is recycled.
|
||||
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
pub struct DepthPage(pub u32);
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
/// Group 2: Scratch buffer
|
||||
@group(2) @binding(0) var<storage, read_write> scratch_buffer: array<u32>;
|
||||
|
||||
/// Resets the lru list
|
||||
/// Resets the lru list to identity order before the depth sort, and clears the
|
||||
/// number of pages consumed by previous insertions.
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn reset_lru_list(@builtin(global_invocation_id) global_invocation_id: vec3<u32>)
|
||||
@@ -28,7 +29,12 @@ fn reset_lru_list(@builtin(global_invocation_id) global_invocation_id: vec3<u32>
|
||||
consumed_count = 0;
|
||||
}
|
||||
|
||||
/// Indirect copy, in between the depth sort and the timestamp sort
|
||||
/// Rearranges timestamps into depth order, in between the descending depth sort
|
||||
/// and the stable timestamp sort.
|
||||
///
|
||||
/// `lru_list` currently holds page indices sorted deepest first. Writing each
|
||||
/// page's timestamp to the same position gives the next (stable) radix sort an
|
||||
/// input where equal timestamps preserve the deepest-first depth order.
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn indirect_copy(@builtin(global_invocation_id) global_invocation_id: vec3<u32>)
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// Gathers the selected (count, index) pairs into contiguous buffers so they can
|
||||
// be sorted by the radix sorter.
|
||||
//
|
||||
// `keys` receives the request counts and `values` receives the request indices.
|
||||
|
||||
@group(0) @binding(0) var<storage, read> requests: array<u32>;
|
||||
@group(0) @binding(1) var<storage, read> selected_indices: array<u32>;
|
||||
@group(0) @binding(2) var<storage, read> selected_count: u32;
|
||||
@group(0) @binding(3) var<storage, read_write> keys: array<u32>;
|
||||
@group(0) @binding(4) var<storage, read_write> values: array<u32>;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn gather_requests(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
let i = gid.x;
|
||||
if (i >= selected_count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let index = selected_indices[i];
|
||||
keys[i] = requests[index];
|
||||
values[i] = index;
|
||||
}
|
||||
@@ -19,9 +19,10 @@ fn invalidation(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
|
||||
for(var i = u32(0); i < CHILDREN_COUNT; i++)
|
||||
{
|
||||
if(pointer_invalid(structure_pointer_pages[index].pointers[i]))
|
||||
let pointer = structure_pointer_pages[index].pointers[i];
|
||||
if(child_pointer_available(pointer) && cache_evictor_timestamps[child_pointer_pointer(pointer)] == new_timestamp)
|
||||
{
|
||||
pointer_invalidate(index, i);
|
||||
structure_pointer_pages[index].pointers[i] = child_pointer_empty(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,8 +46,9 @@ where
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
// Depth pages need to be initialized to unused, this prioritizes them in the
|
||||
// depth sort used in the eviction pass
|
||||
// Unused pages get the maximum depth so they lead the deepest-first
|
||||
// depth sort used by the eviction pass. Combined with their initial
|
||||
// timestamp of 0, this makes them the first pages reused.
|
||||
let depth_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheStructure::depth_pages"),
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
|
||||
@@ -60,7 +60,7 @@ pub struct FixedStructureTable
|
||||
|
||||
impl FixedStructureTable
|
||||
{
|
||||
pub fn new(device: &wgpu::Device, size: usize) -> Self
|
||||
pub fn new(device: &wgpu::Device, size: usize, max_requests: usize) -> Self
|
||||
{
|
||||
let pointer = CachePointer::new(Some(None));
|
||||
let pointers = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
@@ -72,8 +72,11 @@ impl FixedStructureTable
|
||||
let mut memory_profile = MemoryProfile::new("FixedStructureTable");
|
||||
let mut mem_device = memory_profile.begin(device);
|
||||
|
||||
let request_handler =
|
||||
CacheRequestHandler::<1>::new(&mut mem_device.group("CacheRequestHandler"), size);
|
||||
let request_handler = CacheRequestHandler::<1>::new(
|
||||
&mut mem_device.group("CacheRequestHandler"),
|
||||
size,
|
||||
max_requests as u32,
|
||||
);
|
||||
let common_ressources =
|
||||
CacheRessources::new(&mut mem_device.group("CacheRessources"), size);
|
||||
drop(mem_device);
|
||||
@@ -195,8 +198,12 @@ impl FixedStructureTable
|
||||
request_buffer: &CacheRequestBuffer,
|
||||
)
|
||||
{
|
||||
self.request_handler
|
||||
.sort_requests(device, &self.common_ressources, encoder);
|
||||
self.request_handler.sort_requests(
|
||||
device,
|
||||
&self.common_ressources,
|
||||
encoder,
|
||||
request_buffer.max_requests as u32,
|
||||
);
|
||||
|
||||
let workgroup_count_buffer = self.indirect_buffer.workgroup_count(
|
||||
device,
|
||||
|
||||
Reference in New Issue
Block a user