diff --git a/AGENTS.md b/AGENTS.md
index 2e85abc..c015699 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -17,8 +17,9 @@ The durable system is:
- `src/voxel_cache/shaders/*.wgsl` — runtime-specialised cache shaders.
- `src/gpu/*` — radix sort, top-K, indirect dispatch, compaction.
- `shaders/*.slang` — render-side ray marching, compiled ahead of time.
-- `src/voxel_cache/tables.rs` + `src/terrain.rs` — structure tables and the
- toroidal world wrapper.
+- `src/voxel_cache/tables.rs` + `src/terrain.rs` — structure tables
+ (`FixedStructureTable`, the freelist-backed `DynamicStructureTable`, and the
+ shared `StructureTableCore`) and the toroidal world wrapper.
> **Temporary code:** `src/main.rs` and `src/producers.rs` are a playground/test
> harness built alongside the cache. They contain hardcoded parameters and
@@ -84,14 +85,16 @@ Do not change these casually; they are contracts between Rust, WGSL, and Slang.
10. **Eviction order:** timestamp-major (least recently used first), depth-minor
(deepest first). The depth pass runs descending and the timestamp pass runs
stable so equal timestamps keep the deepest-first order.
-11. **Identity is not placement.** `StructureId` is stable tree identity
- (monotonic per producer, never reused for another anchor). `StructureAnchor`
- is the opaque, table-defined content identity (toroidal table: world
- position + version). `TableSlot` is table-private placement and may change
- freely. Root identity is `(ProducerId, StructureId, StructureAnchor)`; the
- slot travels only as attachment metadata. Request keys, `LocationPage`,
- `RequestInformation`, and `InsertionParent` must not treat the slot as
- identity.
+11. **Identity is not placement.** `StructureAnchor` is the opaque, table-defined
+ content identity and the *only* structure identity (toroidal table: world
+ position + version). A table must never expose two live slots with the same
+ anchor, and an anchor must keep naming the same content if it leaves and
+ later re-enters; bump the version word when content generation changes for
+ the same coordinates. `TableSlot` is table-private placement and may change
+ freely. Root identity is `(ProducerId, StructureAnchor)`; the slot travels
+ only as attachment metadata (`RequestMeta`, `InsertionParent`). Request keys,
+ `LocationPage`, `RequestInformation`, `RequestMeta`, and `InsertionParent`
+ must not treat the slot as identity.
## Where to look for common tasks
@@ -103,6 +106,7 @@ Do not change these casually; they are contracts between Rust, WGSL, and Slang.
| Change eviction | `src/voxel_cache/eviction.rs`, `src/voxel_cache/shaders/eviction.wgsl`, `src/voxel_cache/shaders/insertion.wgsl` |
| Change insertion semantics | `src/voxel_cache.rs` (`insert`), `src/voxel_cache/pipelines.rs`, `src/voxel_cache/shaders/insertion.wgsl`, `write_pointers.wgsl` |
| Change world/chunk lookup | `src/voxel_cache/tables.rs`, `src/terrain.rs`, `shaders/toroidal_structure_table.slang` |
+| Add/change slot allocation or table growth | `src/voxel_cache/tables.rs` (`DynamicStructureTable`, `SlotAllocator`, `StructureTableCore`) |
| Change structure identity / anchors | `src/voxel_cache/schema.rs` (`StructureAnchor`, wire structs), `src/production/request_queue.rs`, `src/voxel_cache/tables.rs`, `src/voxel_cache/shaders/common.wgsl`, fixed-table shaders |
| Change ray marching/LOD | `shaders/voxel.slang`, `shaders/voxel_cache.slang`, `shaders/lod_policies.slang` |
| Add a producer | `src/producers.rs` (interface), `src/main.rs` (`fullfill_request`), [`docs/pipeline-and-producers.md`](./docs/pipeline-and-producers.md) |
diff --git a/Cargo.toml b/Cargo.toml
index 404128a..b658c97 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -13,7 +13,7 @@ egui_ltreeview = "0.9.0"
egui_plot = "0.37.0"
env_logger = "0.11.11"
fastapprox = "0.3.1"
-glam = "0.33.5"
+glam = { version = "0.33.5", features = ["bytemuck"] }
image = "0.25.10"
indicatif = "0.18.6"
itertools = "0.15.0"
diff --git a/docs/architecture.md b/docs/architecture.md
index 0b7b3bf..b2673a8 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -113,8 +113,8 @@ flowchart LR
Req --> Gather[gather_requests top-K + radix sort]
TReq --> TGather[table gather_requests]
- Gather --> RBuffer[(Request buffer structure_id, anchor, node_id, child)]
- TGather --> TRBuffer[(Table request buffer structure_id, anchor, slot)]
+ Gather --> RBuffer[(Request buffer anchor, node_id, child)]
+ TGather --> TRBuffer[(Table request buffer anchor, slot)]
RBuffer --> Host[Host fulfils requests]
TRBuffer --> Host
@@ -198,7 +198,7 @@ Consequences agents should keep in mind:
| `src/gpu/` | Radix sort, top-K, indirect dispatch, compaction helpers | Active infrastructure |
| `src/gpu_profiler/` | Timestamp profiling and memory accounting wrappers | Active infrastructure |
| `src/gi_pipeline.rs` (+ `sparse_set.rs`) | Planned GI pipeline using cache attribute sets | **Compiled but never instantiated** |
-| `src/production.rs` | Producer/structure IDs, `StructureAnchor` re-export, `VoxelProducer` trait | Compiled; durable contract |
+| `src/production.rs` | Producer ID, `StructureAnchor` re-export, `VoxelProducer` trait | Compiled; durable contract |
| `src/production/host_production.rs` | Rayon-based `HostRequestHandler` | Compiled; `fullfill` still a stub |
| `src/production/tree_locator.rs` | Compact N-tree locator encoding | Compiled; inactive |
| `src/production/request_queue.rs` | Bounded, deduplicating, priority-ordered request queue | Compiled, unit-tested; not yet on the live async path |
@@ -238,10 +238,10 @@ The toroidal table is a dense 3D grid of chunk root pointers. It wraps with
`imod`, so moving the camera across a chunk boundary invalidates the departing
slab and reuses those slots for incoming chunks. Identity is kept separate from
placement: each slot carries a table-defined `StructureAnchor` (world position
-plus a version word) and a stable `StructureId`. Anchors that stay in view keep
-their id while their slot may change; anchors that leave retire their id, which
-is never reused. In-flight root work carries the anchor and the latest slot, and
-the GPU rejects an insertion whose anchor/id no longer matches the slot, so queue
+plus a version word), and the anchor is the structure identity. Anchors that stay
+in view keep their identity while their slot may change; anchors that leave are
+retired. In-flight root work carries the anchor and the latest slot, and the GPU
+rejects an insertion whose anchor no longer matches the slot, so queue
invalidation is only a cancellation optimisation.
---
diff --git a/docs/pipeline-and-producers.md b/docs/pipeline-and-producers.md
index bffbf23..c4bde83 100644
--- a/docs/pipeline-and-producers.md
+++ b/docs/pipeline-and-producers.md
@@ -29,8 +29,8 @@ 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, anchor, node_id, child, producer, demand)
- T-->>H: table request buffer (structure_id, anchor, slot, 0, producer, demand)
+ C-->>H: request buffer (anchor, node_id, child, producer, demand)
+ T-->>H: table request buffer (anchor, slot, 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
@@ -51,19 +51,18 @@ response to frame N are first visible in frame N+1.
```rust
struct RequestInformation {
- structure_id: u32, // stable tree identity (per producer)
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
anchor: StructureAnchor, // opaque, table-defined content identity
- table_slot: u32, // external root placement, NO_TABLE_SLOT internally
}
struct RequestMeta {
page_index: u32, // parent page (internal) or 0xFFFFFFFF (external)
children_index: u32,
depth: u32, // parent depth
+ table_slot: u32, // external root placement, NO_TABLE_SLOT internally
}
```
@@ -71,22 +70,19 @@ struct RequestMeta {
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`, `structure_id` is the stable
- tree id, `anchor` is the table-defined content identity, and `table_slot` is
- the current placement.
+ 0xFFFFFFFF`, `node_id = 0`, `children_index = 0`, `anchor` is the table-defined
+ content identity, and `RequestMeta.table_slot` is the current placement.
- 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.
-- `structure_id`, `anchor`, and `table_slot` are three different things:
- - `StructureId` is stable tree identity, monotonic per producer, never reused
- for another anchor;
- - `StructureAnchor` is the table-defined content identity (for the toroidal
- table, world position plus a version word);
- - `table_slot` is table-private placement and may change while the id and
- anchor stay the same. It is deliberately not part of a request key.
+- `anchor` and `table_slot` are two different things:
+ - `StructureAnchor` is the table-defined content identity and the structure
+ identity (for the toroidal table, world position plus a version word);
+ - `table_slot` is table-private placement and may change while the anchor
+ stays the same. It is deliberately not part of a request key.
### 2.2 Response
@@ -99,7 +95,6 @@ struct InsertionInformation {
}
struct LocationPage {
- structure_id: u32,
node_id: u32, // locator of the node itself
producer_id: u32,
anchor: StructureAnchor,
@@ -110,7 +105,6 @@ struct InsertionParent {
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,
anchor: StructureAnchor,
@@ -123,11 +117,10 @@ Plus one attribute payload per entry (color and normal in the demo).
Before allocating pages, the cache validates every entry against the current
parent:
-- internal: the parent page must still have the same structure id, producer,
- locator, **and anchor**, and the child slot must still be
- `subdividable, unavailable`;
-- external: the named table slot must still carry the same anchor and structure
- id, and its pointer must still be `subdividable, unavailable`.
+- internal: the parent page must still have the same producer, locator, **and
+ anchor**, and the child slot must still be `subdividable, unavailable`;
+- external: the named table slot must still carry the same anchor, and its
+ pointer must still be `subdividable, unavailable`.
Valid entries are compacted into `valid_indices`/`valid_count`; only those
consume eviction pages. The cache fills `destination_indices[i]` with the page
@@ -199,7 +192,7 @@ The demo's `fullfill_request` (`src/main.rs`) does:
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(structure_id, producer_id, anchor, table_slot)`.
+ `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;
@@ -207,8 +200,7 @@ The demo's `fullfill_request` (`src/main.rs`) does:
- 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, structure_id, node_id, producer_id,
- anchor)`.
+ - emit `InsertionParent::internal(meta, node_id, producer_id, anchor)`.
The root/child test must use `RequestMeta.page_index`, not `node_id`: child 0
of the root also has `node_id = 0`.
@@ -340,7 +332,6 @@ Defines a more ambitious interface:
```rust
pub struct ProducerId(pub u32);
-pub struct StructureId(pub u32);
pub struct StructureLocator(pub u32);
pub use crate::voxel_cache::schema::StructureAnchor;
@@ -354,7 +345,6 @@ pub trait VoxelProducer {
fn produce(
&self,
producer_id: ProducerId,
- id: StructureId,
anchor: StructureAnchor,
locator: StructureLocator,
) -> (InsertionInformation, [Self::Output; N * N * N]);
@@ -369,22 +359,21 @@ Differences from the demo interface:
- The producer receives a `StructureLocator` rather than depth + coordinates,
pushing locator arithmetic into the producer.
- `anchor` is the content identity. A producer must derive world position from
- it (or from the id, which is stable) and never from a table slot.
+ it and never from a table slot.
### 6.1.1 Identity model
| Concept | Meaning |
|---|---|
| `ProducerId` | Which producer fulfils the request. |
-| `StructureId` | Stable identity of one tree instance. Monotonic per producer, never reused for a different anchor. |
-| `StructureAnchor` | Opaque, table-defined content identity. Two live slots must never share one anchor. |
+| `StructureAnchor` | Opaque, table-defined content identity and the only structure identity. Two live slots must never share one anchor. |
| `TableSlot` | Table-private placement. Recycled freely and never part of tree identity. |
-Root identity is `(producer, structure_id, anchor)`; child identity adds the
-parent locator and child index. The table slot travels only as attachment
-metadata. The toroidal table reuses a `StructureId` for an anchor that stays in
-view, allocates fresh ids for anchors entering the window, and retires ids for
-anchors that leave. Retired ids are never reassigned.
+Root identity is `(producer, anchor)`; child identity adds the parent locator and
+child index. The table slot travels only as attachment metadata. The toroidal
+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 `src/production/host_production.rs`
@@ -408,7 +397,6 @@ Key model:
```rust
RequestKey {
producer_id,
- structure_id,
anchor, // table-defined content identity
target: Root | Child { parent: StructureLocator, children_index },
}
@@ -430,15 +418,16 @@ Properties:
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.
-- `table_slot` is attachment metadata, not part of the key. It is refreshed on
- every re-emission, including while a job is in flight or ready, so a produced
- root can follow its anchor to a new slot.
-- `invalidate_structure(id)`, `invalidate_producer(id)`, and
- `invalidate_anchor(anchor)` remove matching 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/id/slot.
+- `table_slot` lives in `RequestMeta` as attachment metadata, not part of the
+ key. Because the whole `RequestMeta` is refreshed on every re-emission,
+ including while a job is in flight or ready, a produced root can follow its
+ anchor to a new slot.
+- `invalidate_producer(id)` and `invalidate_anchor(anchor)` remove matching
+ 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.
- `ReadyItem::insertion_parent()` builds the `InsertionParent` for the insertion
- batch from the key, the latest `RequestMeta`, and the latest `table_slot`.
+ batch from the key and the latest `RequestMeta` (which carries `table_slot`).
The queue is unit-tested without a GPU (`cargo test production::request_queue`).
@@ -494,10 +483,8 @@ Minimum viable path with the current demo interface:
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(structure_id, producer_id, anchor,
- table_slot)`;
- - internal: `InsertionParent::internal(meta, structure_id, node_id,
- producer_id, anchor)`.
+ - 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
@@ -512,7 +499,7 @@ A production-ready producer should additionally:
- handle `destination_indices == 0xFFFFFFFF` by retrying the request;
- implement filtering/mip generation for coarser levels so LOD stops do not
alias;
-- support multiple structures/producers per cache via IDs.
+- support multiple structures/producers per cache via `ProducerId` and anchors.
---
diff --git a/docs/shaders.md b/docs/shaders.md
index 1712b59..60ed995 100644
--- a/docs/shaders.md
+++ b/docs/shaders.md
@@ -407,8 +407,7 @@ group:
- group 0 — table pointers, or request handler;
- group 1 — request buffer, or insertion data;
-- group 2 — slot metadata: binding 0 `fixed_table_anchors`,
- binding 1 `fixed_table_structure_ids`.
+- group 2 — slot metadata: binding 0 `fixed_table_anchors`.
### 9.2 WGSL modules and entry points
@@ -421,9 +420,9 @@ group:
| `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 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, resolving the slot's current structure id and anchor. |
-| `fixed_table/validate_insertion.wgsl` | `validate_external` | Keep only root entries whose named slot still carries the same anchor/id and waits for a page. |
-| `fixed_table/insertion.wgsl` | `insertion` | Re-check anchor/id/slot, then point the table slot at the inserted root page. |
+| `fixed_table/write_requests.wgsl` | `write_requests` | Emit root requests for table slots, resolving the slot's current anchor. |
+| `fixed_table/validate_insertion.wgsl` | `validate_external` | Keep only root entries whose named slot still carries the same anchor and waits for a page. |
+| `fixed_table/insertion.wgsl` | `insertion` | Re-check anchor/slot, then point the table slot at the inserted root page. |
| `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. |
diff --git a/docs/voxel-cache.md b/docs/voxel-cache.md
index 5a8b7de..10957a8 100644
--- a/docs/voxel-cache.md
+++ b/docs/voxel-cache.md
@@ -68,7 +68,6 @@ For `N = 4`, a pointer page is `8 + 64*4 = 264` bytes.
```rust
struct LocationPage {
- structure_id: u32, // stable tree identity
node_id: u32, // application-defined locator within that structure
producer_id: u32, // producer that owns the node
anchor: StructureAnchor, // opaque, table-defined content identity
@@ -77,10 +76,10 @@ struct LocationPage {
The cache never interprets these values; they are copied from insertion data and
returned in requests so the producer knows which node is missing. In the demo,
-`node_id` is an `NTreeNodeLocator`, `structure_id` is a stable per-producer tree
-id, and `anchor` is the toroidal table's world position plus a version word.
-Child requests inherit the anchor from their parent page, so producers never need
-a host-side `StructureId -> anchor` directory. `LocationPage` is 28 bytes.
+`node_id` is an `NTreeNodeLocator` and `anchor` is the toroidal table's world
+position plus a version word. The anchor is the structure identity, so child
+requests inherit it from their parent page and producers never need a host-side
+identity directory. `LocationPage` is 24 bytes.
### 2.3 Depth page
@@ -271,12 +270,12 @@ pub trait CacheInvalidable {
```
`validate_insertion` runs before page allocation: the table checks that each
-external root's named slot still carries the same `anchor` and `structure_id`
-and is still `subdividable, unavailable`, then 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. The
-anchor/id check is what makes host queue invalidation a cancellation hint rather
-than a correctness requirement.
+external root's named slot still carries the same `anchor` and is still
+`subdividable, unavailable`, then 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. The anchor check
+is what makes host queue invalidation a cancellation hint rather than a
+correctness requirement.
### 4.3 Insertion data
@@ -310,7 +309,6 @@ struct InsertionParent {
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
anchor: StructureAnchor, // content identity of the structure
@@ -319,9 +317,9 @@ struct InsertionParent {
```
For an internal insertion, validation requires the parent page's
-`LocationPage` to match `structure_id`, `node_id`, `producer_id`, and `anchor`.
+`LocationPage` to match `node_id`, `producer_id`, and `anchor`.
For an external insertion, validation requires the slot indexed by `table_slot`
-to currently hold the parent's `structure_id` and `anchor`. `write_pointers.wgsl`
+to currently hold the parent's `anchor`. `write_pointers.wgsl`
repeats the internal check before linking, and the table insertion pass repeats
the external check after page allocation.
@@ -386,26 +384,27 @@ flowchart LR
```rust
struct RequestInformation {
- structure_id: u32, // from LocationPage (stable tree identity)
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
anchor: StructureAnchor, // from LocationPage (content identity)
- table_slot: u32, // 0xFFFFFFFF internally; external root placement
}
struct RequestMeta {
page_index: u32, // parent page, or 0xFFFFFFFF if external
children_index: u32,
depth: u32, // parent depth
+ table_slot: u32, // 0xFFFFFFFF internally; external root placement
}
```
`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. `anchor` lets producers stay stateless and lets the
-queue key roots by content identity instead of table placement.
+queue key roots by content identity instead of table placement. `table_slot`
+travels in `RequestMeta` because it is reinsertion/attachment information, not
+request identity.
The external-root marker is `RequestMeta.page_index == 0xFFFFFFFF`, **not**
`node_id == 0`. Both an external root and child 0 of the root carry
@@ -431,7 +430,7 @@ The callback is asynchronous by API, but the demo blocks on it with a
For an **internal** request:
-- `structure_id`, `node_id`, and `anchor` identify the **parent** node.
+- `node_id` and `anchor` identify the **parent** node.
- `children_index` identifies which child is missing.
- The producer must generate that child node and emit a `LocationPage` for the
child (typically `parent_locator.child(x, y, z)`) with the same anchor.
@@ -440,13 +439,12 @@ For an **internal** request:
For an **external** (structure-table) request:
-- `structure_id` is the stable tree id and `anchor` is the table-defined content
- identity; `table_slot` is where the table currently points.
+- `anchor` is the table-defined content identity; `table_slot` is where the
+ table currently points.
- `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` with `structure_id`, `producer_id`, `anchor`, and
- `table_slot`.
+ external `InsertionParent` with `producer_id`, `anchor`, and `table_slot`.
There is no output-order requirement. Each insertion is attached to its parent
by its own `InsertionParent`.
@@ -488,11 +486,10 @@ first, with deeper pages first among equal timestamps. See §7.
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`, anchor, and
- depth, and the requested child pointer must still be `subdividable,
- unavailable`.
+ still have the same `node_id`, `producer_id`, anchor, and depth, and the
+ requested child pointer must still be `subdividable, unavailable`.
- **External** (`fixed_table/validate_insertion.wgsl`): the named table slot
- must still carry the same `structure_id` and `anchor`, and must still be
+ must still carry the same `anchor`, and must still be
`subdividable, unavailable`.
Valid entries are compacted into `valid_indices` and counted in `valid_count`.
@@ -613,8 +610,8 @@ 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`,
- `producer_id = table producer`, `demand = slot counter`, and
+ `node_id = 0`, `children_index = 0`, `producer_id = table producer`,
+ `demand = slot counter`, `anchor = slot anchor`, and
`RequestMeta.page_index = 0xFFFFFFFF`.
- `validate_insertion`: `fixed_table/validate_insertion.wgsl` keeps only slots
that are still `subdividable, unavailable` and compacts their indices.
@@ -638,12 +635,11 @@ The table is dense: allocation is `slot_count * 4` bytes for pointers plus
and runs `terrain/shaders/toroidal_structure.wgsl`: any slot whose world
position changed is reset to `subdividable, unavailable`, so it will be
re-requested.
-- Slot identity is preserved across the move: anchors that stay in view keep
- their `StructureId` even if they change slot, anchors that enter get fresh
- monotonic ids, and anchors that leave retire their id (never reused).
- `reassign_slots` returns the retired ids so the host can cancel speculative
- queue work; correctness does not depend on it because the GPU validates
- `anchor`/`structure_id`/slot before linking a root.
+- Slot identity is preserved across the move: the anchor is the structure
+ identity, so anchors that stay in view keep it even if they change slot, and
+ anchors that leave are retired. `reassign_slots` returns the retired anchors
+ so the host can cancel speculative queue work; correctness does not depend on
+ it because the GPU validates `anchor`/slot before linking a root.
- `position_for_anchor(anchor)` decodes a table anchor back to an absolute
chunk coordinate.
- Everything else delegates to the fixed table.
@@ -652,6 +648,43 @@ The Slang module `toroidal_structure_table.slang` mirrors this indexing and walk
the block of chunks (`ToroidalStructureTableTracer`). `fixed_structure_table.slang`
is imported by `voxel.slang` but unused.
+### 8.3 `DynamicStructureTable`
+
+`src/voxel_cache/tables.rs`. A table whose slots are allocated and released at
+runtime. It shares the GPU scaffolding with `FixedStructureTable` through the
+private `StructureTableCore`; only the host-side slot management differs.
+
+- **Allocator.** A host-side LIFO free list. `allocate(queue, anchor) -> Option`
+ pops a slot and installs the anchor; `release(queue, slot) -> Option`
+ clears the pointer and pushes the slot back. Allocating an already-live anchor
+ is idempotent and returns its existing slot. `allocate` returns `None` when the
+ table is full.
+- **Stable slot indices.** A slot index never moves for the lifetime of an
+ allocation, so it is safe to store in a TLAS or any other long-lived handle.
+ This is why the table uses a free list rather than compaction.
+- **GPU liveness.** A free slot has pointer `0` (not subdividable), so the tracer
+ skips it and insertion/validation reject it. An allocated slot is initialised to
+ `subdividable, unavailable`, exactly like a fixed-table slot, so the normal
+ request/insertion path fills it. Released slots keep their stale anchor on the
+ GPU until reused; the empty pointer is what makes them inert.
+- **Stale requests.** `fixed_table/write_requests.wgsl`,
+ `validate_insertion.wgsl` and `insertion.wgsl` are reused unchanged. They already
+ re-check the slot anchor and pointer state, so a request produced before a
+ release/reuse cannot link the wrong root.
+- **Growth.** `reserve(device, queue, min_capacity)` grows by doubling and
+ `grow` doubles directly. Growth copies the pointer and anchor buffers into
+ larger buffers (zeroing the new tail), rebuilds the size-dependent request
+ handler, scratch resources and bind groups, and keeps the bind group layouts and
+ pipelines. It must happen between frames, and any bind group obtained before
+ growth must be re-fetched. `allocate_or_grow` is a convenience wrapper.
+- **Release semantics.** `release` unlinks the root; it does not free cache
+ pages. Those become unreachable and are reclaimed by normal LRU eviction. The
+ returned anchor can be passed to the request queue to cancel speculative work.
+- **Reuse responsibility.** Slots are reused immediately. The caller must not
+ reuse a slot while a GPU structure (e.g. a TLAS) still references it. A
+ deferred-free/retire queue can be layered on top later without changing the
+ allocator.
+
---
## 9. Bind groups
diff --git a/shaders/voxel.slang b/shaders/voxel.slang
index aa4331b..a27b73f 100644
--- a/shaders/voxel.slang
+++ b/shaders/voxel.slang
@@ -32,12 +32,9 @@ public struct VertexOutput
public float3 world_position;
[vk::location(1)]
- public nointerpolation uint32_t structure_id;
-
- [vk::location(2)]
public float3 cam_position;
- [vk::location(3)]
+ [vk::location(2)]
public float3 chunk_position;
}
diff --git a/src/main.rs b/src/main.rs
index ac0e5b5..45af6b0 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,12 +1,14 @@
#![feature(generic_const_exprs)]
#![feature(float_algebraic)]
+use std::arch::x86_64;
use std::marker::PhantomData;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU32;
use std::sync::mpsc::Sender;
use std::thread::Thread;
+use std::time::Instant;
use bytemuck::Pod;
use bytemuck::Zeroable;
@@ -16,9 +18,12 @@ use egui::Color32;
use egui::mutex::Mutex;
use egui_plot::BarChart;
use glam::Mat4;
+use glam::Quat;
use glam::Vec3;
use glam::Vec4;
use itertools::Itertools;
+use rand::random_bool;
+use rand::random_range;
use rayon::iter::IntoParallelRefIterator;
use rayon::iter::ParallelIterator;
use wgpu::BindGroupLayout;
@@ -49,6 +54,10 @@ use winit::event_loop::OwnedDisplayHandle;
use winit::window::Window;
use winit::window::WindowId;
+use crate::bvh::BvhObject;
+use crate::bvh::BvhStructureTable;
+use crate::bvh::aabb::Aabb;
+use crate::bvh::debug::BvhDebugPipeline;
use crate::camera::Camera;
use crate::egui_renderer::EguiRenderer;
use crate::gpu_profiler::Frame;
@@ -56,21 +65,31 @@ use crate::gpu_profiler::Profile;
use crate::gpu_profiler::ProfilingEncoder;
use crate::producers::ChunkedProducer;
use crate::producers::SdfGenerator;
+use crate::production::ProducerId;
+use crate::production::StructureAnchor;
+use crate::production::StructureLocator;
use crate::production::request_queue::FrameId;
use crate::production::request_queue::IncomingRequest;
use crate::production::request_queue::QueueConfig;
use crate::production::request_queue::RequestKey;
use crate::production::request_queue::RequestQueue;
use crate::production::request_queue::RequestTarget;
-use crate::sparse_tree::NTreeNodeLocator;
+use crate::production::tree_locator::TreeLocator;
+use crate::sparse_tree::Color;
+use crate::sparse_tree::NTree;
+use crate::sparse_tree::NTreeNode;
+use crate::sparse_tree::load_ply;
use crate::terrain::ToroidalStructureTable;
use crate::voxel_cache::VoxelCache;
use crate::voxel_cache::VoxelCacheInsertion;
use crate::voxel_cache::insertion::CacheInsertionData;
use crate::voxel_cache::requests::CacheRequestBuffer;
+use crate::voxel_cache::schema::ChildInformation;
use crate::voxel_cache::schema::InsertionInformation;
use crate::voxel_cache::schema::LocationPage;
+use crate::voxel_cache::tables::FixedStructureTable;
+pub mod bvh;
mod camera;
mod egui_renderer;
mod gi_pipeline;
@@ -81,7 +100,6 @@ mod production;
mod sparse_tree;
mod terrain;
mod voxel_cache;
-//
enum DisplayTexture
{
@@ -134,8 +152,6 @@ struct State
structure_table: Arc>,
structure_table_request_buffer: Arc,
structure_table_cache_insertion: Arc>,
- instance_buffer: Buffer,
- instance_count: usize,
usage_vec: Arc>>,
rm_time: Arc>,
frame_time: Arc>,
@@ -153,6 +169,9 @@ struct State
// Producers workers
wakeup: Sender<()>,
+
+ bvh: BvhStructureTable,
+ bvh_debug: BvhDebugPipeline,
}
pub unsafe fn as_raw_bytes(slice: &[T]) -> &[u8]
@@ -358,6 +377,19 @@ impl State
panic!();
*/
+ // Load dragon ply
+ let tree: NTree<4> = load_ply("dragon.txt");
+ // let mut arrays = vec![Color(0., 0., 0., 0.); 256 * 256 * 256];
+ // for ((x, y), z) in (0..256).cartesian_product(0..256).cartesian_product(0..256)
+ // {
+ // if Vec3::new(x as f32, y as f32, z as f32).length() < 128.
+ // {
+ // let index = x + y * 256 + z * 256 * 256;
+ // //arrays[index] = Color(1., 1., 1., 1.);
+ // }
+ // }
+ // let tree: NTree<4> = NTree::from_array(&arrays, 4);
+
let size = window.inner_size();
let surface = instance.create_surface(window.clone()).unwrap();
@@ -413,11 +445,12 @@ impl State
let total_chunk_count = terrain_height * terrain_width * terrain_alt;
let structure_table_request_buffer = CacheRequestBuffer::new(&device, 128);
- //let structure_table = FixedStructureTable::new(
- // &device,
- // total_chunk_count,
- // structure_table_request_buffer.max_requests,
- //);
+ // let structure_table = FixedStructureTable::new(
+ // &device,
+ // total_chunk_count,
+ // structure_table_request_buffer.max_requests,
+ // 0,
+ // );
let structure_table = ToroidalStructureTable::new(
&device,
(terrain_width, terrain_alt, terrain_height),
@@ -490,6 +523,48 @@ impl State
// )
// };
+ let mut bvh = BvhStructureTable::new(&device, 128, 128);
+ let extent = Aabb::new(-10. * Vec3::ONE, 10. * Vec3::ONE);
+ for _ in 0..200
+ {
+ let transform = Mat4::from_rotation_translation(
+ Quat::from_euler(
+ glam::EulerRot::XYZ,
+ random_range(-3.1..3.1),
+ random_range(-3.1..3.1),
+ random_range(-3.1..3.1),
+ ),
+ Vec3::new(
+ random_range(extent.min().x..extent.max().x),
+ random_range(extent.min().y..extent.max().y),
+ random_range(extent.min().z..extent.max().z),
+ ),
+ );
+
+ bvh.add(
+ &device,
+ &queue,
+ BvhObject {
+ anchor: StructureAnchor::zeroed(),
+ producer_id: ProducerId(0),
+ transform,
+ bounding_box: Aabb::CHUNK,
+ },
+ );
+ }
+
+ let now = Instant::now();
+ bvh.rebuild(&device, &queue);
+ let time = Instant::now() - now;
+
+ println!("Bvh build time : {}ms", time.as_millis());
+
+ let bvh_debug = BvhDebugPipeline::new(
+ &device,
+ surface_format.add_srgb_suffix(),
+ wgpu::TextureFormat::Depth24PlusStencil8,
+ );
+
let shader_module = unsafe {
device.create_shader_module_passthrough({
wgpu::ShaderModuleDescriptorPassthrough {
@@ -706,11 +781,12 @@ impl State
let finshed = work
.par_iter()
.map(|work_item| {
- let d = fullfill_request(
- &terrain_generator,
- &work_item.key,
- &structure_table_1,
- );
+ // let d = fullfill_request(
+ // &terrain_generator,
+ // &work_item.key,
+ // &structure_table_1,
+ // );
+ let d = fullfill_request_tree(&tree, &work_item.key);
(
work_item,
VoxelPayload {
@@ -781,8 +857,6 @@ impl State
insertion_debounce: false,
camera: Default::default(),
- instance_buffer,
- instance_count,
rm_time: Arc::new(Mutex::new(0.)),
frame_time: Arc::new(Mutex::new(0.)),
terrain_width,
@@ -792,6 +866,8 @@ impl State
insert_profile: Arc::new(Mutex::new(Profile::default())),
cursor_grabed: true,
wakeup: wakeup_tx,
+ bvh,
+ bvh_debug,
};
// Configure surface for the first time
@@ -1103,9 +1179,9 @@ impl State
// Cancellation is only an optimisation: stale insertions are
// rejected by the GPU because they no longer match the slot.
let mut request_queue = self.request_queue.lock();
- for structure in retired
+ for anchor in retired
{
- request_queue.invalidate_structure(structure);
+ request_queue.invalidate_anchor(anchor);
}
}
@@ -1147,6 +1223,7 @@ impl State
chunk_height: self.terrain_height as u32,
chunk_alt: self.terrain_alt as u32,
+ //table_base_slot: Default::default(),
table_base_slot,
}];
renderpass.set_immediates(0, unsafe { as_raw_bytes(&imm) });
@@ -1177,6 +1254,19 @@ impl State
self.target_blitter
.copy(&self.device, &mut encoder, target_view, &texture_view);
+ self.bvh_debug.render(
+ &self.device,
+ &self.queue,
+ &mut encoder,
+ &texture_view,
+ &self.depth_buffer.1,
+ self.camera.view_proj(),
+ self.bvh.bvh_nodes(),
+ self.bvh.bvh_objects(),
+ self.bvh.node_count(),
+ 2,
+ );
+
// ~~ EGUI Render pass ~~
{
self.egui_renderer.begin_frame(&self.window);
@@ -1747,6 +1837,108 @@ pub struct ChunkImmediate
frame_timestamp: u32,
}
+fn fullfill_request_tree(
+ tree: &NTree,
+ request: &RequestKey,
+) -> (
+ [u32; N * N * N],
+ [[f32; 3]; N * N * N],
+ InsertionInformation,
+ LocationPage,
+)
+{
+ match request.target
+ {
+ RequestTarget::Root =>
+ {
+ let root = tree
+ .get_by_loc(TreeLocator::root())
+ .expect("Root must exist");
+
+ if !root.subdivided
+ {
+ // Produce little node of constant
+ (
+ [root.color.as_packed_u32(); N * N * N],
+ //[sparse_tree::Color(1., 1., 1., 1.).as_packed_u32(); N * N * N],
+ [Default::default(); N * N * N],
+ InsertionInformation {
+ children: [ChildInformation::new(false, root.color.3 != 0.); N * N * N],
+ },
+ LocationPage {
+ node_id: StructureLocator::from(TreeLocator::::root()).0,
+ producer_id: 0,
+ anchor: StructureAnchor::zeroed(),
+ },
+ )
+ }
+ else
+ {
+ let mut colors = vec![];
+ let mut children = vec![];
+ TreeLocator::root().children().for_each(|loc| {
+ let node = tree.get_by_loc(loc).unwrap();
+ colors.push(node.color.as_packed_u32());
+ children.push(ChildInformation::new(
+ node.subdivided,
+ node.subdivided || node.color.3 != 0.,
+ ));
+ });
+
+ (
+ std::array::from_fn(|i| colors[i]),
+ [Default::default(); N * N * N],
+ InsertionInformation {
+ children: std::array::from_fn(|i| children[i]),
+ },
+ LocationPage {
+ node_id: StructureLocator::from(TreeLocator::::root()).0,
+ producer_id: 0,
+ anchor: StructureAnchor::zeroed(),
+ },
+ )
+ }
+ }
+ RequestTarget::Child {
+ parent,
+ children_index,
+ } =>
+ {
+ let child_z = children_index / (4 * 4);
+ let child_y = (children_index % (4 * 4)) / 4;
+ let child_x = children_index % 4;
+
+ let loc: TreeLocator = parent.into();
+ let loc = loc.child(child_x, child_y, child_z);
+
+ let mut colors = vec![];
+ let mut children = vec![];
+ loc.children().for_each(|child_loc| {
+ let node = tree.get_by_loc(child_loc).unwrap();
+ colors.push(node.color.as_packed_u32());
+ children.push(ChildInformation::new(
+ node.subdivided,
+ node.subdivided || node.color.3 != 0.,
+ ));
+ });
+
+ (
+ std::array::from_fn(|i| colors[i]),
+ [Default::default(); N * N * N],
+ InsertionInformation {
+ children: std::array::from_fn(|i| children[i]),
+ },
+ LocationPage {
+ node_id: StructureLocator::from(loc).0,
+ producer_id: 0,
+ anchor: StructureAnchor::zeroed(),
+ },
+ )
+ }
+ }
+}
+
+/*
fn fullfill_request(
generator: &dyn ChunkedProducer,
request: &RequestKey,
@@ -1789,9 +1981,9 @@ where
// 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));
+ let locator: StructureLocator = TreeLocator::::root().into();
location = LocationPage {
- structure_id: request.structure_id.0,
- node_id: NTreeNodeLocator::<4>::root().as_usize() as u32,
+ node_id: locator.0,
producer_id: request.producer_id.0,
anchor,
};
@@ -1807,7 +1999,7 @@ where
unreachable!();
};
// Figure out depth of request
- let locator = NTreeNodeLocator::<4>::from_usize(parent.0 as usize);
+ let locator: TreeLocator<4> = (*parent).into();
let depth = locator.depth();
//let (x, y, z) = locator.node_location();
@@ -1815,15 +2007,21 @@ where
let child_y = (children_index % (4 * 4)) / 4;
let child_x = children_index % 4;
- let child_locator = locator.child(child_x as usize, child_y as usize, child_z as usize);
+ let child_locator = locator.child(child_x, child_y, child_z);
let (nx, ny, nz) = child_locator.node_location();
- node = generator.produce_node(depth + 1, nx, ny, nz, (chunk_x, chunk_y, chunk_z));
+ node = generator.produce_node(
+ (depth + 1) as usize,
+ nx as usize,
+ ny as usize,
+ nz as usize,
+ (chunk_x, chunk_y, chunk_z),
+ );
+ let st_loc: StructureLocator = child_locator.into();
location = LocationPage {
- structure_id: request.structure_id.0,
- node_id: child_locator.as_usize() as u32,
+ node_id: st_loc.0 as u32,
producer_id: request.producer_id.0,
anchor,
};
@@ -1838,3 +2036,4 @@ where
location,
)
}
+*/
diff --git a/src/production.rs b/src/production.rs
index e0c2160..bd82e78 100644
--- a/src/production.rs
+++ b/src/production.rs
@@ -22,14 +22,6 @@ pub mod request_queue;
#[repr(transparent)]
pub struct ProducerId(pub u32);
-/// A producer can manage differnet independent voxel structure, with their own roots.
-/// As such a producer can tag, to its discretion, its own structure with an Id.
-///
-/// All node of a same tree thus share the same structure Id
-#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, 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, Hash, Debug, Zeroable, Pod)]
@@ -54,16 +46,15 @@ where
/// The voxel data produced by this producer
type Output: VoxelAttributes;
- /// A pure function that can produce a voxel node based on the owner produer id, requesting structure, and the
- /// requesting location within the structure.
+ /// A pure function that can produce a voxel node based on the owner producer
+ /// id, requesting structure, and the requesting location within the structure.
///
/// `anchor` is the table-defined content identity of the structure. Producers
- /// must derive world position/content from it rather than from `id` or any
- /// table slot: slots are placement and may change while `id` stays stable.
+ /// must derive world position/content from it rather than from any table
+ /// slot: slots are placement and may change while the anchor stays stable.
fn produce(
&self,
producer_id: ProducerId,
- id: StructureId,
anchor: StructureAnchor,
locator: StructureLocator,
) -> (InsertionInformation, [Self::Output; N * N * N]);
diff --git a/src/production/host_production.rs b/src/production/host_production.rs
index 5f9978e..c96d313 100644
--- a/src/production/host_production.rs
+++ b/src/production/host_production.rs
@@ -57,7 +57,6 @@ where
.for_each(|((request, dest_information), dest_attributes)| {
let (info, attributes) = self.producer.produce(
super::ProducerId(0),
- super::StructureId(request.structure_id),
request.anchor,
super::StructureLocator(request.node_id),
);
diff --git a/src/production/request_queue.rs b/src/production/request_queue.rs
index 7ac2617..059351d 100644
--- a/src/production/request_queue.rs
+++ b/src/production/request_queue.rs
@@ -3,11 +3,9 @@ use std::collections::BTreeSet;
use std::collections::HashMap;
use crate::production::ProducerId;
-use crate::production::StructureId;
use crate::production::StructureLocator;
use crate::voxel_cache::schema::InsertionParent;
use crate::voxel_cache::schema::NO_PARENT_PAGE;
-use crate::voxel_cache::schema::NO_TABLE_SLOT;
use crate::voxel_cache::schema::RequestInformation;
use crate::voxel_cache::schema::RequestMeta;
use crate::voxel_cache::schema::StructureAnchor;
@@ -44,22 +42,16 @@ pub enum RequestTarget
pub struct RequestKey
{
pub producer_id: ProducerId,
- pub structure_id: StructureId,
pub anchor: StructureAnchor,
pub target: RequestTarget,
}
impl RequestKey
{
- pub fn root(
- producer_id: ProducerId,
- structure_id: StructureId,
- anchor: StructureAnchor,
- ) -> Self
+ pub fn root(producer_id: ProducerId, anchor: StructureAnchor) -> Self
{
Self {
producer_id,
- structure_id,
anchor,
target: RequestTarget::Root,
}
@@ -67,7 +59,6 @@ impl RequestKey
pub fn child(
producer_id: ProducerId,
- structure_id: StructureId,
anchor: StructureAnchor,
parent: StructureLocator,
children_index: u32,
@@ -75,7 +66,6 @@ impl RequestKey
{
Self {
producer_id,
- structure_id,
anchor,
target: RequestTarget::Child {
parent,
@@ -156,12 +146,9 @@ pub struct IncomingRequest
pub key: RequestKey,
pub priority: RequestPriority,
- /// Parent page information captured at the latest emission.
+ /// Parent/reinsertion information captured at the latest emission,
+ /// including the latest table slot for an external root.
pub meta: RequestMeta,
-
- /// Latest table slot reported for an external root; [`NO_TABLE_SLOT`]
- /// otherwise. Refreshed on every re-emission.
- pub table_slot: u32,
}
impl IncomingRequest
@@ -172,13 +159,12 @@ impl IncomingRequest
pub fn from_wire(request: &RequestInformation, meta: &RequestMeta) -> Self
{
let producer_id = ProducerId(request.producer_id);
- let structure_id = StructureId(request.structure_id);
let anchor = request.anchor;
let (key, priority) = if meta.page_index == NO_PARENT_PAGE
{
(
- RequestKey::root(producer_id, structure_id, anchor),
+ RequestKey::root(producer_id, anchor),
RequestPriority::root(request.demand),
)
}
@@ -187,7 +173,6 @@ impl IncomingRequest
(
RequestKey::child(
producer_id,
- structure_id,
anchor,
StructureLocator(request.node_id),
request.children_index,
@@ -196,20 +181,10 @@ impl IncomingRequest
)
};
- let table_slot = if key.is_root()
- {
- request.table_slot
- }
- else
- {
- NO_TABLE_SLOT
- };
-
Self {
key,
priority,
meta: *meta,
- table_slot,
}
}
}
@@ -238,7 +213,6 @@ pub struct ReadyItem
{
pub key: RequestKey,
pub meta: RequestMeta,
- pub table_slot: u32,
pub payload: T,
}
@@ -250,15 +224,11 @@ impl ReadyItem
{
match self.key.target
{
- RequestTarget::Root =>
- {
- InsertionParent::external(
- self.key.structure_id.0,
- self.key.producer_id.0,
- self.key.anchor,
- self.table_slot,
- )
- }
+ RequestTarget::Root => InsertionParent::external(
+ self.key.producer_id.0,
+ self.key.anchor,
+ self.meta.table_slot,
+ ),
RequestTarget::Child {
parent,
children_index,
@@ -271,13 +241,7 @@ impl ReadyItem
children_index,
..self.meta
};
- InsertionParent::internal(
- &meta,
- self.key.structure_id.0,
- parent.0,
- self.key.producer_id.0,
- self.key.anchor,
- )
+ InsertionParent::internal(&meta, parent.0, self.key.producer_id.0, self.key.anchor)
}
}
}
@@ -317,9 +281,9 @@ impl Default for QueueConfig
{
Self {
max_queued: 4096,
- max_in_flight: 4,
+ max_in_flight: 64,
max_ready: 1024,
- stale_after: 8,
+ stale_after: 2,
max_attempts: 3,
}
}
@@ -356,10 +320,9 @@ struct Job
priority: RequestPriority,
first_seen: FrameId,
last_seen: FrameId,
+ /// Parent/reinsertion information, including the latest table slot.
+ /// Refreshed even while the job is in flight or ready.
meta: RequestMeta,
- /// Latest slot reported for an external root. Refreshed even while the job
- /// is in flight or ready so a produced root can follow a slot move.
- table_slot: u32,
generation: u64,
attempt: u32,
payload: Option,
@@ -480,7 +443,6 @@ impl RequestQueue
job.priority = request.priority;
job.meta = request.meta;
- job.table_slot = request.table_slot;
job.last_seen = frame;
match job.state
@@ -537,7 +499,6 @@ impl RequestQueue
first_seen: frame,
last_seen: frame,
meta: request.meta,
- table_slot: request.table_slot,
generation,
attempt: 0,
payload: None,
@@ -722,7 +683,6 @@ impl RequestQueue
result.push(ReadyItem {
key: job.key,
meta: job.meta,
- table_slot: job.table_slot,
payload,
});
}
@@ -731,16 +691,6 @@ impl RequestQueue
result
}
- /// Removes every job belonging to a structure.
- ///
- /// Correctness is enforced on the GPU by validating the insertion against
- /// the current anchor/id/slot. Invalidation only cancels speculative work
- /// and avoids wasted production.
- pub fn invalidate_structure(&mut self, structure: StructureId) -> usize
- {
- self.invalidate_matching(|key| key.structure_id == structure)
- }
-
/// Removes every job belonging to a producer.
pub fn invalidate_producer(&mut self, producer: ProducerId) -> usize
{
@@ -863,8 +813,9 @@ mod tests
{
use super::*;
+ use crate::voxel_cache::schema::NO_TABLE_SLOT;
+
const PRODUCER: ProducerId = ProducerId(0);
- const STRUCTURE: StructureId = StructureId(1);
const ANCHOR: StructureAnchor = StructureAnchor::ZERO;
fn meta(page: u32, child: u32, depth: u32) -> RequestMeta
@@ -873,18 +824,13 @@ mod tests
page_index: page,
children_index: child,
depth,
+ table_slot: NO_TABLE_SLOT,
}
}
fn child_key(parent: u32, child: u32) -> RequestKey
{
- RequestKey::child(
- PRODUCER,
- STRUCTURE,
- ANCHOR,
- StructureLocator(parent),
- child,
- )
+ RequestKey::child(PRODUCER, ANCHOR, StructureLocator(parent), child)
}
fn incoming(key: RequestKey, priority: RequestPriority) -> IncomingRequest
@@ -893,13 +839,11 @@ mod tests
key,
priority,
meta: meta(0, 0, 0),
- table_slot: NO_TABLE_SLOT,
}
}
#[allow(clippy::too_many_arguments)]
fn wire(
- structure: u32,
node: u32,
child: u32,
producer: u32,
@@ -912,18 +856,17 @@ mod tests
{
(
RequestInformation {
- structure_id: structure,
node_id: node,
children_index: child,
producer_id: producer,
demand,
anchor,
- table_slot,
},
RequestMeta {
page_index: parent_page,
children_index: child,
depth,
+ table_slot,
},
)
}
@@ -943,7 +886,7 @@ mod tests
fn root_and_root_child_zero_do_not_collide()
{
let mut q = queue(8, 1, 8);
- let root = RequestKey::root(PRODUCER, STRUCTURE, ANCHOR);
+ let root = RequestKey::root(PRODUCER, ANCHOR);
let child = child_key(0, 0);
q.ingest(
@@ -962,29 +905,18 @@ mod tests
#[test]
fn from_wire_distinguishes_root_from_root_child_zero()
{
- let (root_info, root_meta) = wire(
- STRUCTURE.0,
- 0,
- 0,
- PRODUCER.0,
- 7,
- u32::MAX,
- u32::MAX,
- ANCHOR,
- 3,
- );
- let (child_info, child_meta) =
- wire(STRUCTURE.0, 0, 0, PRODUCER.0, 7, 3, 0, ANCHOR, NO_TABLE_SLOT);
+ let (root_info, root_meta) = wire(0, 0, PRODUCER.0, 7, u32::MAX, u32::MAX, ANCHOR, 3);
+ let (child_info, child_meta) = wire(0, 0, PRODUCER.0, 7, 3, 0, ANCHOR, NO_TABLE_SLOT);
let root = IncomingRequest::from_wire(&root_info, &root_meta);
let child = IncomingRequest::from_wire(&child_info, &child_meta);
- assert_eq!(root.key, RequestKey::root(PRODUCER, STRUCTURE, ANCHOR));
- assert_eq!(root.table_slot, 3);
- assert_eq!(child.table_slot, NO_TABLE_SLOT);
+ assert_eq!(root.key, RequestKey::root(PRODUCER, ANCHOR));
+ assert_eq!(root.meta.table_slot, 3);
+ assert_eq!(child.meta.table_slot, NO_TABLE_SLOT);
assert_eq!(
child.key,
- RequestKey::child(PRODUCER, STRUCTURE, ANCHOR, StructureLocator(0), 0)
+ RequestKey::child(PRODUCER, ANCHOR, StructureLocator(0), 0)
);
assert_ne!(root.key, child.key);
}
@@ -992,17 +924,7 @@ mod tests
#[test]
fn from_wire_carries_demand_and_depth_into_priority()
{
- let (info, meta) = wire(
- STRUCTURE.0,
- 5,
- 2,
- PRODUCER.0,
- 11,
- 9,
- 3,
- ANCHOR,
- NO_TABLE_SLOT,
- );
+ let (info, meta) = wire(5, 2, PRODUCER.0, 11, 9, 3, ANCHOR, NO_TABLE_SLOT);
let request = IncomingRequest::from_wire(&info, &meta);
assert_eq!(request.priority, RequestPriority::child(11, 3));
@@ -1014,7 +936,7 @@ mod tests
fn ready_item_builds_stateless_insertion_parent()
{
let mut q = queue(8, 2, 8);
- let root = RequestKey::root(PRODUCER, STRUCTURE, ANCHOR);
+ let root = RequestKey::root(PRODUCER, ANCHOR);
let child = child_key(4, 2);
q.ingest(
@@ -1023,14 +945,15 @@ mod tests
IncomingRequest {
key: root,
priority: RequestPriority::root(1),
- meta: meta(0, 0, 0),
- table_slot: 5,
+ meta: RequestMeta {
+ table_slot: 5,
+ ..meta(0, 0, 0)
+ },
},
IncomingRequest {
key: child,
priority: RequestPriority::child(1, 3),
meta: meta(7, 2, 3),
- table_slot: NO_TABLE_SLOT,
},
],
);
@@ -1046,7 +969,6 @@ mod tests
let external = ready[0].insertion_parent();
assert!(external.is_external());
assert_eq!(external.page_index, NO_PARENT_PAGE);
- assert_eq!(external.structure_id, STRUCTURE.0);
assert_eq!(external.producer_id, PRODUCER.0);
assert_eq!(external.anchor, ANCHOR);
assert_eq!(external.table_slot, 5);
@@ -1057,7 +979,6 @@ mod tests
assert_eq!(internal.children_index, 2);
assert_eq!(internal.depth, 3);
assert_eq!(internal.node_id, 4);
- assert_eq!(internal.structure_id, STRUCTURE.0);
assert_eq!(internal.anchor, ANCHOR);
assert_eq!(internal.table_slot, NO_TABLE_SLOT);
}
@@ -1074,7 +995,6 @@ mod tests
key: child,
priority: RequestPriority::child(1, 3),
meta: meta(7, 5, 3),
- table_slot: NO_TABLE_SLOT,
}],
);
@@ -1092,8 +1012,8 @@ mod tests
fn producer_id_disambiguates_identical_structure_keys()
{
let mut q = queue(8, 1, 8);
- let a = RequestKey::child(ProducerId(0), STRUCTURE, ANCHOR, StructureLocator(7), 3);
- let b = RequestKey::child(ProducerId(1), STRUCTURE, ANCHOR, StructureLocator(7), 3);
+ let a = RequestKey::child(ProducerId(0), ANCHOR, StructureLocator(7), 3);
+ let b = RequestKey::child(ProducerId(1), ANCHOR, StructureLocator(7), 3);
q.ingest(
0,
@@ -1145,7 +1065,7 @@ mod tests
fn roots_outrank_children()
{
let mut q = queue(8, 8, 8);
- let root = RequestKey::root(PRODUCER, STRUCTURE, ANCHOR);
+ let root = RequestKey::root(PRODUCER, ANCHOR);
let child = child_key(0, 0);
q.ingest(
@@ -1411,7 +1331,7 @@ mod tests
let item = q.pop().unwrap();
q.complete(item, 1);
- assert_eq!(q.invalidate_structure(STRUCTURE), 2);
+ assert_eq!(q.invalidate_anchor(ANCHOR), 2);
assert!(q.is_empty());
assert_eq!(q.in_flight_len(), 0);
assert_eq!(q.ready_len(), 0);
@@ -1421,8 +1341,8 @@ mod tests
fn invalidate_producer_only_removes_that_producer()
{
let mut q = queue(8, 8, 8);
- let a = RequestKey::child(ProducerId(0), STRUCTURE, ANCHOR, StructureLocator(1), 0);
- let b = RequestKey::child(ProducerId(1), STRUCTURE, ANCHOR, StructureLocator(1), 0);
+ let a = RequestKey::child(ProducerId(0), ANCHOR, StructureLocator(1), 0);
+ let b = RequestKey::child(ProducerId(1), ANCHOR, StructureLocator(1), 0);
q.ingest(
0,
@@ -1449,10 +1369,12 @@ mod tests
fn root_incoming(slot: u32) -> IncomingRequest
{
IncomingRequest {
- key: RequestKey::root(PRODUCER, STRUCTURE, ANCHOR),
+ key: RequestKey::root(PRODUCER, ANCHOR),
priority: RequestPriority::root(1),
- meta: meta(NO_PARENT_PAGE, 0, NO_PARENT_PAGE),
- table_slot: slot,
+ meta: RequestMeta {
+ table_slot: slot,
+ ..meta(NO_PARENT_PAGE, 0, NO_PARENT_PAGE)
+ },
}
}
@@ -1475,7 +1397,6 @@ mod tests
assert!(parent.is_external());
assert_eq!(parent.table_slot, 2);
assert_eq!(parent.anchor, ANCHOR);
- assert_eq!(parent.structure_id, STRUCTURE.0);
}
#[test]
@@ -1486,25 +1407,23 @@ mod tests
q.ingest(0, [root_incoming(1)]);
q.ingest(1, [root_incoming(9)]);
- // Same producer/id/anchor: one job, refreshed in place, not duplicated.
+ // Same producer/anchor: one job, refreshed in place, not duplicated.
assert_eq!(q.len(), 1);
- assert!(q.contains(&RequestKey::root(PRODUCER, STRUCTURE, ANCHOR)));
+ assert!(q.contains(&RequestKey::root(PRODUCER, ANCHOR)));
let item = q.pop().unwrap();
q.complete(item, 1);
let ready = q.drain_ready_matching(1, 8, |_| true);
- assert_eq!(ready[0].table_slot, 9);
+ assert_eq!(ready[0].meta.table_slot, 9);
}
#[test]
- fn different_anchors_with_same_structure_are_distinct()
+ fn different_anchors_are_distinct()
{
- // A correct table never does this, but the queue must not merge them.
let mut q = queue(8, 1, 8);
- let a = RequestKey::child(PRODUCER, STRUCTURE, ANCHOR, StructureLocator(1), 0);
+ let a = RequestKey::child(PRODUCER, ANCHOR, StructureLocator(1), 0);
let b = RequestKey::child(
PRODUCER,
- STRUCTURE,
StructureAnchor::from_world(1, 2, 3, 0),
StructureLocator(1),
0,
@@ -1526,7 +1445,7 @@ mod tests
{
let mut q = queue(8, 8, 8);
let anchor = StructureAnchor::from_world(4, 5, 6, 0);
- let a = RequestKey::child(PRODUCER, STRUCTURE, anchor, StructureLocator(1), 0);
+ let a = RequestKey::child(PRODUCER, anchor, StructureLocator(1), 0);
let b = child_key(1, 0);
q.ingest(
diff --git a/src/production/tree_locator.rs b/src/production/tree_locator.rs
index 0cec62e..1459ef0 100644
--- a/src/production/tree_locator.rs
+++ b/src/production/tree_locator.rs
@@ -14,7 +14,7 @@ use crate::production::StructureLocator;
/// an encoded location of `1032` for a 4-tree, refers to from the root : going into the 0th
/// child, then 3rd child, then 2nd child. It refers to a node of depth 3.
///
-#[derive(Clone, Copy, Debug)]
+#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]
pub struct TreeLocator
{
x: u32,
@@ -200,7 +200,7 @@ impl TreeLocator
(0..N as u32)
.cartesian_product(0..N as u32)
.cartesian_product(0..N as u32)
- .map(|((x, y), z)| self.child(x, y, z))
+ .map(|((z, y), x)| self.child(x, y, z))
}
/// Returns the coordinate of this node inside its parent.
@@ -218,6 +218,16 @@ impl TreeLocator
(x, y, z)
}
+
+ /// Returns the location of this node at in the space of this depth
+ pub fn node_location(&self) -> (u32, u32, u32)
+ {
+ let depth = self.depth();
+
+ // Puts a one in base-N on the Nth digit
+ let one = N.pow(depth) as u32;
+ (self.x % one, self.y % one, self.z % one)
+ }
}
#[cfg(test)]
@@ -419,4 +429,13 @@ mod tests
l = l.child(1, 1, 1);
}
}
+
+ #[test]
+ fn node_at_depth_roundtrip()
+ {
+ let l = TreeLocator::<4>::from_node_coords(3, 8, 1, 18);
+ let (nx, ny, nz) = l.node_location();
+ let l2 = TreeLocator::<4>::from_node_coords(3, nx, ny, nz);
+ assert!(l == l2);
+ }
}
diff --git a/src/sparse_tree.rs b/src/sparse_tree.rs
index 36f6400..8b14955 100644
--- a/src/sparse_tree.rs
+++ b/src/sparse_tree.rs
@@ -4,6 +4,9 @@ use std::collections::VecDeque;
use bytemuck::Pod;
use bytemuck::Zeroable;
use itertools::Itertools;
+use noise::Terrace;
+
+use crate::production::tree_locator::TreeLocator;
#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
#[repr(C)]
@@ -43,7 +46,7 @@ impl Color
#[derive(Debug, Clone)]
pub struct NTree
{
- map: HashMap, NTreeNode>,
+ map: HashMap, NTreeNode>,
// Depth is the parameter such that
// N^depth == max_number_of_voxels
@@ -54,19 +57,16 @@ pub struct NTree
pub struct NTreeIter<'a, const N: usize>
{
tree: &'a NTree,
- dfs_stack: Vec>,
+ dfs_stack: Vec>,
}
#[derive(Debug, Clone, Copy)]
pub struct NTreeNode
{
- color: Color,
- subdivided: bool,
+ pub color: Color,
+ pub subdivided: bool,
}
-#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
-pub struct NTreeNodeLocator(usize);
-
impl NTree
where
[(); N * N * N]:,
@@ -78,7 +78,7 @@ where
color,
subdivided: false,
};
- map.insert(NTreeNodeLocator::::root(), root);
+ map.insert(TreeLocator::::root(), root);
Self { map, depth }
}
@@ -94,7 +94,7 @@ where
assert!(z < N.pow(self.depth as u32));
// Try to walk down the tree, and create necessary nodes
- let mut current_node_loc = NTreeNodeLocator::::root();
+ let mut current_node_loc = TreeLocator::::root();
let mut current_node_size = N.pow(self.depth as u32);
let mut current_node = self.map.get(¤t_node_loc).unwrap();
@@ -112,7 +112,8 @@ where
let child_z = (z % current_node_size) / child_node_size;
current_node_size = child_node_size;
- current_node_loc = current_node_loc.child(child_x, child_y, child_z);
+ current_node_loc =
+ current_node_loc.child(child_x as u32, child_y as u32, child_z as u32);
current_node = self.map.get(¤t_node_loc).unwrap();
}
}
@@ -124,7 +125,7 @@ where
assert!(z < N.pow(depth as u32));
// Try to walk down the tree, and create necessary nodes
- let mut current_node_loc = NTreeNodeLocator::::root();
+ let mut current_node_loc = TreeLocator::::root();
let mut current_node_size = N.pow(self.depth as u32);
let mut current_depth = 0;
let mut current_node = self.map.get_mut(¤t_node_loc).unwrap();
@@ -145,7 +146,7 @@ where
color: current_node.color,
subdivided: false,
};
- current_node_loc.children().into_iter().for_each(|child| {
+ current_node_loc.children().for_each(|child| {
self.map.insert(child, new_nodes);
});
}
@@ -158,7 +159,8 @@ where
current_node_size = child_node_size;
current_depth += 1;
- current_node_loc = current_node_loc.child(child_x, child_y, child_z);
+ current_node_loc =
+ current_node_loc.child(child_x as u32, child_y as u32, child_z as u32);
current_node = self.map.get_mut(¤t_node_loc).unwrap();
}
@@ -184,8 +186,7 @@ where
// Access all children's colors
let children_color_avg = current_node_loc
.children()
- .iter()
- .map(|child_loc| self.map.get(child_loc).unwrap().color)
+ .map(|child_loc| self.map.get(&child_loc).unwrap().color)
// AGGREGATE AND AVERAGE HERE !!
.next()
.unwrap();
@@ -200,7 +201,7 @@ where
}
}
- fn make_constant(&mut self, locator: NTreeNodeLocator, color: Color)
+ fn make_constant(&mut self, locator: TreeLocator, color: Color)
{
let mut dfs_stack = Vec::new();
dfs_stack.push(locator);
@@ -236,17 +237,17 @@ where
let mut merged_size = vec![0; array.len()];
let width = N.pow(depth as u32);
- for (x, y) in (0..width).cartesian_product(0..width)
+ for (z, y) in (0..width).cartesian_product(0..width)
{
- let mut z = 0;
- while z < width
+ let mut x = 0;
+ while x < width
{
if merged_size[x + y * width + z * width * width] != 0
{
// If current voxel has already been accounted for -> skip
// We stumbled on a big merged block, we can skip it as a whole on the inner
// dimension
- z += merged_size[x + y * width + z * width * width];
+ x += merged_size[x + y * width + z * width * width];
continue;
}
@@ -261,12 +262,13 @@ where
// Try to merge for each depth
let mut max_power_merge = 0; // Single voxel can always be merged
let color = array[x + y * width + z * width * width];
- let mut locator = NTreeNodeLocator::::new(depth, x, y, z);
+ let mut locator =
+ TreeLocator::::from_node_coords(depth as u32, x as u32, y as u32, z as u32);
'power_search: for power in 1..=block_power
{
let block_size = N.pow(power);
// Check if candidate block has the same color
- for ((merge_x, merge_y), merge_z) in (0..block_size)
+ for ((merge_z, merge_y), merge_x) in (0..block_size)
.cartesian_product(0..block_size)
.cartesian_product(0..block_size)
{
@@ -286,7 +288,7 @@ where
// We know which size we can know merge
// Say we accounted for those voxels :
let block_size = N.pow(max_power_merge);
- for ((merge_x, merge_y), merge_z) in (0..block_size)
+ for ((merge_z, merge_y), merge_x) in (0..block_size)
.cartesian_product(0..block_size)
.cartesian_product(0..block_size)
{
@@ -302,7 +304,7 @@ where
subdivided: false,
};
structure.insert(locator, node);
- z += block_size;
+ x += block_size;
}
}
@@ -329,15 +331,18 @@ where
}
// Add hierarchy node
- let locator =
- NTreeNodeLocator::::new(depth - current_power, block_x, block_y, block_z);
+ let locator = TreeLocator::::from_node_coords(
+ (depth - current_power) as u32,
+ block_x as u32,
+ block_y as u32,
+ block_z as u32,
+ );
// Get average color of children
let color = Color::average(
locator
.children()
- .iter()
- .map(|child_loc| structure.get(child_loc).unwrap().color),
+ .map(|child_loc| structure.get(&child_loc).unwrap().color),
);
let hierarchy_node = NTreeNode {
@@ -354,51 +359,10 @@ where
}
}
- /*
- pub fn as_explicit_structure(&self) -> (Color, Vec>)
+ pub fn get_by_loc(&self, locator: TreeLocator) -> Option
{
- let root = self.map.get(&NTreeNodeLocator::root()).unwrap();
- if !root.subdivided
- {
- return (root.color, vec![]);
- }
-
- let new_node = ExplicitNTreeNode {
- structure: [StructurePointer(0); _],
- colors: [Color(0., 0., 0., 0.); _],
- };
- let mut explicit_structure = vec![new_node.clone()];
- let mut bfs_queue = VecDeque::new();
-
- bfs_queue.push_back((NTreeNodeLocator::root(), 0));
-
- while let Some((node_loc, explicit_loc)) = bfs_queue.pop_front()
- {
- // Iterate on children, that must exist
- for (i, child_loc) in node_loc.children().iter().enumerate()
- {
- let child_data = self.map.get(child_loc).unwrap();
- explicit_structure[explicit_loc].colors[i] = child_data.color;
-
- if !child_data.subdivided
- {
- explicit_structure[explicit_loc].structure[i] =
- StructurePointer::new(false, true, 0);
- continue;
- }
-
- // Child is subdivided, it needs to be handled.
- let spot = explicit_structure.len();
- explicit_structure.push(new_node.clone());
- bfs_queue.push_back((*child_loc, spot));
- explicit_structure[explicit_loc].structure[i] =
- StructurePointer::new(true, true, spot as u32);
- }
- }
-
- (root.color, explicit_structure)
+ self.map.get(&locator).copied()
}
- */
}
fn base_trailing_zeroes(mut number: usize) -> Option
@@ -417,117 +381,80 @@ fn base_trailing_zeroes(mut number: usize) -> Option
Some(trailing_zeroes)
}
-impl NTreeNodeLocator
+pub fn load_ply, const N: usize>(path: P) -> NTree
+where
+ [(); N * N * N]:,
{
- pub fn root() -> Self
+ let file = std::fs::read_to_string(path).unwrap();
+
+ let mut colors = vec![Color(0., 0., 0., 0.); 256 * 256 * 256];
+ for line in file.lines()
{
- Self(1)
+ let coords = line
+ .split(',')
+ .take(3)
+ .map(|s| s.trim_end().trim_start().parse::().unwrap())
+ .collect::>();
+ let (x, y, z) = (coords[0], coords[1], coords[2]);
+ let index = x + z * 256 + y * 256 * 256;
+ colors[index as usize] = Color(1., 1., 1., 1.);
}
- pub fn from_usize(n: usize) -> Self
+ NTree::from_array(&colors, 4)
+}
+
+mod test
+{
+ use glam::Vec3;
+ use rand::random;
+
+ use crate::production::tree_locator::TreeLocator;
+ use crate::sparse_tree::Color;
+ use crate::sparse_tree::NTree;
+
+ #[test]
+ fn constant_set()
{
- Self(n)
+ let mut tree = NTree::<4>::constant(Color(0., 0., 0., 0.), 4);
+ assert!(tree.get(0, 0, 0) == Color(0., 0., 0., 0.));
+ tree.set(0, 0, 0, Color(1., 1., 1., 1.));
+ assert!(tree.get(0, 0, 0) == Color(1., 1., 1., 1.));
}
- pub fn new(mut depth: usize, x: usize, y: usize, z: usize) -> Self
+ #[test]
+ fn load_read_same()
{
- let mut loc = Self::root();
- let mut size = N.pow(depth as u32);
- while depth != 0
+ let file = std::fs::read_to_string("dragon.txt").unwrap();
+
+ let mut colors = vec![Color(0., 0., 0., 0.); 256 * 256 * 256];
+ for line in file.lines()
{
- size /= N;
- let child_x = (x / size) % N;
- let child_y = (y / size) % N;
- let child_z = (z / size) % N;
- loc = loc.child(child_x, child_y, child_z);
- depth -= 1;
+ let coords = line
+ .split(',')
+ .take(3)
+ .map(|s| s.trim_end().trim_start().parse::().unwrap())
+ .collect::>();
+ let (x, y, z) = (coords[0], coords[1], coords[2]);
+ let index = x + z * 256 + y * 256 * 256;
+ colors[index as usize] = Color(1., 1., 1., 1.);
}
- return loc;
- }
+ println!("building tree");
+ let tree = NTree::<4>::from_array(&colors, 4);
+ println!("ok");
- pub fn depth(&self) -> usize
- {
- let mut n = self.0;
- let mut depth = 0;
- while n != 1
+ for x in 0..256
{
- n /= N * N * N;
- depth += 1;
- }
- depth
- }
-
- pub fn child_location(&self) -> (usize, usize, usize)
- {
- let mut n = self.0;
- let z = n % N;
- n /= N;
- let y = n % N;
- n /= N;
- let x = n % N;
-
- (x, y, z)
- }
-
- pub fn node_location(&self) -> (usize, usize, usize)
- {
- let mut locator = *self;
- let mut nx = 0;
- let mut ny = 0;
- let mut nz = 0;
- let mut size = 1;
- while locator.0 != 1
- {
- let (cx, cy, cz) = locator.child_location();
-
- nx += cx * size;
- ny += cy * size;
- nz += cz * size;
- size *= N;
-
- locator = locator.parent().unwrap();
- }
-
- (nx, ny, nz)
- }
-
- pub fn as_usize(&self) -> usize
- {
- self.0
- }
-
- pub fn parent(&self) -> Option
- {
- // Shift left by 3 digits in base N
- let loc = self.0 / (N * N * N);
- if loc == 0 { None } else { Some(Self(loc)) }
- }
-
- pub fn child(&self, x: usize, y: usize, z: usize) -> Self
- {
- assert!(x < N);
- assert!(y < N);
- assert!(z < N);
-
- let child_loc = (self.0 * N * N * N) + (x * N * N) + (y * N) + z;
- NTreeNodeLocator(child_loc)
- }
-
- pub fn children(&self) -> Vec
- {
- let mut children = vec![];
-
- for x in 0..N
- {
- for y in 0..N
+ for y in 0..256
{
- for z in 0..N
+ for z in 0..256
{
- children.push(self.child(x, y, z));
+ let index = x + y * 256 + z * 256 * 256;
+ let color = colors[index];
+ let t = tree.get(x, y, z);
+ assert!(t == color);
}
}
}
- children
}
}
diff --git a/src/terrain.rs b/src/terrain.rs
index f208a0c..30350c0 100644
--- a/src/terrain.rs
+++ b/src/terrain.rs
@@ -7,7 +7,6 @@ use wgpu::CommandEncoder;
use wgpu::include_wgsl;
use crate::gpu::create_multi_buffers_bind_group_layout;
-use crate::production::StructureId;
use crate::voxel_cache;
use crate::voxel_cache::schema::StructureAnchor;
use crate::voxel_cache::tables::FixedStructureTable;
@@ -110,19 +109,19 @@ impl ToroidalStructureTable
/// This requires updating the structure table to remove disapearing chunks.
///
/// Slots whose world position changed get a new anchor. Anchors that remain
- /// in view keep their [`StructureId`]; anchors that leave are retired. The
+ /// in view keep their identity; anchors that leave are retired. The
/// invalidation pass resets the pointers of moved slots so their roots are
/// requested again.
///
- /// Returns the retired structure ids. The host may use them to cancel
- /// speculative queue work; correctness does not depend on it because GPU
- /// insertion validates the anchor/id/slot.
+ /// Returns the retired anchors. The host may use them to cancel speculative
+ /// queue work; correctness does not depend on it because GPU insertion
+ /// validates the anchor/slot.
pub fn move_position(
&mut self,
queue: &wgpu::Queue,
encoder: &mut CommandEncoder,
new_position: Vec3,
- ) -> Vec
+ ) -> Vec
{
let previous_offset = self.current_offset;
let new_offset = Self::offset_from_center(self.extent, new_position);
@@ -140,10 +139,9 @@ impl ToroidalStructureTable
})
.collect();
- let (_assignments, retired_ids) = self
+ retired = self
.fixed_structure_table
.reassign_slots(queue, &new_anchors);
- retired = retired_ids;
}
let invalidation_parameters = ToroidalInvalidationImmediates {
@@ -208,12 +206,12 @@ impl ToroidalStructureTable
fn position_for_offset(
extent: (usize, usize, usize),
- structure_id: usize,
+ slot: 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 id = slot as isize;
let sx = id % ex;
let sz = (id / ex) % ez;
diff --git a/src/voxel_cache/schema.rs b/src/voxel_cache/schema.rs
index d8b32dd..61f0c2c 100644
--- a/src/voxel_cache/schema.rs
+++ b/src/voxel_cache/schema.rs
@@ -102,15 +102,11 @@ unsafe impl Pod for StructurePage where [(); N * N * N]: {}
/// Number of `u32` words in a [`StructureAnchor`].
pub const ANCHOR_WORDS: usize = 4;
-/// Sentinel used in [`RequestInformation::table_slot`] and
+/// Sentinel used in [`RequestMeta::table_slot`] and
/// [`InsertionParent::table_slot`] to mark an insertion that is not attached to
/// a structure-table slot (internal requests).
pub const NO_TABLE_SLOT: u32 = u32::MAX;
-/// Sentinel reserved so that a structure id is never allocated. Structure ids
-/// are monotonic per producer and a value is never reused for another anchor.
-pub const NO_STRUCTURE_ID: u32 = u32::MAX;
-
/// Opaque, table-defined identity of a structure's *content*.
///
/// The cache and the request queue never interpret these words. A table decides
@@ -159,9 +155,6 @@ impl StructureAnchor
#[repr(C)]
pub struct LocationPage
{
- /// Identifier for the structure to which the node pertains
- pub structure_id: u32,
-
/// Identifier for locating this particular node within the structure
pub node_id: u32,
@@ -202,9 +195,6 @@ impl DepthPage
#[repr(C)]
pub struct RequestInformation
{
- /// Identifier for the structure to which the node pertains
- pub structure_id: u32,
-
/// Identifier for locating this particular node within the structure
pub node_id: u32,
@@ -219,10 +209,6 @@ pub struct RequestInformation
/// Opaque content identity of the structure this request belongs to.
pub anchor: StructureAnchor,
-
- /// Table slot for an external root request; [`NO_TABLE_SLOT`] for internal
- /// requests.
- pub table_slot: u32,
}
/// Metainformation kept along each request, to know which node made the demand
@@ -239,6 +225,10 @@ pub struct RequestMeta
/// The depth on which the request was issued
pub depth: u32,
+
+ /// Table slot for an external root request; [`NO_TABLE_SLOT`] for internal
+ /// requests.
+ pub table_slot: u32,
}
/// Sentinel used in [`RequestMeta::page_index`] and [`InsertionParent::page_index`] to mark a
@@ -284,9 +274,6 @@ pub struct InsertionParent
/// 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,
@@ -306,7 +293,6 @@ 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,
anchor: StructureAnchor,
@@ -317,7 +303,6 @@ impl InsertionParent
page_index: meta.page_index,
children_index: meta.children_index,
depth: meta.depth,
- structure_id,
node_id,
producer_id,
anchor,
@@ -326,19 +311,13 @@ impl InsertionParent
}
/// Parent information for the root of an external structure.
- pub fn external(
- structure_id: u32,
- producer_id: u32,
- anchor: StructureAnchor,
- table_slot: u32,
- ) -> Self
+ pub fn external(producer_id: u32, anchor: StructureAnchor, table_slot: 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,
anchor,
@@ -426,10 +405,10 @@ mod tests
fn wire_layout_sizes_are_stable()
{
assert_eq!(size_of::(), 16);
- assert_eq!(size_of::(), 40);
- assert_eq!(size_of::(), 28);
- assert_eq!(size_of::(), 48);
- assert_eq!(size_of::(), 12);
+ assert_eq!(size_of::(), 32);
+ assert_eq!(size_of::(), 24);
+ assert_eq!(size_of::(), 44);
+ assert_eq!(size_of::(), 16);
}
#[test]
diff --git a/src/voxel_cache/shaders/common.wgsl b/src/voxel_cache/shaders/common.wgsl
index fc637e9..a8e001a 100644
--- a/src/voxel_cache/shaders/common.wgsl
+++ b/src/voxel_cache/shaders/common.wgsl
@@ -27,20 +27,19 @@ fn anchor_eq(a: StructureAnchor, b: StructureAnchor) -> bool
struct RequestInformation
{
- structure_id: u32,
node_id: u32,
children_index: u32,
producer_id: u32,
demand: u32,
- anchor: StructureAnchor,
- table_slot: u32
+ anchor: StructureAnchor
}
struct RequestMeta
{
page_index: u32,
children_index: u32,
- depth: u32
+ depth: u32,
+ table_slot: u32
}
// No cache parent (external root insertion).
@@ -56,7 +55,6 @@ struct InsertionParent
page_index: u32,
children_index: u32,
depth: u32,
- structure_id: u32,
node_id: u32,
producer_id: u32,
anchor: StructureAnchor,
@@ -70,7 +68,6 @@ struct AttributeArray
struct LocationPage
{
- structure_id: u32,
node_id: u32,
producer_id: u32,
anchor: StructureAnchor
diff --git a/src/voxel_cache/shaders/fixed_table/insertion.wgsl b/src/voxel_cache/shaders/fixed_table/insertion.wgsl
index b11dd64..7dc301a 100644
--- a/src/voxel_cache/shaders/fixed_table/insertion.wgsl
+++ b/src/voxel_cache/shaders/fixed_table/insertion.wgsl
@@ -12,7 +12,6 @@
// Group 2: Slot metadata
@group(2) @binding(0) var fixed_table_anchors: array;
-@group(2) @binding(1) var fixed_table_structure_ids: array;
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
@@ -24,8 +23,7 @@ fn slot_matches(parent: InsertionParent) -> bool
return false;
}
- return parent.structure_id == fixed_table_structure_ids[slot]
- && anchor_eq(parent.anchor, fixed_table_anchors[slot]);
+ return anchor_eq(parent.anchor, fixed_table_anchors[slot]);
}
@compute
diff --git a/src/voxel_cache/shaders/fixed_table/validate_insertion.wgsl b/src/voxel_cache/shaders/fixed_table/validate_insertion.wgsl
index b83099d..90f5e01 100644
--- a/src/voxel_cache/shaders/fixed_table/validate_insertion.wgsl
+++ b/src/voxel_cache/shaders/fixed_table/validate_insertion.wgsl
@@ -12,13 +12,12 @@
// Group 2: Slot metadata
@group(2) @binding(0) var fixed_table_anchors: array;
-@group(2) @binding(1) var fixed_table_structure_ids: array;
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
-/// The slot named by the parent still holds the same anchor and structure id.
-/// This is what makes queue invalidation optional: a stale root response for a
-/// retired or reused slot can no longer win.
+/// The slot named by the parent still holds the same anchor. This is what makes
+/// queue invalidation optional: a stale root response for a retired or reused
+/// slot can no longer win.
fn slot_matches(parent: InsertionParent) -> bool
{
let slot = parent.table_slot;
@@ -27,8 +26,7 @@ fn slot_matches(parent: InsertionParent) -> bool
return false;
}
- return parent.structure_id == fixed_table_structure_ids[slot]
- && anchor_eq(parent.anchor, fixed_table_anchors[slot]);
+ return anchor_eq(parent.anchor, fixed_table_anchors[slot]);
}
/// Validates external root insertions against the structure table.
diff --git a/src/voxel_cache/shaders/fixed_table/write_requests.wgsl b/src/voxel_cache/shaders/fixed_table/write_requests.wgsl
index a9b0d66..f850ce3 100644
--- a/src/voxel_cache/shaders/fixed_table/write_requests.wgsl
+++ b/src/voxel_cache/shaders/fixed_table/write_requests.wgsl
@@ -8,9 +8,8 @@
@group(1) @binding(1) var request_buffer_informations: array;
@group(1) @binding(2) var request_buffer_meta: array;
-/// Group 2: Slot metadata (current anchor/id assignment)
+/// Group 2: Slot metadata (current anchor assignment)
@group(2) @binding(0) var fixed_table_anchors: array;
-@group(2) @binding(1) var fixed_table_structure_ids: array;
var table_producer_id: u32;
@@ -34,13 +33,11 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3)
}
var request_info: RequestInformation;
- request_info.structure_id = fixed_table_structure_ids[slot];
request_info.node_id = 0;
request_info.children_index = 0;
request_info.producer_id = table_producer_id;
request_info.demand = request_handler_counts[slot];
request_info.anchor = fixed_table_anchors[slot];
- request_info.table_slot = slot;
var request_meta: RequestMeta;
// External requests have no parent page.
@@ -48,6 +45,7 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3)
request_meta.children_index = 0;
// u32s wrap arround
request_meta.depth = 0xFFFFFFFF;
+ request_meta.table_slot = slot;
request_buffer_informations[index] = request_info;
request_buffer_meta[index] = request_meta;
diff --git a/src/voxel_cache/shaders/insertion.wgsl b/src/voxel_cache/shaders/insertion.wgsl
index 6d69df9..13bc6c0 100644
--- a/src/voxel_cache/shaders/insertion.wgsl
+++ b/src/voxel_cache/shaders/insertion.wgsl
@@ -44,8 +44,7 @@ fn internal_parent_is_valid(parent: InsertionParent) -> bool
}
let location = structure_location_pages[parent.page_index];
- if(location.structure_id != parent.structure_id ||
- location.node_id != parent.node_id ||
+ if(location.node_id != parent.node_id ||
location.producer_id != parent.producer_id ||
!anchor_eq(location.anchor, parent.anchor))
{
diff --git a/src/voxel_cache/shaders/write_pointers.wgsl b/src/voxel_cache/shaders/write_pointers.wgsl
index f7dba38..ffcaa9e 100644
--- a/src/voxel_cache/shaders/write_pointers.wgsl
+++ b/src/voxel_cache/shaders/write_pointers.wgsl
@@ -50,8 +50,7 @@ fn write_pointers(@builtin(global_invocation_id) gid: vec3)
}
let location = structure_location_pages[parent.page_index];
- if(location.structure_id != parent.structure_id ||
- location.node_id != parent.node_id ||
+ if(location.node_id != parent.node_id ||
location.producer_id != parent.producer_id ||
!anchor_eq(location.anchor, parent.anchor))
{
diff --git a/src/voxel_cache/shaders/write_requests.wgsl b/src/voxel_cache/shaders/write_requests.wgsl
index e14d686..71497a7 100644
--- a/src/voxel_cache/shaders/write_requests.wgsl
+++ b/src/voxel_cache/shaders/write_requests.wgsl
@@ -33,19 +33,18 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3)
// Fill out request information
var request_information: RequestInformation;
- 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];
request_information.anchor = structure_location_pages[page_index].anchor;
- request_information.table_slot = NO_TABLE_SLOT;
// Fill out request meta information
var request_meta: RequestMeta;
request_meta.page_index = page_index;
request_meta.children_index = request_location.children_index;
request_meta.depth = structure_depth_pages[page_index];
+ request_meta.table_slot = NO_TABLE_SLOT;
// Write them to request buffer
request_buffer_informations[index] = request_information;
diff --git a/src/voxel_cache/tables.rs b/src/voxel_cache/tables.rs
index da8bae4..79fcfcb 100644
--- a/src/voxel_cache/tables.rs
+++ b/src/voxel_cache/tables.rs
@@ -1,23 +1,21 @@
+use std::collections::HashMap;
+
use wgpu::util::DeviceExt;
+use crate::gpu::create_multi_buffers_bind_group;
use crate::gpu::indirect_buffer::IndirectBuffer1D;
use crate::gpu_profiler::ScopeEncoder;
use crate::gpu_profiler::memory_profiler::MemoryProfile;
-use crate::production::StructureId;
use crate::voxel_cache::CacheInvalidable;
use crate::voxel_cache::CacheRessources;
use crate::voxel_cache::create_multi_buffers_bg_bg_layout;
use crate::voxel_cache::eviction::CacheEvictor;
use crate::voxel_cache::insertion::CacheInsertionData;
-use crate::voxel_cache::layout::CacheLayout;
use crate::voxel_cache::requests::CacheRequestBuffer;
use crate::voxel_cache::requests::CacheRequestHandler;
use crate::voxel_cache::schema::CachePointer;
-use crate::voxel_cache::schema::NO_STRUCTURE_ID;
use crate::voxel_cache::schema::StructureAnchor;
-use super::pipelines::include_cache_wgsl;
-
/// Cache keeps pages from different structures within itself.
/// Pages are pieces of structure pointing to each other. But, in order to start tracing inside the
/// voxels, we must enter the cache from somewhere
@@ -40,83 +38,187 @@ macro_rules! include_table_wgsl {
}};
}
-/// One slot whose anchor or structure id changed during a reassignment.
+/// Returns the anchors that were present in the table before the reassignment
+/// but are absent afterwards.
///
-/// Returned for diagnostics and optional host-side cancellation. Correctness
-/// does not depend on callers reading these fields; the GPU validates the
-/// current slot metadata before accepting an insertion.
-#[derive(Clone, Copy, Debug)]
-#[allow(dead_code)]
-pub struct SlotAssignment
-{
- pub slot: u32,
- pub previous_anchor: StructureAnchor,
- pub previous_structure: StructureId,
- pub anchor: StructureAnchor,
- pub structure: StructureId,
-}
-
-/// Reuses ids for anchors that are still present, allocates fresh ids for
-/// anchors entering the table, and returns the ids that are no longer used.
-///
-/// A structure id is never reused for a different anchor. Exhaustion is a fatal
-/// error rather than a wrap, because wrapping would silently alias identities.
-fn plan_slot_reassignment(
+/// The anchor is the structure identity, so an anchor that stays in view keeps
+/// its identity regardless of which slot it occupies. A table must never expose
+/// two live slots with the same anchor.
+fn retired_anchors(
old_anchors: &[StructureAnchor],
- old_ids: &[StructureId],
new_anchors: &[StructureAnchor],
- next_structure_id: &mut u32,
-) -> (Vec, Vec)
+) -> Vec
{
- use std::collections::HashMap;
use std::collections::HashSet;
- assert_eq!(old_anchors.len(), old_ids.len());
assert!(
new_anchors.iter().collect::>().len() == new_anchors.len(),
"a structure table must not expose two live slots with the same anchor"
);
- let mut by_anchor = HashMap::with_capacity(old_anchors.len());
- for (&anchor, &id) in old_anchors.iter().zip(old_ids)
- {
- by_anchor.insert(anchor, id);
- }
-
- let mut new_ids = Vec::with_capacity(new_anchors.len());
- for &anchor in new_anchors
- {
- if let Some(&id) = by_anchor.get(&anchor)
- {
- new_ids.push(id);
- }
- else
- {
- assert_ne!(
- *next_structure_id, NO_STRUCTURE_ID,
- "structure id space exhausted"
- );
- new_ids.push(StructureId(*next_structure_id));
- *next_structure_id += 1;
- }
- }
-
let live: HashSet = new_anchors.iter().copied().collect();
- let retired = old_anchors
+ old_anchors
.iter()
- .zip(old_ids)
- .filter(|(anchor, _)| !live.contains(anchor))
- .map(|(_, id)| *id)
- .collect();
-
- (new_ids, retired)
+ .copied()
+ .filter(|anchor| !live.contains(anchor))
+ .collect()
}
-/// A structure table with a fixed length
-pub struct FixedStructureTable
+/// Host-side free-list allocator for structure-table slots.
+///
+/// Slots are fixed-size, so a freed slot is always reusable and a free list is
+/// all that is needed. A slot index is stable for the lifetime of an allocation,
+/// which is what makes it safe to store in a TLAS or any other long-lived handle.
+///
+/// The GPU does not know about this allocator. Liveness is expressed on the GPU
+/// by the slot pointer being empty ([`CachePointer::new(None)`]). A released slot
+/// keeps its stale anchor on the GPU until it is reused; the empty pointer keeps
+/// the tracer from ever treating it as live.
+#[allow(dead_code)]
+struct SlotAllocator
+{
+ /// Slot-indexed liveness. `None` means the slot is free.
+ slot_anchors: Vec