refactor: cleaner request path + raytracing code

This commit is contained in:
2026-11-23 11:32:16 +01:00
parent dd0e102348
commit dd5fdc13b8
20 changed files with 1427 additions and 618 deletions
+128 -136
View File
@@ -144,101 +144,95 @@ corrupting the tree.
## 3. The durable producer shape
`crates/vxls/src/producers.rs` defines:
The durable interface is `vxls-production::Producer`, and the demo driver uses
it through `TreeProducer` in `crates/vxls/src/producers.rs`:
```rust
pub trait ChunkedProducer<const N: usize>
pub trait Producer<const N: usize, A: Attributes>
where [(); N * N * N]:,
{
fn produce_node(
fn produce(
&self,
depth: usize,
nx: usize,
ny: usize,
nz: usize,
chunk_pos: (usize, usize, usize),
) -> ProducedChunk<N>;
anchor: StructureAnchor,
locator: StructureLocator,
) -> ProducedNode<N, A>;
}
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],
pub struct ProducedNode<const N: usize, A: Attributes>
where [(); N * N * N]:,
{
pub insertion: InsertionInformation<N>,
pub attributes: [A; N * N * N],
}
```
`locator` is the content-local path of the node to produce, obtained from the
request with `RequestKey::node_locator::<N>()`. The producer does not need to
know whether the request was a structure root or an internal child: the locator
already names the node, and the cache derives the matching `LocationPage` from
the same key.
The cache owns identity, so `ProducedNode` deliberately carries no producer id,
anchor, table slot, or location. The host/queue adds those when it builds an
`InsertionEntry`.
The older `ChunkedProducer` / `ProducedChunk` shape in
`crates/vxls/src/producers.rs` is retained only for the unused terrain/ball
fixtures. It is not the interface new producers should implement.
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.
- The producer fills one entry per child of the requested node, plus the
attributes for those children.
- `anchor` is the content identity. A producer must derive world position from
it and never from a table slot.
### 3.1 Fulfilling a request
The demo's `fullfill_request` (`crates/vxls/src/main.rs`) does:
`TreeProducer` (`crates/vxls/src/producers.rs`) does:
1. Decode the table-defined anchor with
`ToroidalStructureTable::position_for_anchor` to get an absolute chunk
coordinate.
2. Add the playground offset `+5000` to x and z and take `abs()` of y.
3. If `request_meta.page_index == 0xFFFFFFFF` (an external table request),
produce the chunk root at depth 0, emit the root locator, and emit
`InsertionParent::external(producer_id, anchor, table_slot)`.
4. Otherwise (an internal child request):
- 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`;
- emit `InsertionParent::internal(meta, node_id, producer_id, anchor)`.
1. Decode `locator` with `TreeLocator::<N>::from`.
2. If the node is not subdivided, emit a constant page: every child has the
node's attribute and `ChildInformation::new(false, occupied)`.
3. Otherwise iterate `locator.children()` and emit each child's
`ChildInformation` and `VoxelAttributes`.
4. Return a `ProducedNode`; no location or parent is produced here.
The root/child test must use `RequestMeta.page_index`, not `node_id`: child 0
of the root also has `node_id = 0`.
The request path is:
The `+5000` offset and the hardcoded `<4>` are playground artifacts. They assume
chunk dimensions of 20×20×20 and a 4-ary tree.
1. `RequestQueue` yields a `WorkItem` with a `RequestKey`.
2. The worker calls `producer.produce(key.anchor, key.node_locator::<4>())`.
3. On drain, `ReadyItem::insertion_entry()` combines the payload with
`ReadyItem::insertion_parent()` and `ReadyItem::location_page()`.
4. `CacheInsertionData::upload` writes the batch.
### 3.2 Locators
Two locator implementations exist:
`TreeLocator<N>` (`crates/vxls-production/src/tree_locator.rs`) is the locator
used by the request queue and the demo producer. 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.
- **`NTreeNodeLocator<N>`** (`crates/vxls/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>`** (`crates/vxls-production/src/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`.
`NTree<N>` in `crates/vxls/src/sparse_tree.rs` is keyed by the same locator, so
a `RequestKey` can name a produced node directly. Locators must round-trip
through the 32-bit `node_id`.
---
## 4. The current driver, step by step
Relevant code: `State::render` and `fullfill_request` in `crates/vxls/src/main.rs`.
Relevant code: `State::render` and `TreeProducer` in `crates/vxls/src/main.rs` /
`crates/vxls/src/producers.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 three asynchronous reads per request buffer (count,
informations, meta).
informations, meta). Each callback only ingests the wire requests into the
shared `RequestQueue`; it does not drain or upload.
4. **Busy-wait**:
```rust
@@ -249,19 +243,26 @@ Relevant code: `State::render` and `fullfill_request` in `crates/vxls/src/main.r
```
`finished` counts completed callbacks (one cache, one table), so completion
does not require all six reads to land independently.
5. **Produce** on the CPU with rayon: one `fullfill_request` per
`(RequestInformation, RequestMeta)` pair. The results are copied into dense
vectors, then uploaded with `queue.write_buffer` into:
- `insertion_information_buffer()`
- `location_pages_buffer()`
- `insertion_parents_buffer()`
- `attributes_buffers()[0]` (color)
- `attributes_buffers()[1]` (normal)
- `destination_indices_buffer()` (pre-filled with `0xFFFFFFFF`)
- `valid_count_buffer()` (`0`)
- `page_count_buffer()`
6. **Insert** encodes:
does not require all six reads to land independently. Each callback
increments it only after ingesting.
5. **Drain** the queue once both downloads have landed:
```rust
let children = queue.drain_ready_matching(
frame_id, cache_insertion.capacity(), |key| !key.is_root());
let roots = queue.drain_ready_matching(
frame_id, structure_table_insertion.capacity(), |key| key.is_root());
```
`frame_id` is a host-owned monotonic counter, not the cache timestamp word.
6. **Produce** on the worker thread with rayon, one `Producer::produce` call per
`WorkItem`. Each result is a `ProducedNode<N, A>` keyed by
`RequestKey::node_locator::<N>()`. On drain,
`ReadyItem::insertion_entry()` attaches the parent and location, and
`CacheInsertionData::upload` writes the whole batch (structure, location,
parent, attributes, `valid_count`, `page_count`). `destination_indices` is
reset by the validation shaders, not by the host.
7. **Insert** encodes:
```rust
cache.insert(&device, &mut encoder, &mut [
@@ -277,7 +278,7 @@ Relevant code: `State::render` and `fullfill_request` in `crates/vxls/src/main.r
preparation is shared by both page allocations. 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.
8. **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
@@ -285,14 +286,16 @@ 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.
- The render thread blocks waiting for downloads before it can drain results, so
production does not overlap with 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.
- The worker thread is spawned from the playground, so scheduling and producer
ownership are not reusable outside `main.rs`.
- No backpressure or prioritisation beyond the top-K request cap.
- Rejected insertions (`destination_indices == 0xFFFFFFFF`) are still not
reported back to the producer.
These are acceptable for a playground and are the first things to redesign for a
real engine.
@@ -306,9 +309,10 @@ 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. |
| `TreeProducer<N>` | Used by the demo | Implements the durable `vxls_production::Producer` over an in-memory `NTree`; the request's `node_locator` selects the node. |
| `SdfGenerator<N>` | Fixture, unused | Signed-distance field from FBM simplex noise plus procedural "trees"; derives normal by finite differences; packs color from normal. |
| `TerrainGenerator<N>` | Fixture, unused | Loads a TIFF heightmap and a JPEG/PNG colormap; builds low-resolution mips; produces nodes from min/max height spans. |
| `BallGenerator<N>` | Fixture, unused | Implements the local playground `producers::Producer<N>` trait, not the durable one. |
`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
@@ -325,9 +329,10 @@ branching logic based on `depth <= 2`.
## 6. The production subsystem
`crates/vxls-production/src/lib.rs` and its children are compiled (`mod production;`), but the
demo driver in `main.rs` still uses its synchronous `fullfill_request` path. The
production types are the durable contract; the driver is still the playground.
`crates/vxls-production/src/lib.rs` and its children are compiled, and the demo
driver now uses its durable `Producer` / `ProducedNode` / `RequestQueue` types.
The `main.rs` producer remains a playground fixture, but it implements the
durable interface.
### 6.1 `crates/vxls-production/src/lib.rs`
@@ -362,16 +367,18 @@ The cache-facing side is:
```rust
let layout = CacheLayout::from_attributes(&A::LAYOUT, &[]);
let insertion = CacheInsertionData::new(&device, max_entries, &layout);
let entry_count = insertion.write_attributes(&queue, node.attributes())?;
let entries: Vec<InsertionEntry<N>> = ...;
insertion.upload(&queue, &entries, &voxels)?;
```
Differences from the demo interface:
Differences from the legacy `ChunkedProducer` fixture interface:
- A node carries a `producer_id`, so one cache can mix multiple producers.
- Attributes are abstracted behind `Attributes`, avoiding hardcoded
color/normal buffers.
- The producer receives a `StructureLocator` rather than depth + coordinates,
pushing locator arithmetic into the producer.
- `ProducedNode` carries no identity: the request key supplies producer, anchor,
parent, and `LocationPage` when the entry is staged.
- `anchor` is the content identity. A producer must derive world position from
it and never from a table slot.
@@ -389,12 +396,11 @@ table keeps an anchor's identity while it stays in view and retires anchors that
leave. An anchor must keep naming the same content if it later re-enters; bump
its version word when content generation changes for the same coordinates.
### 6.2 `crates/vxls-production/src/host_production.rs`
### 6.2 Host production helper (not present)
`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.
There is no `crates/vxls-production/src/host_production.rs` in this tree. The
worker thread and `RequestQueue` in `crates/vxls/src/main.rs` are the current
host-side implementation.
### 6.3 `crates/vxls-production/src/tree_locator.rs`
@@ -440,32 +446,25 @@ Properties:
queued/in-flight/ready jobs. Invalidation is a cancellation/cleanup hint,
**not** a correctness mechanism: the GPU rejects stale insertions by checking
the current anchor/slot.
- `RequestKey::node_locator::<N>()` derives the locator of the requested node
(root or child) from the key, so producers and `LocationPage` agree.
- `ReadyItem::insertion_parent()` builds the `InsertionParent` for the insertion
batch from the key and the latest `RequestMeta` (which carries `table_slot`).
- `ReadyItem::location_page::<N>()` builds the `LocationPage` from the key, not
from the producer payload or the table slot.
- `ReadyItem::insertion_entry()` combines the payload's `InsertionInformation`
with those two into a cache-facing `InsertionEntry`.
The queue is unit-tested without a GPU (`cargo test -p vxls-production request_queue`).
### 6.5 `crates/vxls/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 `crates/vxls/src/sparse_tree.rs`
### 6.5 `crates/vxls/src/sparse_tree.rs`
A CPU `NTree<N>` prototype backed by a `HashMap<TreeLocator<N>, NTreeNode>`,
with `constant`, `get`, `set`, array conversion, and explicit-structure export.
It also provides the packed `Color` helper and PLY loading. Useful for
understanding the tree and used by the playground producers, not by the renderer.
### 6.7 `crates/vxls/src/gi_pipeline.rs` + `sparse_set.rs`
### 6.6 `crates/vxls/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`
@@ -478,36 +477,34 @@ code.
Minimum viable path with the current demo interface:
1. Implement `ChunkedProducer<N>`:
1. Implement the durable `vxls_production::Producer<N, A>`:
```rust
impl ChunkedProducer<4> for MyProducer {
fn produce_node(&self, depth, nx, ny, nz, chunk_pos) -> ProducedChunk<4> { ... }
impl Producer<4, MyAttributes> for MyProducer {
fn produce(
&self,
anchor: StructureAnchor,
locator: StructureLocator,
) -> ProducedNode<4, MyAttributes> { ... }
}
```
2. For each child, compute:
2. Decode `locator` with `TreeLocator::<N>::from` if the producer needs node
coordinates.
3. For each child of the requested node, 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 (`RequestMeta.page_index == 0xFFFFFFFF`), 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. Emit an `InsertionParent`:
- external: `InsertionParent::external(producer_id, anchor, table_slot)`;
- internal: `InsertionParent::internal(meta, node_id, producer_id, anchor)`.
6. Set `page_count_buffer` to the number of entries. Order does not matter, but
every entry must have matching information, location, parent, and attributes.
7. Update the size passed to `CacheInsertionData::new` if the maximum batch can
exceed `max_requests`.
4. Return a `ProducedNode` with `InsertionInformation` and the attribute array.
Do not emit a `LocationPage` or `InsertionParent`; those are derived from the
`RequestKey` when the result is drained.
5. Replace `TreeProducer` in `crates/vxls/src/main.rs` with the new producer.
6. Keep `CacheInsertionData::new` capacity at least as large as the maximum
number of entries the queue can drain in one frame.
A production-ready producer should additionally:
- use the `Producer`/`Attributes` abstraction so attributes are not hardcoded;
- use the `Attributes` abstraction so attributes are not hardcoded;
- run through `RequestQueue` on a worker thread and stream results across frames
without blocking the render loop;
- handle `destination_indices == 0xFFFFFFFF` by retrying the request;
@@ -522,14 +519,9 @@ A production-ready producer should additionally:
| Symptom | Location | Impact | Confidence |
|---|---|---|---|
| The host request path busy-waits on `device.poll`; production blocks the render thread. | `crates/vxls/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. | `crates/vxls/src/main.rs:1814-1905` | Not generic; offsets only make sense for the demo terrain. | High |
| The demo driver is still synchronous: it downloads, produces, and inserts in one frame. The queue exists but `main.rs` does not schedule through it yet. | `crates/vxls/src/main.rs` (`render`), `crates/vxls-production/src/request_queue.rs` | No overlap between production and rendering in the demo. The durable contract is ready for an async scheduler. | 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. | `crates/vxls/src/main.rs` (write of `page_count_buffer`), `CacheInsertionData::new` | Buffer overrun / truncated production. | High |
| The demo driver is still synchronous: it downloads, produces, and inserts in one frame. | `crates/vxls/src/main.rs` (`render`), `crates/vxls-production/src/request_queue.rs` | No overlap between production and rendering in the demo. The queue is on the live path but the scheduler is still frame-blocking. | 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. | `crates/vxls/src/producers.rs:207-263,330` | Not robust to different chunk resolutions. | High |
| `BallGenerator` implements the old `Producer` trait, not `ChunkedProducer`. | `crates/vxls/src/producers.rs:31-116` | Copying it as a template will not work with the current driver. | High |
| The `production/` subsystem is compiled but not used by the demo driver. | `crates/vxls-production/src/lib.rs`, `crates/vxls-production/src/*` | Agents may assume the queue is on the live path; it is the durable target, while `fullfill_request` is still the active playground path. | High |
| `crates/vxls-production/src/request_queue.rs` is new. | same | Its API may still change; `main.rs` does not depend on it yet. | Medium |
| The demo uploads all attribute payloads with `bytemuck::cast_slice` of Rust arrays, so layout mismatches (padding, alignment) are not checked. | `crates/vxls/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. | `crates/vxls/src/main.rs:1785-1789` | Duplicate chunks / visual artifacts at negative y. | Medium |
| `TerrainGenerator` uses hardcoded mip factor 8 and `depth <= 2` special cases. | `crates/vxls/src/producers.rs` | Not robust to different chunk resolutions. | High |
| `BallGenerator` implements the local playground `producers::Producer<N>` trait, not the durable `vxls_production::Producer`. | `crates/vxls/src/producers.rs` | Copying it as a template will not work with the current driver. | High |
| The worker thread is owned by `main.rs` rather than `vxls-production`, so queue scheduling and producers are not reusable yet. | `crates/vxls/src/main.rs` | Durable producer types exist, but the host service around them does not. | Medium |