refactor: Removing structureID, keep structure anchor as id

This commit is contained in:
2026-11-12 15:51:05 +01:00
parent a39256a0f1
commit c31f3a9bc3
23 changed files with 1417 additions and 806 deletions
+224 -25
View File
@@ -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<Mutex<ToroidalStructureTable>>,
structure_table_request_buffer: Arc<CacheRequestBuffer>,
structure_table_cache_insertion: Arc<CacheInsertionData<4>>,
instance_buffer: Buffer,
instance_count: usize,
usage_vec: Arc<Mutex<Vec<usize>>>,
rm_time: Arc<Mutex<f32>>,
frame_time: Arc<Mutex<f32>>,
@@ -153,6 +169,9 @@ struct State
// Producers workers
wakeup: Sender<()>,
bvh: BvhStructureTable,
bvh_debug: BvhDebugPipeline,
}
pub unsafe fn as_raw_bytes<T: Sized>(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<const N: usize>(
tree: &NTree<N>,
request: &RequestKey,
) -> (
[u32; N * N * N],
[[f32; 3]; N * N * N],
InsertionInformation<N>,
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::<N>::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::<N>::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<N> = 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<const N: usize>(
generator: &dyn ChunkedProducer<N>,
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::<N>::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,
)
}
*/
+4 -13
View File
@@ -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<N>;
/// A pure function that can produce a voxel node based on the owner produer id, requesting structure, and the
/// requesting location within the structure.
/// 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<N>, [Self::Output; N * N * N]);
-1
View File
@@ -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),
);
+49 -130
View File
@@ -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<T>
{
pub key: RequestKey,
pub meta: RequestMeta,
pub table_slot: u32,
pub payload: T,
}
@@ -250,15 +224,11 @@ impl<T> ReadyItem<T>
{
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<T> ReadyItem<T>
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<T>
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<T>,
@@ -480,7 +443,6 @@ impl<T> RequestQueue<T>
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<T> RequestQueue<T>
first_seen: frame,
last_seen: frame,
meta: request.meta,
table_slot: request.table_slot,
generation,
attempt: 0,
payload: None,
@@ -722,7 +683,6 @@ impl<T> RequestQueue<T>
result.push(ReadyItem {
key: job.key,
meta: job.meta,
table_slot: job.table_slot,
payload,
});
}
@@ -731,16 +691,6 @@ impl<T> RequestQueue<T>
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(
+21 -2
View File
@@ -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<const N: usize>
{
x: u32,
@@ -200,7 +200,7 @@ impl<const N: usize> TreeLocator<N>
(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<const N: usize> TreeLocator<N>
(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);
}
}
+92 -165
View File
@@ -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<const N: usize>
{
map: HashMap<NTreeNodeLocator<N>, NTreeNode>,
map: HashMap<TreeLocator<N>, NTreeNode>,
// Depth is the parameter such that
// N^depth == max_number_of_voxels
@@ -54,19 +57,16 @@ pub struct NTree<const N: usize>
pub struct NTreeIter<'a, const N: usize>
{
tree: &'a NTree<N>,
dfs_stack: Vec<NTreeNodeLocator<N>>,
dfs_stack: Vec<TreeLocator<N>>,
}
#[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<const N: usize>(usize);
impl<const N: usize> NTree<N>
where
[(); N * N * N]:,
@@ -78,7 +78,7 @@ where
color,
subdivided: false,
};
map.insert(NTreeNodeLocator::<N>::root(), root);
map.insert(TreeLocator::<N>::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::<N>::root();
let mut current_node_loc = TreeLocator::<N>::root();
let mut current_node_size = N.pow(self.depth as u32);
let mut current_node = self.map.get(&current_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(&current_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::<N>::root();
let mut current_node_loc = TreeLocator::<N>::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(&current_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(&current_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<N>, color: Color)
fn make_constant(&mut self, locator: TreeLocator<N>, 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::<N>::new(depth, x, y, z);
let mut locator =
TreeLocator::<N>::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::<N>::new(depth - current_power, block_x, block_y, block_z);
let locator = TreeLocator::<N>::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<ExplicitNTreeNode<N>>)
pub fn get_by_loc(&self, locator: TreeLocator<N>) -> Option<NTreeNode>
{
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<const N: usize>(mut number: usize) -> Option<u32>
@@ -417,117 +381,80 @@ fn base_trailing_zeroes<const N: usize>(mut number: usize) -> Option<u32>
Some(trailing_zeroes)
}
impl<const N: usize> NTreeNodeLocator<N>
pub fn load_ply<P: AsRef<std::path::Path>, const N: usize>(path: P) -> NTree<N>
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::<u32>().unwrap())
.collect::<Vec<_>>();
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::<u32>().unwrap())
.collect::<Vec<_>>();
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<Self>
{
// 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<Self>
{
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
}
}
+8 -10
View File
@@ -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<StructureId>
) -> Vec<StructureAnchor>
{
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;
+10 -31
View File
@@ -102,15 +102,11 @@ unsafe impl<const N: usize> Pod for StructurePage<N> 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::<StructureAnchor>(), 16);
assert_eq!(size_of::<RequestInformation>(), 40);
assert_eq!(size_of::<LocationPage>(), 28);
assert_eq!(size_of::<InsertionParent>(), 48);
assert_eq!(size_of::<RequestMeta>(), 12);
assert_eq!(size_of::<RequestInformation>(), 32);
assert_eq!(size_of::<LocationPage>(), 24);
assert_eq!(size_of::<InsertionParent>(), 44);
assert_eq!(size_of::<RequestMeta>(), 16);
}
#[test]
+3 -6
View File
@@ -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
@@ -12,7 +12,6 @@
// Group 2: Slot metadata
@group(2) @binding(0) var<storage, read_write> fixed_table_anchors: array<StructureAnchor>;
@group(2) @binding(1) var<storage, read_write> fixed_table_structure_ids: array<u32>;
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
@@ -12,13 +12,12 @@
// Group 2: Slot metadata
@group(2) @binding(0) var<storage, read_write> fixed_table_anchors: array<StructureAnchor>;
@group(2) @binding(1) var<storage, read_write> fixed_table_structure_ids: array<u32>;
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.
@@ -8,9 +8,8 @@
@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 2: Slot metadata (current anchor/id assignment)
/// Group 2: Slot metadata (current anchor assignment)
@group(2) @binding(0) var<storage, read_write> fixed_table_anchors: array<StructureAnchor>;
@group(2) @binding(1) var<storage, read_write> fixed_table_structure_ids: array<u32>;
var<immediate> table_producer_id: u32;
@@ -34,13 +33,11 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
}
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<u32>)
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;
+1 -2
View File
@@ -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))
{
+1 -2
View File
@@ -50,8 +50,7 @@ fn write_pointers(@builtin(global_invocation_id) gid: vec3<u32>)
}
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))
{
+1 -2
View File
@@ -33,19 +33,18 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
// 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;
+867 -295
View File
File diff suppressed because it is too large Load Diff