Starting decoupling requests

This commit is contained in:
2026-11-08 21:25:40 +01:00
parent 82c952c6d8
commit d44da4520c
23 changed files with 2386 additions and 306 deletions
+4
View File
@@ -1,5 +1,9 @@
/target
Cargo.lock
.codegraph/
.mcp.json
opencode.jsonc
.claude/
imgs.tar.gz
+11
View File
@@ -148,3 +148,14 @@ The full tables live in the docs. The most important ones:
`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.
<!-- CODEGRAPH_START -->
## CodeGraph
In repositories indexed by CodeGraph (a `.codegraph/` directory exists at the repo root), reach for it BEFORE grep/find or reading files when you need to understand or locate code:
- **MCP tool** (when available): `codegraph_explore` answers most code questions in one call — the relevant symbols' verbatim source plus the call paths between them, including dynamic-dispatch hops grep can't follow. Name a file or symbol in the query to read its current line-numbered source. If it's listed but deferred, load it by name via tool search.
- **Shell** (always works): `codegraph explore "<symbol names or question>"` prints the same output.
If there is no `.codegraph/` directory, skip CodeGraph entirely — indexing is the user's decision.
<!-- CODEGRAPH_END -->
+130 -58
View File
@@ -29,13 +29,13 @@ sequenceDiagram
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
C-->>H: request buffer (structure_id, node_id, child, producer, demand)
T-->>H: table request buffer (slot, 0, 0, producer, demand)
H->>H: queue + produce one node per request (parallel, possibly across frames)
H->>I: upload CacheInsertionData (info, location, parent, attributes, count)
I->>C: validate/compact, recycle pages, write pages, invalidate stale pointers
I->>C: write new child pointers
I->>T: point table slots at new root pages
I->>T: validate/point table slots at new root pages
Note over R: next frame sees the new pages
```
@@ -54,25 +54,34 @@ 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
producer_id: u32, // owner of the parent node
demand: u32, // request counter for this slot this frame
}
struct RequestMeta {
page_index: u32, // parent page (internal) or sentinel (external)
page_index: u32, // parent page (internal) or 0xFFFFFFFF (external)
children_index: u32,
depth: u32,
depth: u32, // parent depth
}
```
- 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.
- The producer receives both `RequestInformation` and `RequestMeta`, so it can
build the insertion's `InsertionParent` without referring back to a request
buffer.
- For external requests from a structure table: `RequestMeta.page_index =
0xFFFFFFFF`, `node_id = 0`, `children_index = 0`, and `structure_id` is the
table slot.
- The root/child distinction must use `RequestMeta.page_index == 0xFFFFFFFF`,
**not** `node_id == 0`: child 0 of the root also has `node_id = 0`.
- Requests are sorted by demand (highest counter first) and capped at
`max_requests`.
- `producer_id` and `demand` are on the wire so the host queue can deduplicate
and prioritise without guessing.
### 2.2 Response
One `CacheInsertionData` entry per request, in the **same order**:
One `CacheInsertionData` entry per produced node. Entries do **not** have to be in
request order, because each one carries its own attachment point:
```rust
struct InsertionInformation<N> {
@@ -81,28 +90,44 @@ struct InsertionInformation<N> {
struct LocationPage {
structure_id: u32,
node_id: u32,
node_id: u32, // locator of the node itself
producer_id: u32,
}
struct InsertionParent {
kind: u32, // 0 = child of a resident page, 1 = external root
page_index: u32, // parent page, or 0xFFFFFFFF for an external root
children_index: u32,
depth: u32, // parent depth, or 0xFFFFFFFF
structure_id: u32,
node_id: u32, // parent locator (0 for an external root)
producer_id: u32,
}
```
Plus one attribute payload per page (color and normal in the demo).
Plus one attribute payload per entry (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.
Before allocating pages, the cache validates every entry against the current
parent:
### 2.3 Why order matters
- internal: the parent page must still have the same identity and the child slot
must still be `subdividable, unavailable`;
- external: the table slot must still be `subdividable, unavailable`.
`write_pointers.wgsl` and `fixed_table/insertion.wgsl` assume:
Valid entries are compacted into `valid_indices`/`valid_count`; only those
consume eviction pages. The cache fills `destination_indices[i]` with the page
that received entry `i`, or `0xFFFFFFFF` if it was rejected (invalid, out of
capacity, or too recently used). A real producer should read it and retry the
request if needed.
```text
request_informations[i] <-> insertion_data[i] <-> destination_indices[i]
```
### 2.3 Ordering and staleness
If a producer reorders, filters, or duplicates requests, pages will be linked to
the wrong parents. There is no validation.
There is no longer an ordering requirement between requests and insertion
entries. `write_pointers.wgsl` and `fixed_table/insertion.wgsl` use the batch's
`InsertionParent`, and re-check parent identity before linking. This is what
makes asynchronous, cross-frame production safe: a page produced for a parent
that has since been evicted or reused is dropped at insertion time instead of
corrupting the tree.
---
@@ -156,15 +181,20 @@ 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:
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(structure_id, producer_id)`.
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 the child locator as the new `LocationPage.node_id`;
- emit `InsertionParent::internal(meta, structure_id, node_id, producer_id)`.
The root/child test must use `RequestMeta.page_index`, not `node_id`: child 0
of the root also has `node_id = 0`.
The `+5000` offset and the hardcoded `<4>` are playground artifacts. They assume
chunk dimensions of 20×20×20 and a 4-ary tree.
@@ -195,8 +225,8 @@ 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).
3. **Download** starts three asynchronous reads per request buffer (count,
informations, meta).
4. **Busy-wait**:
```rust
@@ -207,14 +237,17 @@ Relevant code: `State::render` and `fullfill_request` in `src/main.rs`.
```
`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:
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:
@@ -222,16 +255,16 @@ Relevant code: `State::render` and `fullfill_request` in `src/main.rs`.
cache.insert(&device, &mut encoder, &mut [
&mut VoxelCacheInsertion::ExternalRequest(
&structure_table_cache_insertion, &mut *structure_table),
&mut VoxelCacheInsertion::InternalRequest(
&cache_insertion, &request_buffer),
&mut VoxelCacheInsertion::InternalRequest(&cache_insertion),
]);
structure_table.insert(&device, &mut encoder,
&structure_table_cache_insertion, &structure_table_request_buffer);
&structure_table_cache_insertion);
```
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).
Validation and compaction run first for both batches, then one eviction
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.
Because the external insertion is processed first, newly produced chunk roots
@@ -278,11 +311,11 @@ branching logic based on `depth <= 2`.
---
## 6. The unwired production subsystem
## 6. The 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.
`src/production.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.
### 6.1 `src/production.rs`
@@ -331,7 +364,41 @@ callback. `produce_requests` does the real parallel mapping.
### 6.4 `src/production/request_queue.rs`
Untracked WIP. Do not depend on it.
A bounded, deduplicating, priority-ordered request queue. It is the durable
answer to "the cache re-emits the same request every frame".
Key model:
```rust
RequestKey {
producer_id,
structure_id,
target: Root | Child { parent: StructureLocator, children_index },
}
```
`Root` vs `Child` is explicit, so `(node_id = 0, children_index = 0)` (external
root and child 0 of the root) do not collide.
Properties:
- `ingest(frame, requests)` refreshes duplicates in place and drops requests
unseen for more than `stale_after` frames.
- Priority is `(root before child, higher demand, shallower depth)`, with
`first_seen` as a tie-breaker so old requests do not starve.
- Separate bounds `max_queued`, `max_in_flight`, and `max_ready`. Dispatch
preserves `ready.len() + in_flight <= max_ready`, so backpressure is visible
before workers run.
- New requests only evict queued jobs when strictly more urgent; otherwise they
are dropped and re-emitted next frame.
- Each job has a generation and attempt count. Completions from evicted,
expired, retried, or invalidated jobs are discarded.
- `invalidate_structure(id)` and `invalidate_producer(id)` remove all matching
queued/in-flight/ready jobs. Use the former for toroidal slot reuse.
- `ReadyItem::insertion_parent()` builds the `InsertionParent` for the insertion
batch from the latest `RequestMeta`.
The queue is unit-tested without a GPU (`cargo test production::request_queue`).
### 6.5 `src/host_production.rs`
@@ -379,21 +446,25 @@ Minimum viable path with the current demo interface:
- 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;
- 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. 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
5. Emit an `InsertionParent`:
- external: `InsertionParent::external(structure_id, producer_id)`;
- internal: `InsertionParent::internal(meta, structure_id, node_id, producer_id)`.
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`.
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;
- use the `VoxelProducer`/`VoxelAttributes` abstraction (or an equivalent) 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;
- implement filtering/mip generation for coarser levels so LOD stops do not
alias;
@@ -406,13 +477,14 @@ A production-ready producer should additionally:
| 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 |
| `fullfill_request` hardcodes `NTreeNodeLocator<4>`, x/y/z child unpacking with `4` and `16`, and a `+5000` chunk offset. | `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. | `src/main.rs` (`render`), `src/production/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. | `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 `production/` subsystem is compiled but not used by the demo driver. | `src/production.rs`, `src/production/*` | 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 |
| `src/production/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. | `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 |
+8 -5
View File
@@ -397,8 +397,9 @@ 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.
`CacheIndex`, `RequestInformation`, `RequestMeta`, `InsertionParent`,
`AttributeArray`, `LocationPage`, and child-pointer helpers so the Rust and WGSL
sides share names.
### 9.2 WGSL modules and entry points
@@ -407,11 +408,12 @@ Structure-table shaders use a simpler concatenation:
| `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/insertion.wgsl` | `validate_internal`, `insertion`, `consume` | Validate/compact internal entries, 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/write_pointers.wgsl` | `write_pointers` | Link internal insertion results into parent pages using the batch's `InsertionParent`. |
| `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/validate_insertion.wgsl` | `validate_external` | Keep only root entries whose slot still waits for a page. |
| `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. |
@@ -425,7 +427,8 @@ 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 1 — request handler, evictor, insertion data, 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.
+129 -46
View File
@@ -26,9 +26,8 @@ entry points into the cache.
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.
2. An insertion is identified by its own `InsertionParent`, not by its position
in a request buffer. Request order and insertion order may differ.
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
@@ -232,8 +231,8 @@ count** (2 in the demo). This naming collision is a common source of confusion.
```rust
pub enum VoxelCacheInsertion<'a, const N: usize> {
ExternalRequest(&'a CacheInsertionData<N>, &'a mut dyn CacheInvalidable),
InternalRequest(&'a CacheInsertionData<N>, &'a CacheRequestBuffer),
ExternalRequest(&'a CacheInsertionData<N>, &'a mut dyn CacheInvalidable<N>),
InternalRequest(&'a CacheInsertionData<N>),
}
```
@@ -249,27 +248,43 @@ preparation pass and one timestamp.
`CacheInvalidable` is implemented by the structure tables:
```rust
pub trait CacheInvalidable {
pub trait CacheInvalidable<const N: usize> {
fn invalidate(
&mut self,
encoder: &mut ScopeEncoder<CommandEncoder>,
cache_evictor: &CacheEvictor,
invalid_timestamp: u32,
);
fn validate_insertion(
&mut self,
device: &Device,
encoder: &mut ScopeEncoder<CommandEncoder>,
insertion: &CacheInsertionData<N>,
);
}
```
`validate_insertion` runs before page allocation: the table checks that each
external root's slot is still `subdividable, unavailable` and compacts the valid
entries. This prevents a stale root response from consuming a page, and lets a
slot be reused (toroidal move) without accepting a response for its old world
position.
### 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 |
| `page_count` | number of entries in this batch |
| `insertion_information` | dense `InsertionInformation<N>` per entry |
| `location_pages` | dense `LocationPage` per entry (includes `producer_id`) |
| `insertion_parents` | dense `InsertionParent` per entry |
| `destination_indices` | reset to `0xFFFFFFFF` by the validation pass; the insertion pass writes the destination page for accepted entries |
| `valid_indices` | filled by the validation pass: compacted indices of valid entries |
| `valid_count` | host writes `0`; the validation pass fills the amount of valid entries |
| attribute buffers | dense per-entry attribute payloads |
`InsertionInformation<N>` is just `children: [ChildInformation; 64]`, where each
`ChildInformation` uses the four-state encoding below.
@@ -279,6 +294,25 @@ bit 31 = subdividable
bit 30 = occupied
```
`InsertionParent` makes the batch self-describing. It is what replaces the
former request-buffer lookup:
```rust
struct InsertionParent {
kind: u32, // 0 = internal child, 1 = external root
page_index: u32, // parent cache page, or 0xFFFFFFFF for an external root
children_index: u32, // child slot in the parent
depth: u32, // parent depth, or 0xFFFFFFFF for an external root
structure_id: u32, // structure the parent belongs to
node_id: u32, // locator of the parent (0 for an external root)
producer_id: u32, // producer that owns the parent
}
```
A batch no longer has to be ordered like the request buffer. The host may
reorder, filter, or produce entries on different frames; the GPU validates each
entry independently.
The insertion shader converts child information into a `PointerPage`:
- every child pointer starts as `empty(subdividable)`;
@@ -286,8 +320,8 @@ The insertion shader converts child information into a `PointerPage`:
- 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).
table insertion pass. `0xFFFFFFFF` means "not inserted" (out of capacity, too
recently used, or invalid).
---
@@ -339,6 +373,8 @@ struct RequestInformation {
structure_id: u32, // from LocationPage
node_id: u32, // from LocationPage (the parent node)
children_index: u32, // requested child
producer_id: u32, // from LocationPage
demand: u32, // request counter for this slot this frame
}
struct RequestMeta {
@@ -348,6 +384,15 @@ struct RequestMeta {
}
```
`producer_id` lets a cache mix several producers and lets the host queue route
requests without guessing. `demand` is the raw request counter; the queue uses it
as the primary priority key.
The external-root marker is `RequestMeta.page_index == 0xFFFFFFFF`, **not**
`node_id == 0`. Both an external root and child 0 of the root carry
`node_id = 0, children_index = 0`, so a queue keyed on those fields alone would
collapse them.
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
@@ -355,10 +400,10 @@ struct RequestMeta {
### 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]`.
`CacheRequestBuffer::host_download_requests(device, queue, callback)` uses three
`DownloadBuffer::read_buffer` calls (count + informations + meta). A small
`RequestMapState` waits for all three and invokes the callback with
`&request_informations[0..count]` and `&request_meta[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).
@@ -371,13 +416,19 @@ For an **internal** request:
- `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.
- It must also emit an internal `InsertionParent` carrying the parent page,
child index, depth, and parent identity.
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`.
- `node_id` and `children_index` are 0, and `RequestMeta.page_index` is
`0xFFFFFFFF`.
- The producer must generate a chunk root and emit its `LocationPage` plus an
external `InsertionParent`.
There is no output-order requirement. Each insertion is attached to its parent
by its own `InsertionParent`.
---
@@ -387,11 +438,12 @@ For an **external** (structure-table) request:
```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]
A[prepare eviction list] --> B[validate + compact<br/>one per insertion]
B --> C[insertion pass<br/>one per insertion]
C --> D[external invalidation]
D --> E[cache invalidation]
E --> F[write pointers<br/>internal insertions only]
F --> G[frame_timestamp += 1]
```
### 6.1 Eviction preparation
@@ -410,14 +462,28 @@ flowchart TD
The resulting order is **timestamp-major, depth-minor**: least recently used
first, with deeper pages first among equal timestamps. See §7.
### 6.2 Insertion
### 6.2 Validation and insertion
For each insertion, `CacheInsertionPass::encode`:
Before any page is allocated, each batch is validated:
- **Internal** (`insertion.wgsl`, `validate_internal`): the parent page must
still have the same `structure_id`, `node_id`, `producer_id`, and depth, and
the requested child pointer must still be `subdividable, unavailable`.
- **External** (`fixed_table/validate_insertion.wgsl`): the table slot must still
be `subdividable, unavailable`.
Valid entries are compacted into `valid_indices` and counted in `valid_count`.
The validation pass resets every `destination_indices` entry to `0xFFFFFFFF`,
so invalid entries never get a page even if the host reuses an insertion buffer.
For each insertion, `CacheInsertionPass::encode` then:
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`;
2. Reads `valid_count` and computes
`available_amount = min(page_count_free - consumed, valid_count)`.
3. For compacted slot `i`:
- if `i >= available_amount`, leave `destination_indices[entry]` at
`0xFFFFFFFF` (already reset by validation);
- 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
@@ -448,16 +514,25 @@ be requested later.
### 6.5 Write pointers
For each internal insertion, `write_pointers.wgsl`:
For each internal insertion, `write_pointers.wgsl` reads the batch's own
`InsertionParent` (there is no request buffer):
```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;
let parent = insertion_data_parents[index];
if(parent.kind == INSERTION_PARENT_INTERNAL &&
insertion_data_destination_indices[index] != 0xFFFFFFFF &&
parent.page_index != insertion_data_destination_indices[index] &&
location_pages[parent.page_index] still has parent's identity)
{
structure_pointer_pages[parent.page_index].pointers[parent.children_index]
= child_pointer_make_available(destination_index);
structure_depth_pages[destination_index] = parent.depth + 1;
}
```
This is the step that actually links the new pages into the tree. It relies on
request index == insertion index.
This is the step that actually links the new pages into the tree. The identity
re-check catches the case where the parent page itself was recycled by the same
insertion batch.
### 6.6 Timestamp advance
@@ -515,10 +590,14 @@ root page? Structure tables answer that and emit requests when it is missing.
- `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])`.
`structure_id = slot`, `node_id = 0`, `children_index = 0`,
`producer_id = table producer`, `demand = slot counter`, and
`RequestMeta.page_index = 0xFFFFFFFF`.
- `validate_insertion`: `fixed_table/validate_insertion.wgsl` keeps only slots
that are still `subdividable, unavailable` and compacts their indices.
- `insert`: `fixed_table/insertion.wgsl` reads each entry's `InsertionParent`
and sets `pointers[slot] = available(destination_indices[i])` for external
roots whose slot is still waiting.
- `invalidate`: clears slots pointing at pages recycled this insert.
The table is dense: allocation is `slot_count * 4` bytes for pointers plus
@@ -534,6 +613,10 @@ The table is dense: allocation is `slot_count * 4` bytes for pointers plus
- `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.
It also returns the list of changed slot ids on the CPU. The host must feed
that list to the request queue (`invalidate_structure`) before batching
insertions, otherwise a response produced for the slot's old position could
be accepted after the toroidal move.
- `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.
@@ -575,7 +658,7 @@ Used by write-requests, insertion, invalidation, and write-pointers passes.
| `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 | — | — |
| `WritePointersPass` | structure | insertion data | — | — | — |
| Eviction reset / indirect copy | evictor | structure | scratch | — | — |
---
@@ -618,9 +701,9 @@ Memory example at 150k pages and 2 attributes is tabulated in
| `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 |
| Insertion order no longer matters: each entry is validated against its `InsertionParent` and linked statelessly. | `insertion.wgsl`, `write_pointers.wgsl`, `fixed_table/insertion.wgsl` | A producer may reorder or filter results; unchanged request order is no longer a correctness requirement. | High |
| `CacheInsertionPass` can silently insert fewer pages than requested (`0xFFFFFFFF` destinations) with no host feedback. | `src/voxel_cache/shaders/insertion.wgsl` | 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:248`, `src/voxel_cache/shaders/insertion.wgsl:141-146` | 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 |
| `CacheAttributeInit::DontTouch` attributes can become stale after a page is recycled; the cache deliberately does not clear them. | `src/voxel_cache/shaders/insertion.wgsl:164-178` | 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:445-449` | Easy to corrupt cache behaviour by writing to that buffer. | Medium |
+79 -12
View File
@@ -17,6 +17,7 @@ use glam::Mat4;
use glam::Vec3;
use glam::Vec4;
use itertools::Itertools;
use rayon::iter::IndexedParallelIterator;
use rayon::iter::IntoParallelRefIterator;
use rayon::iter::ParallelIterator;
use wgpu::BindGroupLayout;
@@ -65,8 +66,11 @@ use crate::voxel_cache::VoxelCacheInsertion;
use crate::voxel_cache::insertion::CacheInsertionData;
use crate::voxel_cache::requests::CacheRequestBuffer;
use crate::voxel_cache::schema::InsertionInformation;
use crate::voxel_cache::schema::InsertionParent;
use crate::voxel_cache::schema::LocationPage;
use crate::voxel_cache::schema::NO_PARENT_PAGE;
use crate::voxel_cache::schema::RequestInformation;
use crate::voxel_cache::schema::RequestMeta;
use crate::voxel_cache::tables::FixedStructureTable;
mod camera;
@@ -75,6 +79,7 @@ mod gi_pipeline;
mod gpu;
pub mod gpu_profiler;
mod producers;
mod production;
mod sparse_tree;
mod terrain;
mod voxel_cache;
@@ -407,6 +412,7 @@ impl State
(terrain_width, terrain_alt, terrain_height),
Vec3::ZERO,
structure_table_request_buffer.max_requests,
0,
);
let structure_table_insertion_data = CacheInsertionData::new(&device, 128, &layout);
let chunk_instances = (0..terrain_alt)
@@ -1292,7 +1298,7 @@ impl State
self.request_buffer.host_download_requests(
&self.device,
&self.queue,
move |request_informations| {
move |request_informations, request_metas| {
let done = request_buffer_done_1.load(std::sync::atomic::Ordering::Relaxed);
if !done
{
@@ -1310,26 +1316,32 @@ impl State
let mut color_attributes = vec![];
let mut normal_attributes: Vec<[[f32; 3]; 64]> = vec![];
let mut location_pages = vec![];
let mut insertion_parents = vec![];
request_informations
.par_iter()
.map(|request| {
.zip(request_metas.par_iter())
.map(|(request, meta)| {
fullfill_request(
cloned_generator.as_ref(),
request,
meta,
cloned_map.as_ref(),
&cloned_table_1,
)
})
.collect::<Vec<_>>()
.into_iter()
.for_each(|(colors, normals, insertion_info, location)| {
.for_each(|(colors, normals, insertion_info, location, parent)| {
insertion_infos.push(insertion_info);
color_attributes.push(colors);
normal_attributes.push(std::array::from_fn(|i| normals[i].into()));
location_pages.push(location);
insertion_parents.push(parent);
});
let request_count = request_informations.len() as u32;
cloned_queue.write_buffer(
cloned_insertion_data.insertion_information_buffer(),
0,
@@ -1342,6 +1354,12 @@ impl State
bytemuck::cast_slice(&location_pages),
);
cloned_queue.write_buffer(
cloned_insertion_data.insertion_parents_buffer(),
0,
bytemuck::cast_slice(&insertion_parents),
);
cloned_queue.write_buffer(
&cloned_insertion_data.attributes_buffers()[0],
0,
@@ -1354,10 +1372,22 @@ impl State
bytemuck::cast_slice(&normal_attributes),
);
cloned_queue.write_buffer(
cloned_insertion_data.destination_indices_buffer(),
0,
bytemuck::cast_slice(&vec![u32::MAX; request_count as usize]),
);
cloned_queue.write_buffer(
cloned_insertion_data.valid_count_buffer(),
0,
bytemuck::bytes_of(&0u32),
);
cloned_queue.write_buffer(
cloned_insertion_data.page_count_buffer(),
0,
bytemuck::bytes_of(&(request_informations.len() as u32)),
bytemuck::bytes_of(&request_count),
);
},
);
@@ -1375,7 +1405,7 @@ impl State
self.structure_table_request_buffer.host_download_requests(
&self.device,
&self.queue,
move |request_informations| {
move |request_informations, request_metas| {
let done = structure_table_request_buffer_done_1
.load(std::sync::atomic::Ordering::Relaxed);
if !done
@@ -1395,26 +1425,32 @@ impl State
let mut color_attributes = vec![];
let mut normal_attributes: Vec<[[f32; 3]; 64]> = vec![];
let mut location_pages = vec![];
let mut insertion_parents = vec![];
request_informations
.par_iter()
.map(|request| {
.zip(request_metas.par_iter())
.map(|(request, meta)| {
fullfill_request(
cloned_generator.as_ref(),
request,
meta,
cloned_map.as_ref(),
&cloned_table_2,
)
})
.collect::<Vec<_>>()
.into_iter()
.for_each(|(colors, normals, insertion_info, location)| {
.for_each(|(colors, normals, insertion_info, location, parent)| {
insertion_infos.push(insertion_info);
color_attributes.push(colors);
normal_attributes.push(std::array::from_fn(|i| normals[i].into()));
location_pages.push(location);
insertion_parents.push(parent);
});
let request_count = request_informations.len() as u32;
cloned_queue.write_buffer(
cloned_st_insertion_data.insertion_information_buffer(),
0,
@@ -1427,6 +1463,12 @@ impl State
bytemuck::cast_slice(&location_pages),
);
cloned_queue.write_buffer(
cloned_st_insertion_data.insertion_parents_buffer(),
0,
bytemuck::cast_slice(&insertion_parents),
);
cloned_queue.write_buffer(
&cloned_st_insertion_data.attributes_buffers()[0],
0,
@@ -1439,10 +1481,22 @@ impl State
bytemuck::cast_slice(&normal_attributes),
);
cloned_queue.write_buffer(
cloned_st_insertion_data.destination_indices_buffer(),
0,
bytemuck::cast_slice(&vec![u32::MAX; request_count as usize]),
);
cloned_queue.write_buffer(
cloned_st_insertion_data.valid_count_buffer(),
0,
bytemuck::bytes_of(&0u32),
);
cloned_queue.write_buffer(
cloned_st_insertion_data.page_count_buffer(),
0,
bytemuck::bytes_of(&(request_informations.len() as u32)),
bytemuck::bytes_of(&request_count),
);
},
);
@@ -1614,7 +1668,6 @@ impl State
),
&mut VoxelCacheInsertion::InternalRequest(
&self.cache_insertion,
&self.request_buffer,
),
],
);
@@ -1623,7 +1676,6 @@ impl State
&self.device,
&mut scoped_encoder,
&self.structure_table_cache_insertion,
&self.structure_table_request_buffer,
);
}
@@ -1762,6 +1814,7 @@ pub struct ChunkImmediate
fn fullfill_request<const N: usize>(
generator: &dyn ChunkedProducer<N>,
request: &RequestInformation,
meta: &RequestMeta,
map: &HashMap<u32, (usize, usize, usize)>,
table: &Arc<Mutex<ToroidalStructureTable>>,
) -> (
@@ -1769,6 +1822,7 @@ fn fullfill_request<const N: usize>(
[[f32; 3]; N * N * N],
InsertionInformation<N>,
LocationPage,
InsertionParent,
)
where
[(); N * N * N]:,
@@ -1795,14 +1849,19 @@ where
let location;
let node;
if request.node_id == 0
let parent;
if meta.page_index == NO_PARENT_PAGE
{
// Produce root node
// Produce root node. An external (structure-table) request is the only
// one without a parent page; `node_id == 0` also happens for child 0 of
// the root, so it cannot be used to detect roots.
node = generator.produce_node(0, 0, 0, 0, (chunk_x, chunk_y, chunk_z));
location = LocationPage {
structure_id: request.structure_id,
node_id: NTreeNodeLocator::<4>::root().as_usize() as u32,
producer_id: request.producer_id,
};
parent = InsertionParent::external(request.structure_id, request.producer_id);
}
else
{
@@ -1824,7 +1883,14 @@ where
location = LocationPage {
structure_id: request.structure_id,
node_id: child_locator.as_usize() as u32,
producer_id: request.producer_id,
};
parent = InsertionParent::internal(
meta,
request.structure_id,
request.node_id,
request.producer_id,
);
}
(
@@ -1834,5 +1900,6 @@ where
children: node.children,
},
location,
parent,
)
}
+6 -3
View File
@@ -9,11 +9,14 @@ pub mod tree_locator;
/// Facilities for voxel production on the host (CPU) side
pub mod host_production;
/// Bounded, deduplicating, priority-ordered cache request queue
pub mod request_queue;
/// 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)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Zeroable, Pod)]
#[repr(transparent)]
pub struct ProducerId(pub u32);
@@ -21,13 +24,13 @@ pub struct ProducerId(pub u32);
/// 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)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, 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)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Zeroable, Pod)]
#[repr(transparent)]
pub struct StructureLocator(pub u32);
+1 -1
View File
@@ -39,7 +39,7 @@ where
insertion: &CacheInsertionData<N>,
)
{
request_buffer.host_download_requests(device, queue, |requests| {});
request_buffer.host_download_requests(device, queue, |_requests, _metas| {});
}
pub fn produce_requests(
File diff suppressed because it is too large Load Diff
+61 -13
View File
@@ -47,6 +47,7 @@ impl ToroidalStructureTable
extent: (usize, usize, usize),
initial_position: Vec3,
max_requests: usize,
producer_id: u32,
) -> Self
{
let size = extent.0 * extent.1 * extent.2;
@@ -81,7 +82,12 @@ impl ToroidalStructureTable
ToroidalStructureTable {
extent,
fixed_structure_table: FixedStructureTable::new(device, size, max_requests),
fixed_structure_table: FixedStructureTable::new(
device,
size,
max_requests,
producer_id,
),
position: initial_position,
current_offset,
invalidation_pass,
@@ -89,13 +95,37 @@ impl ToroidalStructureTable
}
/// Moves the center position to `new_position`.
/// This requires updating to structure table to remove disapearing chunks
pub fn move_position(&mut self, encoder: &mut CommandEncoder, new_position: Vec3)
/// This requires updating to structure table to remove disapearing chunks.
///
/// Returns the structure slots whose world position changed. The host must
/// invalidate any pending request/insertion work for those slots before it
/// batches insertions for this frame.
pub fn move_position(
&mut self,
encoder: &mut CommandEncoder,
new_position: Vec3,
) -> Vec<u32>
{
let previous_offset = self.current_offset;
self.current_offset = Self::offset_from_center(self.extent, new_position);
let new_offset = Self::offset_from_center(self.extent, new_position);
self.current_offset = new_offset;
self.position = new_position;
let mut invalidated = Vec::new();
if previous_offset != new_offset
{
let size = self.extent.0 * self.extent.1 * self.extent.2;
for id in 0..size
{
let previous = Self::position_for_offset(self.extent, id, previous_offset);
let current = Self::position_for_offset(self.extent, id, new_offset);
if previous != current
{
invalidated.push(id as u32);
}
}
}
let invalidation_parameters = ToroidalInvalidationImmediates {
extent: [
self.extent.0 as u32,
@@ -130,23 +160,30 @@ impl ToroidalStructureTable
self.extent.1.div_ceil(4) as u32,
self.extent.2.div_ceil(4) as u32,
);
invalidated
}
/// Given the structure id, returns the position of the requesting chunk
pub fn get_request_position(&self, structure_id: u32) -> (isize, isize, isize)
{
let (ex, ey, ez) = (
self.extent.0 as isize,
self.extent.1 as isize,
self.extent.2 as isize,
);
Self::position_for_offset(self.extent, structure_id as usize, self.current_offset)
}
fn position_for_offset(
extent: (usize, usize, usize),
structure_id: usize,
offset: (isize, isize, isize),
) -> (isize, isize, isize)
{
let (ex, ey, ez) = (extent.0 as isize, extent.1 as isize, extent.2 as isize);
let id = structure_id as isize;
let sx = id % ex;
let sz = (id / ex) % ez;
let sy = id / (ex * ez);
let (ox, oy, oz) = self.current_offset;
let (ox, oy, oz) = offset;
(
ox + (sx - ox).rem_euclid(ex),
@@ -181,12 +218,11 @@ impl ToroidalStructureTable
device: &wgpu::Device,
encoder: &mut crate::gpu_profiler::ScopeEncoder<wgpu::CommandEncoder>,
insertion: &voxel_cache::insertion::CacheInsertionData<N>,
request: &voxel_cache::requests::CacheRequestBuffer,
) where
[(); N * N * N]:,
{
self.fixed_structure_table
.insert(device, encoder, insertion, request);
.insert(device, encoder, insertion);
}
pub fn gather_requests(
@@ -201,8 +237,20 @@ impl ToroidalStructureTable
}
}
impl voxel_cache::CacheInvalidable for ToroidalStructureTable
impl<const N: usize> voxel_cache::CacheInvalidable<N> for ToroidalStructureTable
where
[(); N * N * N]:,
{
fn validate_insertion(
&mut self,
device: &wgpu::Device,
encoder: &mut crate::gpu_profiler::ScopeEncoder<CommandEncoder>,
insertion: &voxel_cache::insertion::CacheInsertionData<N>,
) {
self.fixed_structure_table
.validate_insertion(device, encoder, insertion);
}
fn invalidate(
&mut self,
encoder: &mut crate::gpu_profiler::ScopeEncoder<CommandEncoder>,
+40 -6
View File
@@ -108,7 +108,9 @@ where
frame_timestamp: u32,
}
pub trait CacheInvalidable
pub trait CacheInvalidable<const N: usize>
where
[(); N * N * N]:,
{
fn invalidate(
&mut self,
@@ -116,14 +118,23 @@ pub trait CacheInvalidable
cache_evictor: &CacheEvictor,
invalid_timestamp: u32,
);
/// Validates an external insertion batch against the structure table and
/// compacts the valid entries before the cache allocates pages for them.
fn validate_insertion(
&mut self,
device: &Device,
encoder: &mut ScopeEncoder<CommandEncoder>,
insertion: &CacheInsertionData<N>,
);
}
pub enum VoxelCacheInsertion<'a, const N: usize>
where
[(); N * N * N]:,
{
ExternalRequest(&'a CacheInsertionData<N>, &'a mut dyn CacheInvalidable),
InternalRequest(&'a CacheInsertionData<N>, &'a CacheRequestBuffer),
ExternalRequest(&'a CacheInsertionData<N>, &'a mut dyn CacheInvalidable<N>),
InternalRequest(&'a CacheInsertionData<N>),
}
impl<const N: usize> VoxelCache<N>
@@ -243,12 +254,36 @@ where
&mut encoder,
);
// Validate everything before allocating any page, so stale insertions
// can never consume a recycled page.
for insertion in insertions.iter_mut()
{
match insertion
{
VoxelCacheInsertion::ExternalRequest(cache_insertion_data, invalidable) =>
{
invalidable.validate_insertion(device, &mut encoder, cache_insertion_data);
}
VoxelCacheInsertion::InternalRequest(cache_insertion_data) =>
{
self.cache_insertion_pass.encode_validation(
device,
&mut encoder,
&self.attributes,
&self.structure,
cache_insertion_data,
&self.evictor,
);
}
}
}
for insertion in insertions.iter()
{
match insertion
{
VoxelCacheInsertion::ExternalRequest(cache_insertion_data, _)
| VoxelCacheInsertion::InternalRequest(cache_insertion_data, _) =>
| VoxelCacheInsertion::InternalRequest(cache_insertion_data) =>
{
self.cache_insertion_pass.encode(
device,
@@ -283,13 +318,12 @@ where
// Write internal requests pointers
for insertion in insertions.iter_mut()
{
if let VoxelCacheInsertion::InternalRequest(insertion, request) = insertion
if let VoxelCacheInsertion::InternalRequest(insertion) = insertion
{
self.write_pointers_pass.encode(
&mut encoder,
device,
&self.structure,
request,
insertion,
);
}
+86 -42
View File
@@ -6,6 +6,7 @@ use wgpu::ShaderStages;
use crate::voxel_cache::layout::CacheLayout;
use crate::voxel_cache::schema::InsertionInformation;
use crate::voxel_cache::schema::InsertionParent;
use crate::voxel_cache::schema::LocationPage;
/// Data to be inserted in a cache insertion operation
@@ -31,6 +32,15 @@ where
/// Contains the indicies of the page in which the data was written
destination_indices: wgpu::Buffer,
/// Parent/attachment information for every entry : dense array of [`InsertionParent`]
insertion_parents: wgpu::Buffer,
/// Indices of the entries that passed validation, written by the validation pass
valid_indices: wgpu::Buffer,
/// Amount of entries written to [`Self::valid_indices`]
valid_count: wgpu::Buffer,
bind_group_layout: wgpu::BindGroupLayout,
bind_group: wgpu::BindGroup,
bind_group_no_attributes: wgpu::BindGroup,
@@ -65,11 +75,32 @@ where
let destination_indices = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheInsertionData::destination_indices"),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
size: (size_of::<u32>() * max_page_count) as u64,
});
let insertion_parents = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheInsertionData::insertion_parents"),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
size: (size_of::<InsertionParent>() * max_page_count) as u64,
});
let valid_indices = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheInsertionData::valid_indices"),
usage: wgpu::BufferUsages::STORAGE,
mapped_at_creation: false,
size: (size_of::<u32>() * max_page_count) as u64,
});
let valid_count = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheInsertionData::valid_count"),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
size: size_of::<u32>() as u64,
});
let attributes = layout
.attributes
.iter()
@@ -105,6 +136,18 @@ where
binding: 3,
resource: destination_indices.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: insertion_parents.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 5,
resource: valid_indices.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 6,
resource: valid_count.as_entire_binding(),
},
];
let bind_group_layout_no_attributes = Self::create_bind_group_layout(device, None);
@@ -114,7 +157,7 @@ where
entries: &entries,
});
entries.push(wgpu::BindGroupEntry {
binding: 4,
binding: 7,
resource: wgpu::BindingResource::BufferArray(&bind_group_bindings),
});
@@ -131,6 +174,9 @@ where
insertion_information,
location_pages,
destination_indices,
insertion_parents,
valid_indices,
valid_count,
attributes,
bind_group_layout,
@@ -155,53 +201,31 @@ where
layout: Option<&CacheLayout>,
) -> BindGroupLayout
{
let storage_entry = |binding: u32| wgpu::BindGroupLayoutEntry {
binding,
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 mut entries = vec![
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
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,
},
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,
},
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,
},
storage_entry(0), // page count
storage_entry(1), // insertion information
storage_entry(2), // location pages
storage_entry(3), // destination indices
storage_entry(4), // insertion parents
storage_entry(5), // valid indices
storage_entry(6), // valid count
];
if let Some(layout) = layout
{
entries.push(wgpu::BindGroupLayoutEntry {
binding: 4,
binding: 7,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
@@ -248,6 +272,26 @@ where
&self.location_pages
}
pub fn destination_indices_buffer(&self) -> &wgpu::Buffer
{
&self.destination_indices
}
pub fn insertion_parents_buffer(&self) -> &wgpu::Buffer
{
&self.insertion_parents
}
pub fn valid_indices_buffer(&self) -> &wgpu::Buffer
{
&self.valid_indices
}
pub fn valid_count_buffer(&self) -> &wgpu::Buffer
{
&self.valid_count
}
pub fn attributes_buffers(&self) -> &[wgpu::Buffer]
{
&self.attributes
+54 -5
View File
@@ -160,6 +160,9 @@ where
/// Copies new pages into cache using LRU order
write_pipeline: ComputePipeline,
/// Validates internal insertions and compacts their indices
validate_internal_pipeline: ComputePipeline,
/// u32 buffer containing amount of inserted data of current pass
inserted_count: wgpu::Buffer,
inserted_count_bind_group: wgpu::BindGroup,
@@ -244,8 +247,19 @@ where
cache: None,
});
let validate_internal_pipeline =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("CacheInsertionPass::validate_internal_pipeline"),
layout: Some(&pipeline_layout),
module: &shader_module,
entry_point: Some("validate_internal"),
compilation_options: Default::default(),
cache: None,
});
Self {
write_pipeline,
validate_internal_pipeline,
consume_pipeline,
inserted_count,
inserted_count_bind_group,
@@ -253,6 +267,45 @@ where
}
}
/// Validates internal insertions and compacts them into the insertion data's
/// `valid_indices` buffer.
///
/// External roots are validated by the structure table that requested them.
#[allow(clippy::too_many_arguments)]
pub fn encode_validation(
&self,
device: &wgpu::Device,
encoder: &mut ScopeEncoder<CommandEncoder>,
cache_attributes: &CacheAttributes<N>,
cache_structure: &CacheStructure<N>,
insertion_data: &CacheInsertionData<N>,
cache_evictor: &CacheEvictor,
)
{
gpu_profiler::begin_scope!(encoder, "PageInsertionValidation");
let indirect_write_dispatch = self.indirect_dispatcher.workgroup_count(
device,
&mut encoder,
insertion_data.page_count_buffer(),
256,
);
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("CacheInsertionPass::validation_pass"),
timestamp_writes: None,
});
pass.set_bind_group(0, cache_attributes.bind_group(), &[]);
pass.set_bind_group(1, cache_structure.bind_group(), &[]);
pass.set_bind_group(2, insertion_data.bind_group(), &[]);
pass.set_bind_group(3, cache_evictor.bind_group(), &[]);
pass.set_bind_group(4, &self.inserted_count_bind_group, &[]);
pass.set_pipeline(&self.validate_internal_pipeline);
pass.dispatch_workgroups_indirect(indirect_write_dispatch, 0);
}
#[allow(clippy::too_many_arguments)]
pub fn encode(
&self,
@@ -396,8 +449,6 @@ where
let bindings = [
// To find where pages are pointing
Some(&CacheStructure::<N>::create_bind_group_layout(device)),
// To find where the requests came from
Some(&CacheRequestBuffer::create_bind_group_layout(device)),
// To find where the request's response went
Some(&CacheInsertionData::<N>::create_bind_group_layout(
device,
@@ -438,7 +489,6 @@ where
encoder: &mut ScopeEncoder<CommandEncoder>,
device: &Device,
cache_structure: &CacheStructure<N>,
request_buffer: &CacheRequestBuffer,
cache_insertion_data: &CacheInsertionData<N>,
)
{
@@ -458,8 +508,7 @@ where
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, cache_structure.bind_group(), &[]);
pass.set_bind_group(1, request_buffer.bind_group(), &[]);
pass.set_bind_group(2, cache_insertion_data.bind_group(), &[]);
pass.set_bind_group(1, cache_insertion_data.bind_group(), &[]);
pass.dispatch_workgroups_indirect(indirect_buffer, 0);
}
+42 -9
View File
@@ -150,7 +150,7 @@ impl<const N: usize> CacheRequestHandler<N>
let bind_group = create_multi_buffers_bind_group(
device,
&bind_group_layout,
&[&request_count, &sorted_requests],
&[&request_count, &sorted_requests, &request_counts_pages],
Some("CacheRequestHandler::bind_group"),
);
@@ -299,7 +299,7 @@ impl<const N: usize> CacheRequestHandler<N>
{
create_multi_buffers_bind_group_layout(
device,
2,
3,
Some("CacheRequestHandler::bind_group_layout"),
)
}
@@ -390,14 +390,16 @@ impl CacheRequestBuffer
&self.bind_group
}
pub fn host_download_requests<F: FnMut(&[RequestInformation]) + Send + Sync + 'static>(
pub fn host_download_requests<
F: FnMut(&[RequestInformation], &[RequestMeta]) + Send + Sync + 'static,
>(
&self,
device: &Device,
queue: &wgpu::Queue,
callback: F,
)
{
// Once the two required buffer have been mapped, the requestMapState will automatically
// Once the three required buffers have been mapped, the requestMapState will automatically
// fire the callback
let request_map_state = Arc::new(Mutex::new(RequestMapState::new(callback)));
@@ -433,33 +435,58 @@ impl CacheRequestBuffer
.set_request_infos(request_infos);
},
);
let request_map_state_3 = request_map_state.clone();
wgpu::util::DownloadBuffer::read_buffer(
device,
queue,
&self.request_meta.slice(..),
move |buffer| {
let mapped_buffer = buffer.expect("Could not map request buffer (meta).");
let request_metas: Vec<RequestMeta> =
bytemuck::pod_collect_to_vec(&mapped_buffer);
request_map_state_3
.lock()
.unwrap()
.set_request_metas(request_metas);
},
);
}
}
struct RequestMapState<F: FnMut(&[RequestInformation]) -> () + Send + Sync + 'static>
struct RequestMapState<F: FnMut(&[RequestInformation], &[RequestMeta]) + Send + Sync + 'static>
{
request_count: Option<usize>,
request_infos: Option<Vec<RequestInformation>>,
request_metas: Option<Vec<RequestMeta>>,
callback: F,
}
impl<F: FnMut(&[RequestInformation]) -> () + Send + Sync + 'static> RequestMapState<F>
impl<F: FnMut(&[RequestInformation], &[RequestMeta]) + Send + Sync + 'static> RequestMapState<F>
{
pub fn new(callback: F) -> Self
{
Self {
request_count: None,
request_infos: None,
request_metas: None,
callback,
}
}
fn try_callback(&mut self)
{
if let (Some(request_count), Some(request_infos)) =
(self.request_count, &self.request_infos)
if let (Some(request_count), Some(request_infos), Some(request_metas)) = (
self.request_count,
&self.request_infos,
&self.request_metas,
)
{
(self.callback)(&request_infos[0..request_count])
(self.callback)(
&request_infos[0..request_count],
&request_metas[0..request_count],
)
}
}
@@ -474,4 +501,10 @@ impl<F: FnMut(&[RequestInformation]) -> () + Send + Sync + 'static> RequestMapSt
self.request_infos = Some(request_infos);
self.try_callback();
}
pub fn set_request_metas(&mut self, request_metas: Vec<RequestMeta>)
{
self.request_metas = Some(request_metas);
self.try_callback();
}
}
+108
View File
@@ -110,6 +110,9 @@ pub struct LocationPage
/// Identifier for locating this particular node within the structure
pub node_id: u32,
/// Identifier of the producer that owns this node
pub producer_id: u32,
}
/// Page storing the depth of the current node related to its root.
@@ -150,6 +153,12 @@ pub struct RequestInformation
/// The index of the children on which the request was issued
pub children_index: u32,
/// Identifier of the producer that owns the requesting node
pub producer_id: u32,
/// The amount of times this request was emitted this frame. Higher means more urgent.
pub demand: u32,
}
/// Metainformation kept along each request, to know which node made the demand
@@ -168,6 +177,105 @@ pub struct RequestMeta
pub depth: u32,
}
/// Sentinel used in [`RequestMeta::page_index`] and [`InsertionParent::page_index`] to mark a
/// request/insertion that has no cache parent (an external root requested by a structure table).
pub const NO_PARENT_PAGE: u32 = u32::MAX;
/// Kind of parent an insertion is attached to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Zeroable, Pod)]
#[repr(transparent)]
pub struct InsertionParentKind(u32);
impl InsertionParentKind
{
/// The new page is a child of a resident cache page.
pub const INTERNAL: Self = Self(0);
/// The new page is the root of a structure owned by a structure table.
pub const EXTERNAL: Self = Self(1);
pub fn raw(self) -> u32
{
self.0
}
}
/// Identity and attachment point of the page being inserted.
///
/// This makes an insertion batch self-describing: the GPU can validate that the parent is still
/// the node the request was issued on, and link the new page without reading the request buffer.
#[derive(Clone, Copy, Debug, Zeroable, Pod)]
#[repr(C)]
pub struct InsertionParent
{
/// [`InsertionParentKind`].
pub kind: u32,
/// Cache page of the parent. [`NO_PARENT_PAGE`] for external roots.
pub page_index: u32,
/// Child slot inside the parent. `0` for external roots.
pub children_index: u32,
/// Depth of the parent. [`NO_PARENT_PAGE`] for external roots.
pub depth: u32,
/// Structure the parent belongs to.
pub structure_id: u32,
/// Locator of the parent inside the structure. `0` for external roots.
pub node_id: u32,
/// Producer that owns the parent.
pub producer_id: u32,
}
impl InsertionParent
{
/// Parent information for a child of a resident cache page.
pub fn internal(
meta: &RequestMeta,
structure_id: u32,
node_id: u32,
producer_id: u32,
) -> Self
{
Self {
kind: InsertionParentKind::INTERNAL.raw(),
page_index: meta.page_index,
children_index: meta.children_index,
depth: meta.depth,
structure_id,
node_id,
producer_id,
}
}
/// Parent information for the root of an external structure.
pub fn external(structure_id: u32, producer_id: u32) -> Self
{
Self {
kind: InsertionParentKind::EXTERNAL.raw(),
page_index: NO_PARENT_PAGE,
children_index: 0,
depth: NO_PARENT_PAGE,
structure_id,
node_id: 0,
producer_id,
}
}
pub fn is_external(&self) -> bool
{
self.kind == InsertionParentKind::EXTERNAL.raw()
}
pub fn is_internal(&self) -> bool
{
self.kind == InsertionParentKind::INTERNAL.raw()
}
}
/// Structure information about the children of a node.
/// Used when inserting data in the cache, to setup structure pointers
///
+20 -1
View File
@@ -9,7 +9,9 @@ struct RequestInformation
{
structure_id: u32,
node_id: u32,
children_index: u32
children_index: u32,
producer_id: u32,
demand: u32
}
struct RequestMeta
@@ -19,6 +21,22 @@ struct RequestMeta
depth: u32
}
// No cache parent (external root insertion).
const NO_PARENT_PAGE: u32 = 0xFFFFFFFFu;
const INSERTION_PARENT_INTERNAL: u32 = 0u;
const INSERTION_PARENT_EXTERNAL: u32 = 1u;
struct InsertionParent
{
kind: u32,
page_index: u32,
children_index: u32,
depth: u32,
structure_id: u32,
node_id: u32,
producer_id: u32,
}
struct AttributeArray
{
values: array<u32>
@@ -28,6 +46,7 @@ struct LocationPage
{
structure_id: u32,
node_id: u32,
producer_id: u32,
}
fn child_information_occupied(info: u32) -> bool
@@ -6,27 +6,46 @@
@group(1) @binding(1) var<storage, read_write> insertion_data_information: array<u32>; // UNUSED
@group(1) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
@group(1) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
@group(1) @binding(4) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
@group(1) @binding(4) var<storage, read_write> insertion_data_parents: array<InsertionParent>;
@group(1) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
@group(1) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
/// Group 2: Request buffer
@group(2) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
@group(2) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
@group(2) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
@compute
@workgroup_size(256, 1, 1)
fn insertion(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
if(index >= insertion_data_page_count_buffer)
let entry_count = min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents));
if(index >= entry_count)
{
return;
}
let parent = insertion_data_parents[index];
if(parent.kind != INSERTION_PARENT_EXTERNAL)
{
return;
}
let destination = insertion_data_destination_indices[index];
if(destination != 0xFFFFFFFF)
if(destination == DESTINATION_NONE)
{
let request_location = request_buffer_informations[index].structure_id;
fixed_table_pointers[request_location] = child_pointer_make_available(insertion_data_destination_indices[index]);
return;
}
if(parent.structure_id >= arrayLength(&fixed_table_pointers))
{
return;
}
// Re-check that the slot is still waiting for this root.
let pointer = fixed_table_pointers[parent.structure_id];
if(!child_pointer_subdivided(pointer) || child_pointer_available(pointer))
{
return;
}
fixed_table_pointers[parent.structure_id] = child_pointer_make_available(destination);
}
@@ -0,0 +1,56 @@
// Group 0: Table pointers
@group(0) @binding(0) var<storage, read_write> fixed_table_pointers: array<u32>;
// Group 1: Cache insertion data
@group(1) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
@group(1) @binding(1) var<storage, read_write> insertion_data_information: array<u32>; // UNUSED
@group(1) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
@group(1) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
@group(1) @binding(4) var<storage, read_write> insertion_data_parents: array<InsertionParent>;
@group(1) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
@group(1) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
/// Validates external root insertions against the structure table.
///
/// A root is still wanted while its table slot is subdivisible but not yet
/// available. Slots that were already satisfied (or whose structure was
/// invalidated before the request was dispatched) are dropped here, before the
/// cache allocates any page for them.
@compute
@workgroup_size(256, 1, 1)
fn validate_external(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
let entry_count = min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents));
if(index >= entry_count)
{
return;
}
let parent = insertion_data_parents[index];
// Reset every destination; only validated entries that are allocated get a
// page written back by the cache insertion pass.
insertion_data_destination_indices[index] = DESTINATION_NONE;
if(parent.kind != INSERTION_PARENT_EXTERNAL)
{
return;
}
if(parent.structure_id >= arrayLength(&fixed_table_pointers))
{
return;
}
let pointer = fixed_table_pointers[parent.structure_id];
if(!child_pointer_subdivided(pointer) || child_pointer_available(pointer))
{
return;
}
let slot = atomicAdd(&insertion_data_valid_count, 1u);
insertion_data_valid_indices[slot] = index;
}
@@ -1,12 +1,15 @@
/// Group 0: Cache request handler
@group(0) @binding(0) var<storage, read_write> request_handler_count: u32; // Request count
@group(0) @binding(1) var<storage, read_write> request_handler_requests: array<u32>;
@group(0) @binding(2) var<storage, read_write> request_handler_counts: array<u32>;
/// Group 1: Request buffer
@group(1) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
@group(1) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
@group(1) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
var<immediate> table_producer_id: u32;
@compute
@workgroup_size(256, 1, 1)
fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
@@ -18,13 +21,18 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
return;
}
let structure_id = request_handler_requests[index];
var request_info: RequestInformation;
request_info.structure_id = request_handler_requests[index];
request_info.structure_id = structure_id;
request_info.node_id = 0;
request_info.children_index = 0;
request_info.producer_id = table_producer_id;
request_info.demand = request_handler_counts[structure_id];
var request_meta: RequestMeta;
request_meta.page_index = 0;
// External requests have no parent page.
request_meta.page_index = 0xFFFFFFFF;
request_meta.children_index = 0;
// u32s wrap arround
request_meta.depth = 0xFFFFFFFF;
+103 -25
View File
@@ -12,7 +12,10 @@
@group(2) @binding(1) var<storage, read_write> insertion_data_information: array<InsertionInformation>;
@group(2) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
@group(2) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
@group(2) @binding(4) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
@group(2) @binding(4) var<storage, read_write> insertion_data_parents: array<InsertionParent>;
@group(2) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
@group(2) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
@group(2) @binding(7) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
// Group 3: Cache evictor
@group(3) @binding(0) var<storage, read_write> cache_evictor_timestamps: array<u32>;
@@ -24,13 +27,79 @@
var<immediate> new_timestamp: u32;
// Computes amount of available LRU pages
fn available_amount() -> u32
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
fn insertion_entry_count() -> u32
{
return min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents));
}
/// Checks that the parent page still holds the node the request was issued on,
/// and that the requested child slot is still waiting for a page.
fn internal_parent_is_valid(parent: InsertionParent) -> bool
{
if(parent.page_index >= PAGE_COUNT)
{
return false;
}
let location = structure_location_pages[parent.page_index];
if(location.structure_id != parent.structure_id ||
location.node_id != parent.node_id ||
location.producer_id != parent.producer_id)
{
return false;
}
if(structure_depth_pages[parent.page_index] != parent.depth)
{
return false;
}
let pointer = structure_pointer_pages[parent.page_index].pointers[parent.children_index];
return child_pointer_subdivided(pointer) && !child_pointer_available(pointer);
}
/// Validates a batch of internal insertions and compacts the valid ones into
/// `insertion_data_valid_indices`.
///
/// This must run before page allocation so that stale insertions never consume
/// an evicted page. External roots are validated by the structure table that
/// requested them (see `fixed_table/validate_insertion.wgsl`).
@compute
@workgroup_size(256, 1, 1)
fn validate_internal(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
if(index >= insertion_entry_count())
{
return;
}
let parent = insertion_data_parents[index];
// Reset the destination of every entry. Only entries compacted into
// `valid_indices` and actually allocated by the insertion pass get a page;
// this keeps invalid/stale insertions from reusing a previous batch's
// destination if the host did not pre-fill the buffer.
insertion_data_destination_indices[index] = DESTINATION_NONE;
if(parent.kind != INSERTION_PARENT_INTERNAL)
{
return;
}
if(internal_parent_is_valid(parent))
{
let slot = atomicAdd(&insertion_data_valid_count, 1u);
insertion_data_valid_indices[slot] = index;
}
}
fn available_amount(valid_count: u32) -> u32
{
let lru_remaining = arrayLength(&cache_evictor_timestamps) - cache_evictor_consumed_count;
let available_amount = min(lru_remaining, insertion_data_page_count_buffer);
return available_amount;
return min(lru_remaining, valid_count);
}
@compute
@@ -38,7 +107,7 @@ fn available_amount() -> u32
fn consume(@builtin(global_invocation_id) gid: vec3<u32>)
{
// Report consumed amount of LRU pages to cache evictor
// So that subsequent insertions can can continue to use new pages
// So that subsequent insertions can can continue to use new pages
cache_evictor_consumed_count += atomicLoad(&pass_inserted_count);
atomicStore(&pass_inserted_count, 0);
}
@@ -47,48 +116,57 @@ fn consume(@builtin(global_invocation_id) gid: vec3<u32>)
@workgroup_size(256, 1, 1)
fn insertion(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
//let insertion_count = min(array_length(&insertion_data_information), insertion_data_page_count_buffer);
let insertion_count = available_amount();
if(index >= insertion_data_page_count_buffer)
let slot = gid.x;
let entry_count = insertion_entry_count();
if(slot >= entry_count)
{
return;
}
if(index >= insertion_count)
{
// Report that page was not written
insertion_data_destination_indices[index] = 0xFFFFFFFF;
return;
let valid_count = atomicLoad(&insertion_data_valid_count);
if(slot >= valid_count)
{
return;
}
// Compacted entry index in the host-provided arrays.
let index = insertion_data_valid_indices[slot];
let insertion_count = available_amount(valid_count);
if(slot >= insertion_count)
{
// Report that page was not written. The host also pre-fills the whole
// destination array with DESTINATION_NONE, so this is defensive.
insertion_data_destination_indices[index] = DESTINATION_NONE;
return;
}
// Get a page to evict
let page_index = cache_evictor_lru_pages[index + cache_evictor_consumed_count];
let page_index = cache_evictor_lru_pages[slot + cache_evictor_consumed_count];
let page_timestamp = cache_evictor_timestamps[page_index];
if(page_timestamp >= new_timestamp - 1)
{
// Do not insert page
insertion_data_destination_indices[index] = 0xFFFFFFFF;
return;
insertion_data_destination_indices[index] = DESTINATION_NONE;
return;
}
atomicAdd(&pass_inserted_count, 1);
insertion_data_destination_indices[index] = page_index;
// Copy new location
structure_location_pages[page_index] = insertion_data_location_pages[index];
structure_location_pages[page_index] = insertion_data_location_pages[index];
// Copy new pointers
let new_pointers = insertion_info_to_pointer_page(insertion_data_information[index]);
structure_pointer_pages[page_index] = new_pointers;
structure_pointer_pages[page_index] = new_pointers;
// Mark page as dirty for invalidation
cache_evictor_timestamps[page_index] = new_timestamp;
// Set default depth
structure_depth_pages[page_index] = 0;
// Set default depth. `write_pointers` refines it for internal insertions.
structure_depth_pages[page_index] = 0;
// Copy attributes
for(var attribute_index = u32(0); attribute_index < ATTRIBUTE_COUNT; attribute_index ++)
@@ -116,7 +194,7 @@ fn insertion_info_to_pointer_page(info: InsertionInformation) -> PointerPage
var occupancy_low = u32(0);
var occupancy_high = u32(0);
for(var i = u32(0); i < CHILDREN_COUNT; i++)
for(var i = u32(0); i < CHILDREN_COUNT; i++)
{
let insert_info = info.children[i];
+48 -21
View File
@@ -3,34 +3,61 @@
@group(0) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
@group(0) @binding(2) var<storage, read_write> structure_depth_pages: array<u32>;
/// Group 1: Request buffer
@group(1) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
@group(1) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
@group(1) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
// Group 1: Cache insertion data
@group(1) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
@group(1) @binding(1) var<storage, read_write> insertion_data_information: array<InsertionInformation>;
@group(1) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
@group(1) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
@group(1) @binding(4) var<storage, read_write> insertion_data_parents: array<InsertionParent>;
@group(1) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
@group(1) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
@group(1) @binding(7) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
// Group 2: Cache insertion data
@group(2) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
@group(2) @binding(1) var<storage, read_write> insertion_data_information: array<InsertionInformation>;
@group(2) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
@group(2) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
@group(2) @binding(4) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
/// Links inserted pages into their parent, using only the insertion batch's own
/// parent description. No request buffer is involved, so a batch may be
/// produced on a different frame than the one that emitted the requests.
@compute
@workgroup_size(256, 1, 1)
fn write_pointers(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
if(index >= request_buffer_count || index >= insertion_data_page_count_buffer) { return; }
// The write pages pass establishes a one-to-one corresepondancy
// between requests and recycled pages
let meta_inf = request_buffer_meta[index];
let page_index = insertion_data_destination_indices[index];
if(page_index != 0xFFFFFFFF)
let entry_count = min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents));
if(index >= entry_count)
{
structure_pointer_pages[meta_inf.page_index].pointers[meta_inf.children_index]
= child_pointer_make_available(page_index);
structure_depth_pages[page_index] = meta_inf.depth + 1;
return;
}
let parent = insertion_data_parents[index];
if(parent.kind != INSERTION_PARENT_INTERNAL)
{
return;
}
let page_index = insertion_data_destination_indices[index];
if(page_index == DESTINATION_NONE)
{
return;
}
// The parent page may have been recycled while this insertion batch was in
// flight. Only link if it still describes the same node, and never link a
// page to itself.
if(parent.page_index >= PAGE_COUNT || parent.page_index == page_index)
{
return;
}
let location = structure_location_pages[parent.page_index];
if(location.structure_id != parent.structure_id ||
location.node_id != parent.node_id ||
location.producer_id != parent.producer_id)
{
return;
}
structure_pointer_pages[parent.page_index].pointers[parent.children_index]
= child_pointer_make_available(page_index);
structure_depth_pages[page_index] = parent.depth + 1;
}
@@ -8,6 +8,7 @@
/// Group 1: Cache request handler
@group(1) @binding(0) var<storage, read_write> request_handler_count: u32; // Request count
@group(1) @binding(1) var<storage, read_write> request_handler_requests: array<u32>;
@group(1) @binding(2) var<storage, read_write> request_handler_counts: array<u32>;
/// Group 3: Request buffer
@group(2) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
@@ -35,6 +36,8 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
request_information.structure_id = structure_location_pages[page_index].structure_id;
request_information.node_id = structure_location_pages[page_index].node_id;
request_information.children_index = request_location.children_index;
request_information.producer_id = structure_location_pages[page_index].producer_id;
request_information.demand = request_handler_counts[request_index];
// Fill out request meta information
var request_meta: RequestMeta;
+56 -8
View File
@@ -47,10 +47,14 @@ pub struct FixedStructureTable
common_ressources: CacheRessources<1>,
request_handler: CacheRequestHandler<1>,
/// Producer that owns the root structures stored by this table
producer_id: u32,
// To dispatch write request passes per request count
indirect_buffer: IndirectBuffer1D,
write_requests_pass: wgpu::ComputePipeline,
invalidation_pass: wgpu::ComputePipeline,
validation_pass: wgpu::ComputePipeline,
insertion_pass: wgpu::ComputePipeline,
// Raytrace
@@ -60,7 +64,12 @@ pub struct FixedStructureTable
impl FixedStructureTable
{
pub fn new(device: &wgpu::Device, size: usize, max_requests: usize) -> Self
pub fn new(
device: &wgpu::Device,
size: usize,
max_requests: usize,
producer_id: u32,
) -> Self
{
let pointer = CachePointer::new(Some(None));
let pointers = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
@@ -98,7 +107,7 @@ impl FixedStructureTable
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("FixedStructureTable::pipeline_layout"),
bind_group_layouts: &write_requests_bindings,
immediate_size: 0,
immediate_size: size_of::<u32>() as u32,
});
let write_requests_shader_module = device.create_shader_module(include_table_wgsl!(
@@ -153,7 +162,6 @@ impl FixedStructureTable
Some(&CacheInsertionData::<1>::create_bind_group_layout(
device, None,
)),
Some(&CacheRequestBuffer::create_bind_group_layout(device)),
];
let insertion_pipeline_layout =
@@ -175,15 +183,30 @@ impl FixedStructureTable
cache: None,
});
let validation_shader_module = device.create_shader_module(include_table_wgsl!(
"./shaders/fixed_table/validate_insertion.wgsl"
));
let validation_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("FixedStructureTable::validation_pass"),
layout: Some(&insertion_pipeline_layout),
module: &validation_shader_module,
entry_point: Some("validate_external"),
compilation_options: Default::default(),
cache: None,
});
Self {
size,
pointers,
pointers_bind_group,
common_ressources,
request_handler,
producer_id,
indirect_buffer: IndirectBuffer1D::new(device),
write_requests_pass,
invalidation_pass,
validation_pass,
insertion_pass,
raytrace_bind_group,
@@ -229,10 +252,10 @@ impl FixedStructureTable
timestamp_writes: None,
});
write_requests_pass.set_pipeline(&self.write_requests_pass);
write_requests_pass.set_bind_group(0, self.request_handler.bind_group(), &[]);
write_requests_pass.set_bind_group(1, request_buffer.bind_group(), &[]);
write_requests_pass.set_pipeline(&self.write_requests_pass);
write_requests_pass.set_immediates(0, bytemuck::bytes_of(&self.producer_id));
write_requests_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0);
}
@@ -249,7 +272,6 @@ impl FixedStructureTable
device: &wgpu::Device,
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
insertion: &CacheInsertionData<N>,
request: &CacheRequestBuffer,
) where
[(); N * N * N]:,
{
@@ -268,7 +290,6 @@ impl FixedStructureTable
insertion_pass.set_bind_group(0, &self.pointers_bind_group, &[]);
insertion_pass.set_bind_group(1, insertion.bind_group_no_attributes(), &[]);
insertion_pass.set_bind_group(2, request.bind_group(), &[]);
insertion_pass.set_pipeline(&self.insertion_pass);
insertion_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0);
@@ -296,8 +317,35 @@ impl FixedStructureTable
}
}
impl CacheInvalidable for FixedStructureTable
impl<const N: usize> CacheInvalidable<N> for FixedStructureTable
where
[(); N * N * N]:,
{
fn validate_insertion(
&mut self,
device: &wgpu::Device,
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
insertion: &CacheInsertionData<N>,
) {
let workgroup_count_buffer = self.indirect_buffer.workgroup_count(
device,
encoder,
insertion.page_count_buffer(),
256,
);
let mut validate_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("FixedStructureTable::validate_pass"),
timestamp_writes: None,
});
validate_pass.set_bind_group(0, &self.pointers_bind_group, &[]);
validate_pass.set_bind_group(1, insertion.bind_group_no_attributes(), &[]);
validate_pass.set_pipeline(&self.validation_pass);
validate_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0);
}
fn invalidate(
&mut self,
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,