Starting decoupling requests

This commit is contained in:
2026-11-08 21:25:40 +01:00
parent 82c952c6d8
commit d44da4520c
23 changed files with 2386 additions and 306 deletions
+79 -12
View File
@@ -17,6 +17,7 @@ use glam::Mat4;
use glam::Vec3;
use glam::Vec4;
use itertools::Itertools;
use rayon::iter::IndexedParallelIterator;
use rayon::iter::IntoParallelRefIterator;
use rayon::iter::ParallelIterator;
use wgpu::BindGroupLayout;
@@ -65,8 +66,11 @@ use crate::voxel_cache::VoxelCacheInsertion;
use crate::voxel_cache::insertion::CacheInsertionData;
use crate::voxel_cache::requests::CacheRequestBuffer;
use crate::voxel_cache::schema::InsertionInformation;
use crate::voxel_cache::schema::InsertionParent;
use crate::voxel_cache::schema::LocationPage;
use crate::voxel_cache::schema::NO_PARENT_PAGE;
use crate::voxel_cache::schema::RequestInformation;
use crate::voxel_cache::schema::RequestMeta;
use crate::voxel_cache::tables::FixedStructureTable;
mod camera;
@@ -75,6 +79,7 @@ mod gi_pipeline;
mod gpu;
pub mod gpu_profiler;
mod producers;
mod production;
mod sparse_tree;
mod terrain;
mod voxel_cache;
@@ -407,6 +412,7 @@ impl State
(terrain_width, terrain_alt, terrain_height),
Vec3::ZERO,
structure_table_request_buffer.max_requests,
0,
);
let structure_table_insertion_data = CacheInsertionData::new(&device, 128, &layout);
let chunk_instances = (0..terrain_alt)
@@ -1292,7 +1298,7 @@ impl State
self.request_buffer.host_download_requests(
&self.device,
&self.queue,
move |request_informations| {
move |request_informations, request_metas| {
let done = request_buffer_done_1.load(std::sync::atomic::Ordering::Relaxed);
if !done
{
@@ -1310,26 +1316,32 @@ impl State
let mut color_attributes = vec![];
let mut normal_attributes: Vec<[[f32; 3]; 64]> = vec![];
let mut location_pages = vec![];
let mut insertion_parents = vec![];
request_informations
.par_iter()
.map(|request| {
.zip(request_metas.par_iter())
.map(|(request, meta)| {
fullfill_request(
cloned_generator.as_ref(),
request,
meta,
cloned_map.as_ref(),
&cloned_table_1,
)
})
.collect::<Vec<_>>()
.into_iter()
.for_each(|(colors, normals, insertion_info, location)| {
.for_each(|(colors, normals, insertion_info, location, parent)| {
insertion_infos.push(insertion_info);
color_attributes.push(colors);
normal_attributes.push(std::array::from_fn(|i| normals[i].into()));
location_pages.push(location);
insertion_parents.push(parent);
});
let request_count = request_informations.len() as u32;
cloned_queue.write_buffer(
cloned_insertion_data.insertion_information_buffer(),
0,
@@ -1342,6 +1354,12 @@ impl State
bytemuck::cast_slice(&location_pages),
);
cloned_queue.write_buffer(
cloned_insertion_data.insertion_parents_buffer(),
0,
bytemuck::cast_slice(&insertion_parents),
);
cloned_queue.write_buffer(
&cloned_insertion_data.attributes_buffers()[0],
0,
@@ -1354,10 +1372,22 @@ impl State
bytemuck::cast_slice(&normal_attributes),
);
cloned_queue.write_buffer(
cloned_insertion_data.destination_indices_buffer(),
0,
bytemuck::cast_slice(&vec![u32::MAX; request_count as usize]),
);
cloned_queue.write_buffer(
cloned_insertion_data.valid_count_buffer(),
0,
bytemuck::bytes_of(&0u32),
);
cloned_queue.write_buffer(
cloned_insertion_data.page_count_buffer(),
0,
bytemuck::bytes_of(&(request_informations.len() as u32)),
bytemuck::bytes_of(&request_count),
);
},
);
@@ -1375,7 +1405,7 @@ impl State
self.structure_table_request_buffer.host_download_requests(
&self.device,
&self.queue,
move |request_informations| {
move |request_informations, request_metas| {
let done = structure_table_request_buffer_done_1
.load(std::sync::atomic::Ordering::Relaxed);
if !done
@@ -1395,26 +1425,32 @@ impl State
let mut color_attributes = vec![];
let mut normal_attributes: Vec<[[f32; 3]; 64]> = vec![];
let mut location_pages = vec![];
let mut insertion_parents = vec![];
request_informations
.par_iter()
.map(|request| {
.zip(request_metas.par_iter())
.map(|(request, meta)| {
fullfill_request(
cloned_generator.as_ref(),
request,
meta,
cloned_map.as_ref(),
&cloned_table_2,
)
})
.collect::<Vec<_>>()
.into_iter()
.for_each(|(colors, normals, insertion_info, location)| {
.for_each(|(colors, normals, insertion_info, location, parent)| {
insertion_infos.push(insertion_info);
color_attributes.push(colors);
normal_attributes.push(std::array::from_fn(|i| normals[i].into()));
location_pages.push(location);
insertion_parents.push(parent);
});
let request_count = request_informations.len() as u32;
cloned_queue.write_buffer(
cloned_st_insertion_data.insertion_information_buffer(),
0,
@@ -1427,6 +1463,12 @@ impl State
bytemuck::cast_slice(&location_pages),
);
cloned_queue.write_buffer(
cloned_st_insertion_data.insertion_parents_buffer(),
0,
bytemuck::cast_slice(&insertion_parents),
);
cloned_queue.write_buffer(
&cloned_st_insertion_data.attributes_buffers()[0],
0,
@@ -1439,10 +1481,22 @@ impl State
bytemuck::cast_slice(&normal_attributes),
);
cloned_queue.write_buffer(
cloned_st_insertion_data.destination_indices_buffer(),
0,
bytemuck::cast_slice(&vec![u32::MAX; request_count as usize]),
);
cloned_queue.write_buffer(
cloned_st_insertion_data.valid_count_buffer(),
0,
bytemuck::bytes_of(&0u32),
);
cloned_queue.write_buffer(
cloned_st_insertion_data.page_count_buffer(),
0,
bytemuck::bytes_of(&(request_informations.len() as u32)),
bytemuck::bytes_of(&request_count),
);
},
);
@@ -1614,7 +1668,6 @@ impl State
),
&mut VoxelCacheInsertion::InternalRequest(
&self.cache_insertion,
&self.request_buffer,
),
],
);
@@ -1623,7 +1676,6 @@ impl State
&self.device,
&mut scoped_encoder,
&self.structure_table_cache_insertion,
&self.structure_table_request_buffer,
);
}
@@ -1762,6 +1814,7 @@ pub struct ChunkImmediate
fn fullfill_request<const N: usize>(
generator: &dyn ChunkedProducer<N>,
request: &RequestInformation,
meta: &RequestMeta,
map: &HashMap<u32, (usize, usize, usize)>,
table: &Arc<Mutex<ToroidalStructureTable>>,
) -> (
@@ -1769,6 +1822,7 @@ fn fullfill_request<const N: usize>(
[[f32; 3]; N * N * N],
InsertionInformation<N>,
LocationPage,
InsertionParent,
)
where
[(); N * N * N]:,
@@ -1795,14 +1849,19 @@ where
let location;
let node;
if request.node_id == 0
let parent;
if meta.page_index == NO_PARENT_PAGE
{
// Produce root node
// Produce root node. An external (structure-table) request is the only
// one without a parent page; `node_id == 0` also happens for child 0 of
// the root, so it cannot be used to detect roots.
node = generator.produce_node(0, 0, 0, 0, (chunk_x, chunk_y, chunk_z));
location = LocationPage {
structure_id: request.structure_id,
node_id: NTreeNodeLocator::<4>::root().as_usize() as u32,
producer_id: request.producer_id,
};
parent = InsertionParent::external(request.structure_id, request.producer_id);
}
else
{
@@ -1824,7 +1883,14 @@ where
location = LocationPage {
structure_id: request.structure_id,
node_id: child_locator.as_usize() as u32,
producer_id: request.producer_id,
};
parent = InsertionParent::internal(
meta,
request.structure_id,
request.node_id,
request.producer_id,
);
}
(
@@ -1834,5 +1900,6 @@ where
children: node.children,
},
location,
parent,
)
}
+6 -3
View File
@@ -9,11 +9,14 @@ pub mod tree_locator;
/// Facilities for voxel production on the host (CPU) side
pub mod host_production;
/// Bounded, deduplicating, priority-ordered cache request queue
pub mod request_queue;
/// This module contains definition and common logic to produce voxel data to feed a [`VoxelCache`]
/// A cache might hold data owned by multiple different producers. To discriminate where to route the
/// request, a node is always tagged by a [`ProducerId`].
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Zeroable, Pod)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Zeroable, Pod)]
#[repr(transparent)]
pub struct ProducerId(pub u32);
@@ -21,13 +24,13 @@ pub struct ProducerId(pub u32);
/// As such a producer can tag, to its discretion, its own structure with an Id.
///
/// All node of a same tree thus share the same structure Id
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Zeroable, Pod)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Zeroable, Pod)]
#[repr(transparent)]
pub struct StructureId(pub u32);
/// A request can come from anywhere inside the structure. The producer can thus tag each node with
/// a locator, to know where the request was issued.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Zeroable, Pod)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Zeroable, Pod)]
#[repr(transparent)]
pub struct StructureLocator(pub u32);
+1 -1
View File
@@ -39,7 +39,7 @@ where
insertion: &CacheInsertionData<N>,
)
{
request_buffer.host_download_requests(device, queue, |requests| {});
request_buffer.host_download_requests(device, queue, |_requests, _metas| {});
}
pub fn produce_requests(
File diff suppressed because it is too large Load Diff
+61 -13
View File
@@ -47,6 +47,7 @@ impl ToroidalStructureTable
extent: (usize, usize, usize),
initial_position: Vec3,
max_requests: usize,
producer_id: u32,
) -> Self
{
let size = extent.0 * extent.1 * extent.2;
@@ -81,7 +82,12 @@ impl ToroidalStructureTable
ToroidalStructureTable {
extent,
fixed_structure_table: FixedStructureTable::new(device, size, max_requests),
fixed_structure_table: FixedStructureTable::new(
device,
size,
max_requests,
producer_id,
),
position: initial_position,
current_offset,
invalidation_pass,
@@ -89,13 +95,37 @@ impl ToroidalStructureTable
}
/// Moves the center position to `new_position`.
/// This requires updating to structure table to remove disapearing chunks
pub fn move_position(&mut self, encoder: &mut CommandEncoder, new_position: Vec3)
/// This requires updating to structure table to remove disapearing chunks.
///
/// Returns the structure slots whose world position changed. The host must
/// invalidate any pending request/insertion work for those slots before it
/// batches insertions for this frame.
pub fn move_position(
&mut self,
encoder: &mut CommandEncoder,
new_position: Vec3,
) -> Vec<u32>
{
let previous_offset = self.current_offset;
self.current_offset = Self::offset_from_center(self.extent, new_position);
let new_offset = Self::offset_from_center(self.extent, new_position);
self.current_offset = new_offset;
self.position = new_position;
let mut invalidated = Vec::new();
if previous_offset != new_offset
{
let size = self.extent.0 * self.extent.1 * self.extent.2;
for id in 0..size
{
let previous = Self::position_for_offset(self.extent, id, previous_offset);
let current = Self::position_for_offset(self.extent, id, new_offset);
if previous != current
{
invalidated.push(id as u32);
}
}
}
let invalidation_parameters = ToroidalInvalidationImmediates {
extent: [
self.extent.0 as u32,
@@ -130,23 +160,30 @@ impl ToroidalStructureTable
self.extent.1.div_ceil(4) as u32,
self.extent.2.div_ceil(4) as u32,
);
invalidated
}
/// Given the structure id, returns the position of the requesting chunk
pub fn get_request_position(&self, structure_id: u32) -> (isize, isize, isize)
{
let (ex, ey, ez) = (
self.extent.0 as isize,
self.extent.1 as isize,
self.extent.2 as isize,
);
Self::position_for_offset(self.extent, structure_id as usize, self.current_offset)
}
fn position_for_offset(
extent: (usize, usize, usize),
structure_id: usize,
offset: (isize, isize, isize),
) -> (isize, isize, isize)
{
let (ex, ey, ez) = (extent.0 as isize, extent.1 as isize, extent.2 as isize);
let id = structure_id as isize;
let sx = id % ex;
let sz = (id / ex) % ez;
let sy = id / (ex * ez);
let (ox, oy, oz) = self.current_offset;
let (ox, oy, oz) = offset;
(
ox + (sx - ox).rem_euclid(ex),
@@ -181,12 +218,11 @@ impl ToroidalStructureTable
device: &wgpu::Device,
encoder: &mut crate::gpu_profiler::ScopeEncoder<wgpu::CommandEncoder>,
insertion: &voxel_cache::insertion::CacheInsertionData<N>,
request: &voxel_cache::requests::CacheRequestBuffer,
) where
[(); N * N * N]:,
{
self.fixed_structure_table
.insert(device, encoder, insertion, request);
.insert(device, encoder, insertion);
}
pub fn gather_requests(
@@ -201,8 +237,20 @@ impl ToroidalStructureTable
}
}
impl voxel_cache::CacheInvalidable for ToroidalStructureTable
impl<const N: usize> voxel_cache::CacheInvalidable<N> for ToroidalStructureTable
where
[(); N * N * N]:,
{
fn validate_insertion(
&mut self,
device: &wgpu::Device,
encoder: &mut crate::gpu_profiler::ScopeEncoder<CommandEncoder>,
insertion: &voxel_cache::insertion::CacheInsertionData<N>,
) {
self.fixed_structure_table
.validate_insertion(device, encoder, insertion);
}
fn invalidate(
&mut self,
encoder: &mut crate::gpu_profiler::ScopeEncoder<CommandEncoder>,
+40 -6
View File
@@ -108,7 +108,9 @@ where
frame_timestamp: u32,
}
pub trait CacheInvalidable
pub trait CacheInvalidable<const N: usize>
where
[(); N * N * N]:,
{
fn invalidate(
&mut self,
@@ -116,14 +118,23 @@ pub trait CacheInvalidable
cache_evictor: &CacheEvictor,
invalid_timestamp: u32,
);
/// Validates an external insertion batch against the structure table and
/// compacts the valid entries before the cache allocates pages for them.
fn validate_insertion(
&mut self,
device: &Device,
encoder: &mut ScopeEncoder<CommandEncoder>,
insertion: &CacheInsertionData<N>,
);
}
pub enum VoxelCacheInsertion<'a, const N: usize>
where
[(); N * N * N]:,
{
ExternalRequest(&'a CacheInsertionData<N>, &'a mut dyn CacheInvalidable),
InternalRequest(&'a CacheInsertionData<N>, &'a CacheRequestBuffer),
ExternalRequest(&'a CacheInsertionData<N>, &'a mut dyn CacheInvalidable<N>),
InternalRequest(&'a CacheInsertionData<N>),
}
impl<const N: usize> VoxelCache<N>
@@ -243,12 +254,36 @@ where
&mut encoder,
);
// Validate everything before allocating any page, so stale insertions
// can never consume a recycled page.
for insertion in insertions.iter_mut()
{
match insertion
{
VoxelCacheInsertion::ExternalRequest(cache_insertion_data, invalidable) =>
{
invalidable.validate_insertion(device, &mut encoder, cache_insertion_data);
}
VoxelCacheInsertion::InternalRequest(cache_insertion_data) =>
{
self.cache_insertion_pass.encode_validation(
device,
&mut encoder,
&self.attributes,
&self.structure,
cache_insertion_data,
&self.evictor,
);
}
}
}
for insertion in insertions.iter()
{
match insertion
{
VoxelCacheInsertion::ExternalRequest(cache_insertion_data, _)
| VoxelCacheInsertion::InternalRequest(cache_insertion_data, _) =>
| VoxelCacheInsertion::InternalRequest(cache_insertion_data) =>
{
self.cache_insertion_pass.encode(
device,
@@ -283,13 +318,12 @@ where
// Write internal requests pointers
for insertion in insertions.iter_mut()
{
if let VoxelCacheInsertion::InternalRequest(insertion, request) = insertion
if let VoxelCacheInsertion::InternalRequest(insertion) = insertion
{
self.write_pointers_pass.encode(
&mut encoder,
device,
&self.structure,
request,
insertion,
);
}
+86 -42
View File
@@ -6,6 +6,7 @@ use wgpu::ShaderStages;
use crate::voxel_cache::layout::CacheLayout;
use crate::voxel_cache::schema::InsertionInformation;
use crate::voxel_cache::schema::InsertionParent;
use crate::voxel_cache::schema::LocationPage;
/// Data to be inserted in a cache insertion operation
@@ -31,6 +32,15 @@ where
/// Contains the indicies of the page in which the data was written
destination_indices: wgpu::Buffer,
/// Parent/attachment information for every entry : dense array of [`InsertionParent`]
insertion_parents: wgpu::Buffer,
/// Indices of the entries that passed validation, written by the validation pass
valid_indices: wgpu::Buffer,
/// Amount of entries written to [`Self::valid_indices`]
valid_count: wgpu::Buffer,
bind_group_layout: wgpu::BindGroupLayout,
bind_group: wgpu::BindGroup,
bind_group_no_attributes: wgpu::BindGroup,
@@ -65,11 +75,32 @@ where
let destination_indices = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheInsertionData::destination_indices"),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
size: (size_of::<u32>() * max_page_count) as u64,
});
let insertion_parents = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheInsertionData::insertion_parents"),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
size: (size_of::<InsertionParent>() * max_page_count) as u64,
});
let valid_indices = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheInsertionData::valid_indices"),
usage: wgpu::BufferUsages::STORAGE,
mapped_at_creation: false,
size: (size_of::<u32>() * max_page_count) as u64,
});
let valid_count = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheInsertionData::valid_count"),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
size: size_of::<u32>() as u64,
});
let attributes = layout
.attributes
.iter()
@@ -105,6 +136,18 @@ where
binding: 3,
resource: destination_indices.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: insertion_parents.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 5,
resource: valid_indices.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 6,
resource: valid_count.as_entire_binding(),
},
];
let bind_group_layout_no_attributes = Self::create_bind_group_layout(device, None);
@@ -114,7 +157,7 @@ where
entries: &entries,
});
entries.push(wgpu::BindGroupEntry {
binding: 4,
binding: 7,
resource: wgpu::BindingResource::BufferArray(&bind_group_bindings),
});
@@ -131,6 +174,9 @@ where
insertion_information,
location_pages,
destination_indices,
insertion_parents,
valid_indices,
valid_count,
attributes,
bind_group_layout,
@@ -155,53 +201,31 @@ where
layout: Option<&CacheLayout>,
) -> BindGroupLayout
{
let storage_entry = |binding: u32| wgpu::BindGroupLayoutEntry {
binding,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
let mut entries = vec![
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
storage_entry(0), // page count
storage_entry(1), // insertion information
storage_entry(2), // location pages
storage_entry(3), // destination indices
storage_entry(4), // insertion parents
storage_entry(5), // valid indices
storage_entry(6), // valid count
];
if let Some(layout) = layout
{
entries.push(wgpu::BindGroupLayoutEntry {
binding: 4,
binding: 7,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
@@ -248,6 +272,26 @@ where
&self.location_pages
}
pub fn destination_indices_buffer(&self) -> &wgpu::Buffer
{
&self.destination_indices
}
pub fn insertion_parents_buffer(&self) -> &wgpu::Buffer
{
&self.insertion_parents
}
pub fn valid_indices_buffer(&self) -> &wgpu::Buffer
{
&self.valid_indices
}
pub fn valid_count_buffer(&self) -> &wgpu::Buffer
{
&self.valid_count
}
pub fn attributes_buffers(&self) -> &[wgpu::Buffer]
{
&self.attributes
+54 -5
View File
@@ -160,6 +160,9 @@ where
/// Copies new pages into cache using LRU order
write_pipeline: ComputePipeline,
/// Validates internal insertions and compacts their indices
validate_internal_pipeline: ComputePipeline,
/// u32 buffer containing amount of inserted data of current pass
inserted_count: wgpu::Buffer,
inserted_count_bind_group: wgpu::BindGroup,
@@ -244,8 +247,19 @@ where
cache: None,
});
let validate_internal_pipeline =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("CacheInsertionPass::validate_internal_pipeline"),
layout: Some(&pipeline_layout),
module: &shader_module,
entry_point: Some("validate_internal"),
compilation_options: Default::default(),
cache: None,
});
Self {
write_pipeline,
validate_internal_pipeline,
consume_pipeline,
inserted_count,
inserted_count_bind_group,
@@ -253,6 +267,45 @@ where
}
}
/// Validates internal insertions and compacts them into the insertion data's
/// `valid_indices` buffer.
///
/// External roots are validated by the structure table that requested them.
#[allow(clippy::too_many_arguments)]
pub fn encode_validation(
&self,
device: &wgpu::Device,
encoder: &mut ScopeEncoder<CommandEncoder>,
cache_attributes: &CacheAttributes<N>,
cache_structure: &CacheStructure<N>,
insertion_data: &CacheInsertionData<N>,
cache_evictor: &CacheEvictor,
)
{
gpu_profiler::begin_scope!(encoder, "PageInsertionValidation");
let indirect_write_dispatch = self.indirect_dispatcher.workgroup_count(
device,
&mut encoder,
insertion_data.page_count_buffer(),
256,
);
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("CacheInsertionPass::validation_pass"),
timestamp_writes: None,
});
pass.set_bind_group(0, cache_attributes.bind_group(), &[]);
pass.set_bind_group(1, cache_structure.bind_group(), &[]);
pass.set_bind_group(2, insertion_data.bind_group(), &[]);
pass.set_bind_group(3, cache_evictor.bind_group(), &[]);
pass.set_bind_group(4, &self.inserted_count_bind_group, &[]);
pass.set_pipeline(&self.validate_internal_pipeline);
pass.dispatch_workgroups_indirect(indirect_write_dispatch, 0);
}
#[allow(clippy::too_many_arguments)]
pub fn encode(
&self,
@@ -396,8 +449,6 @@ where
let bindings = [
// To find where pages are pointing
Some(&CacheStructure::<N>::create_bind_group_layout(device)),
// To find where the requests came from
Some(&CacheRequestBuffer::create_bind_group_layout(device)),
// To find where the request's response went
Some(&CacheInsertionData::<N>::create_bind_group_layout(
device,
@@ -438,7 +489,6 @@ where
encoder: &mut ScopeEncoder<CommandEncoder>,
device: &Device,
cache_structure: &CacheStructure<N>,
request_buffer: &CacheRequestBuffer,
cache_insertion_data: &CacheInsertionData<N>,
)
{
@@ -458,8 +508,7 @@ where
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, cache_structure.bind_group(), &[]);
pass.set_bind_group(1, request_buffer.bind_group(), &[]);
pass.set_bind_group(2, cache_insertion_data.bind_group(), &[]);
pass.set_bind_group(1, cache_insertion_data.bind_group(), &[]);
pass.dispatch_workgroups_indirect(indirect_buffer, 0);
}
+42 -9
View File
@@ -150,7 +150,7 @@ impl<const N: usize> CacheRequestHandler<N>
let bind_group = create_multi_buffers_bind_group(
device,
&bind_group_layout,
&[&request_count, &sorted_requests],
&[&request_count, &sorted_requests, &request_counts_pages],
Some("CacheRequestHandler::bind_group"),
);
@@ -299,7 +299,7 @@ impl<const N: usize> CacheRequestHandler<N>
{
create_multi_buffers_bind_group_layout(
device,
2,
3,
Some("CacheRequestHandler::bind_group_layout"),
)
}
@@ -390,14 +390,16 @@ impl CacheRequestBuffer
&self.bind_group
}
pub fn host_download_requests<F: FnMut(&[RequestInformation]) + Send + Sync + 'static>(
pub fn host_download_requests<
F: FnMut(&[RequestInformation], &[RequestMeta]) + Send + Sync + 'static,
>(
&self,
device: &Device,
queue: &wgpu::Queue,
callback: F,
)
{
// Once the two required buffer have been mapped, the requestMapState will automatically
// Once the three required buffers have been mapped, the requestMapState will automatically
// fire the callback
let request_map_state = Arc::new(Mutex::new(RequestMapState::new(callback)));
@@ -433,33 +435,58 @@ impl CacheRequestBuffer
.set_request_infos(request_infos);
},
);
let request_map_state_3 = request_map_state.clone();
wgpu::util::DownloadBuffer::read_buffer(
device,
queue,
&self.request_meta.slice(..),
move |buffer| {
let mapped_buffer = buffer.expect("Could not map request buffer (meta).");
let request_metas: Vec<RequestMeta> =
bytemuck::pod_collect_to_vec(&mapped_buffer);
request_map_state_3
.lock()
.unwrap()
.set_request_metas(request_metas);
},
);
}
}
struct RequestMapState<F: FnMut(&[RequestInformation]) -> () + Send + Sync + 'static>
struct RequestMapState<F: FnMut(&[RequestInformation], &[RequestMeta]) + Send + Sync + 'static>
{
request_count: Option<usize>,
request_infos: Option<Vec<RequestInformation>>,
request_metas: Option<Vec<RequestMeta>>,
callback: F,
}
impl<F: FnMut(&[RequestInformation]) -> () + Send + Sync + 'static> RequestMapState<F>
impl<F: FnMut(&[RequestInformation], &[RequestMeta]) + Send + Sync + 'static> RequestMapState<F>
{
pub fn new(callback: F) -> Self
{
Self {
request_count: None,
request_infos: None,
request_metas: None,
callback,
}
}
fn try_callback(&mut self)
{
if let (Some(request_count), Some(request_infos)) =
(self.request_count, &self.request_infos)
if let (Some(request_count), Some(request_infos), Some(request_metas)) = (
self.request_count,
&self.request_infos,
&self.request_metas,
)
{
(self.callback)(&request_infos[0..request_count])
(self.callback)(
&request_infos[0..request_count],
&request_metas[0..request_count],
)
}
}
@@ -474,4 +501,10 @@ impl<F: FnMut(&[RequestInformation]) -> () + Send + Sync + 'static> RequestMapSt
self.request_infos = Some(request_infos);
self.try_callback();
}
pub fn set_request_metas(&mut self, request_metas: Vec<RequestMeta>)
{
self.request_metas = Some(request_metas);
self.try_callback();
}
}
+108
View File
@@ -110,6 +110,9 @@ pub struct LocationPage
/// Identifier for locating this particular node within the structure
pub node_id: u32,
/// Identifier of the producer that owns this node
pub producer_id: u32,
}
/// Page storing the depth of the current node related to its root.
@@ -150,6 +153,12 @@ pub struct RequestInformation
/// The index of the children on which the request was issued
pub children_index: u32,
/// Identifier of the producer that owns the requesting node
pub producer_id: u32,
/// The amount of times this request was emitted this frame. Higher means more urgent.
pub demand: u32,
}
/// Metainformation kept along each request, to know which node made the demand
@@ -168,6 +177,105 @@ pub struct RequestMeta
pub depth: u32,
}
/// Sentinel used in [`RequestMeta::page_index`] and [`InsertionParent::page_index`] to mark a
/// request/insertion that has no cache parent (an external root requested by a structure table).
pub const NO_PARENT_PAGE: u32 = u32::MAX;
/// Kind of parent an insertion is attached to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Zeroable, Pod)]
#[repr(transparent)]
pub struct InsertionParentKind(u32);
impl InsertionParentKind
{
/// The new page is a child of a resident cache page.
pub const INTERNAL: Self = Self(0);
/// The new page is the root of a structure owned by a structure table.
pub const EXTERNAL: Self = Self(1);
pub fn raw(self) -> u32
{
self.0
}
}
/// Identity and attachment point of the page being inserted.
///
/// This makes an insertion batch self-describing: the GPU can validate that the parent is still
/// the node the request was issued on, and link the new page without reading the request buffer.
#[derive(Clone, Copy, Debug, Zeroable, Pod)]
#[repr(C)]
pub struct InsertionParent
{
/// [`InsertionParentKind`].
pub kind: u32,
/// Cache page of the parent. [`NO_PARENT_PAGE`] for external roots.
pub page_index: u32,
/// Child slot inside the parent. `0` for external roots.
pub children_index: u32,
/// Depth of the parent. [`NO_PARENT_PAGE`] for external roots.
pub depth: u32,
/// Structure the parent belongs to.
pub structure_id: u32,
/// Locator of the parent inside the structure. `0` for external roots.
pub node_id: u32,
/// Producer that owns the parent.
pub producer_id: u32,
}
impl InsertionParent
{
/// Parent information for a child of a resident cache page.
pub fn internal(
meta: &RequestMeta,
structure_id: u32,
node_id: u32,
producer_id: u32,
) -> Self
{
Self {
kind: InsertionParentKind::INTERNAL.raw(),
page_index: meta.page_index,
children_index: meta.children_index,
depth: meta.depth,
structure_id,
node_id,
producer_id,
}
}
/// Parent information for the root of an external structure.
pub fn external(structure_id: u32, producer_id: u32) -> Self
{
Self {
kind: InsertionParentKind::EXTERNAL.raw(),
page_index: NO_PARENT_PAGE,
children_index: 0,
depth: NO_PARENT_PAGE,
structure_id,
node_id: 0,
producer_id,
}
}
pub fn is_external(&self) -> bool
{
self.kind == InsertionParentKind::EXTERNAL.raw()
}
pub fn is_internal(&self) -> bool
{
self.kind == InsertionParentKind::INTERNAL.raw()
}
}
/// Structure information about the children of a node.
/// Used when inserting data in the cache, to setup structure pointers
///
+20 -1
View File
@@ -9,7 +9,9 @@ struct RequestInformation
{
structure_id: u32,
node_id: u32,
children_index: u32
children_index: u32,
producer_id: u32,
demand: u32
}
struct RequestMeta
@@ -19,6 +21,22 @@ struct RequestMeta
depth: u32
}
// No cache parent (external root insertion).
const NO_PARENT_PAGE: u32 = 0xFFFFFFFFu;
const INSERTION_PARENT_INTERNAL: u32 = 0u;
const INSERTION_PARENT_EXTERNAL: u32 = 1u;
struct InsertionParent
{
kind: u32,
page_index: u32,
children_index: u32,
depth: u32,
structure_id: u32,
node_id: u32,
producer_id: u32,
}
struct AttributeArray
{
values: array<u32>
@@ -28,6 +46,7 @@ struct LocationPage
{
structure_id: u32,
node_id: u32,
producer_id: u32,
}
fn child_information_occupied(info: u32) -> bool
@@ -6,27 +6,46 @@
@group(1) @binding(1) var<storage, read_write> insertion_data_information: array<u32>; // UNUSED
@group(1) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
@group(1) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
@group(1) @binding(4) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
@group(1) @binding(4) var<storage, read_write> insertion_data_parents: array<InsertionParent>;
@group(1) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
@group(1) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
/// Group 2: Request buffer
@group(2) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
@group(2) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
@group(2) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
@compute
@workgroup_size(256, 1, 1)
fn insertion(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
if(index >= insertion_data_page_count_buffer)
let entry_count = min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents));
if(index >= entry_count)
{
return;
}
let parent = insertion_data_parents[index];
if(parent.kind != INSERTION_PARENT_EXTERNAL)
{
return;
}
let destination = insertion_data_destination_indices[index];
if(destination != 0xFFFFFFFF)
if(destination == DESTINATION_NONE)
{
let request_location = request_buffer_informations[index].structure_id;
fixed_table_pointers[request_location] = child_pointer_make_available(insertion_data_destination_indices[index]);
return;
}
if(parent.structure_id >= arrayLength(&fixed_table_pointers))
{
return;
}
// Re-check that the slot is still waiting for this root.
let pointer = fixed_table_pointers[parent.structure_id];
if(!child_pointer_subdivided(pointer) || child_pointer_available(pointer))
{
return;
}
fixed_table_pointers[parent.structure_id] = child_pointer_make_available(destination);
}
@@ -0,0 +1,56 @@
// Group 0: Table pointers
@group(0) @binding(0) var<storage, read_write> fixed_table_pointers: array<u32>;
// Group 1: Cache insertion data
@group(1) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
@group(1) @binding(1) var<storage, read_write> insertion_data_information: array<u32>; // UNUSED
@group(1) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
@group(1) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
@group(1) @binding(4) var<storage, read_write> insertion_data_parents: array<InsertionParent>;
@group(1) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
@group(1) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
/// Validates external root insertions against the structure table.
///
/// A root is still wanted while its table slot is subdivisible but not yet
/// available. Slots that were already satisfied (or whose structure was
/// invalidated before the request was dispatched) are dropped here, before the
/// cache allocates any page for them.
@compute
@workgroup_size(256, 1, 1)
fn validate_external(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
let entry_count = min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents));
if(index >= entry_count)
{
return;
}
let parent = insertion_data_parents[index];
// Reset every destination; only validated entries that are allocated get a
// page written back by the cache insertion pass.
insertion_data_destination_indices[index] = DESTINATION_NONE;
if(parent.kind != INSERTION_PARENT_EXTERNAL)
{
return;
}
if(parent.structure_id >= arrayLength(&fixed_table_pointers))
{
return;
}
let pointer = fixed_table_pointers[parent.structure_id];
if(!child_pointer_subdivided(pointer) || child_pointer_available(pointer))
{
return;
}
let slot = atomicAdd(&insertion_data_valid_count, 1u);
insertion_data_valid_indices[slot] = index;
}
@@ -1,12 +1,15 @@
/// Group 0: Cache request handler
@group(0) @binding(0) var<storage, read_write> request_handler_count: u32; // Request count
@group(0) @binding(1) var<storage, read_write> request_handler_requests: array<u32>;
@group(0) @binding(2) var<storage, read_write> request_handler_counts: array<u32>;
/// Group 1: Request buffer
@group(1) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
@group(1) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
@group(1) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
var<immediate> table_producer_id: u32;
@compute
@workgroup_size(256, 1, 1)
fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
@@ -18,13 +21,18 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
return;
}
let structure_id = request_handler_requests[index];
var request_info: RequestInformation;
request_info.structure_id = request_handler_requests[index];
request_info.structure_id = structure_id;
request_info.node_id = 0;
request_info.children_index = 0;
request_info.producer_id = table_producer_id;
request_info.demand = request_handler_counts[structure_id];
var request_meta: RequestMeta;
request_meta.page_index = 0;
// External requests have no parent page.
request_meta.page_index = 0xFFFFFFFF;
request_meta.children_index = 0;
// u32s wrap arround
request_meta.depth = 0xFFFFFFFF;
+103 -25
View File
@@ -12,7 +12,10 @@
@group(2) @binding(1) var<storage, read_write> insertion_data_information: array<InsertionInformation>;
@group(2) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
@group(2) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
@group(2) @binding(4) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
@group(2) @binding(4) var<storage, read_write> insertion_data_parents: array<InsertionParent>;
@group(2) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
@group(2) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
@group(2) @binding(7) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
// Group 3: Cache evictor
@group(3) @binding(0) var<storage, read_write> cache_evictor_timestamps: array<u32>;
@@ -24,13 +27,79 @@
var<immediate> new_timestamp: u32;
// Computes amount of available LRU pages
fn available_amount() -> u32
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
fn insertion_entry_count() -> u32
{
return min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents));
}
/// Checks that the parent page still holds the node the request was issued on,
/// and that the requested child slot is still waiting for a page.
fn internal_parent_is_valid(parent: InsertionParent) -> bool
{
if(parent.page_index >= PAGE_COUNT)
{
return false;
}
let location = structure_location_pages[parent.page_index];
if(location.structure_id != parent.structure_id ||
location.node_id != parent.node_id ||
location.producer_id != parent.producer_id)
{
return false;
}
if(structure_depth_pages[parent.page_index] != parent.depth)
{
return false;
}
let pointer = structure_pointer_pages[parent.page_index].pointers[parent.children_index];
return child_pointer_subdivided(pointer) && !child_pointer_available(pointer);
}
/// Validates a batch of internal insertions and compacts the valid ones into
/// `insertion_data_valid_indices`.
///
/// This must run before page allocation so that stale insertions never consume
/// an evicted page. External roots are validated by the structure table that
/// requested them (see `fixed_table/validate_insertion.wgsl`).
@compute
@workgroup_size(256, 1, 1)
fn validate_internal(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
if(index >= insertion_entry_count())
{
return;
}
let parent = insertion_data_parents[index];
// Reset the destination of every entry. Only entries compacted into
// `valid_indices` and actually allocated by the insertion pass get a page;
// this keeps invalid/stale insertions from reusing a previous batch's
// destination if the host did not pre-fill the buffer.
insertion_data_destination_indices[index] = DESTINATION_NONE;
if(parent.kind != INSERTION_PARENT_INTERNAL)
{
return;
}
if(internal_parent_is_valid(parent))
{
let slot = atomicAdd(&insertion_data_valid_count, 1u);
insertion_data_valid_indices[slot] = index;
}
}
fn available_amount(valid_count: u32) -> u32
{
let lru_remaining = arrayLength(&cache_evictor_timestamps) - cache_evictor_consumed_count;
let available_amount = min(lru_remaining, insertion_data_page_count_buffer);
return available_amount;
return min(lru_remaining, valid_count);
}
@compute
@@ -38,7 +107,7 @@ fn available_amount() -> u32
fn consume(@builtin(global_invocation_id) gid: vec3<u32>)
{
// Report consumed amount of LRU pages to cache evictor
// So that subsequent insertions can can continue to use new pages
// So that subsequent insertions can can continue to use new pages
cache_evictor_consumed_count += atomicLoad(&pass_inserted_count);
atomicStore(&pass_inserted_count, 0);
}
@@ -47,48 +116,57 @@ fn consume(@builtin(global_invocation_id) gid: vec3<u32>)
@workgroup_size(256, 1, 1)
fn insertion(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
//let insertion_count = min(array_length(&insertion_data_information), insertion_data_page_count_buffer);
let insertion_count = available_amount();
if(index >= insertion_data_page_count_buffer)
let slot = gid.x;
let entry_count = insertion_entry_count();
if(slot >= entry_count)
{
return;
}
if(index >= insertion_count)
{
// Report that page was not written
insertion_data_destination_indices[index] = 0xFFFFFFFF;
return;
let valid_count = atomicLoad(&insertion_data_valid_count);
if(slot >= valid_count)
{
return;
}
// Compacted entry index in the host-provided arrays.
let index = insertion_data_valid_indices[slot];
let insertion_count = available_amount(valid_count);
if(slot >= insertion_count)
{
// Report that page was not written. The host also pre-fills the whole
// destination array with DESTINATION_NONE, so this is defensive.
insertion_data_destination_indices[index] = DESTINATION_NONE;
return;
}
// Get a page to evict
let page_index = cache_evictor_lru_pages[index + cache_evictor_consumed_count];
let page_index = cache_evictor_lru_pages[slot + cache_evictor_consumed_count];
let page_timestamp = cache_evictor_timestamps[page_index];
if(page_timestamp >= new_timestamp - 1)
{
// Do not insert page
insertion_data_destination_indices[index] = 0xFFFFFFFF;
return;
insertion_data_destination_indices[index] = DESTINATION_NONE;
return;
}
atomicAdd(&pass_inserted_count, 1);
insertion_data_destination_indices[index] = page_index;
// Copy new location
structure_location_pages[page_index] = insertion_data_location_pages[index];
structure_location_pages[page_index] = insertion_data_location_pages[index];
// Copy new pointers
let new_pointers = insertion_info_to_pointer_page(insertion_data_information[index]);
structure_pointer_pages[page_index] = new_pointers;
structure_pointer_pages[page_index] = new_pointers;
// Mark page as dirty for invalidation
cache_evictor_timestamps[page_index] = new_timestamp;
// Set default depth
structure_depth_pages[page_index] = 0;
// Set default depth. `write_pointers` refines it for internal insertions.
structure_depth_pages[page_index] = 0;
// Copy attributes
for(var attribute_index = u32(0); attribute_index < ATTRIBUTE_COUNT; attribute_index ++)
@@ -116,7 +194,7 @@ fn insertion_info_to_pointer_page(info: InsertionInformation) -> PointerPage
var occupancy_low = u32(0);
var occupancy_high = u32(0);
for(var i = u32(0); i < CHILDREN_COUNT; i++)
for(var i = u32(0); i < CHILDREN_COUNT; i++)
{
let insert_info = info.children[i];
+48 -21
View File
@@ -3,34 +3,61 @@
@group(0) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
@group(0) @binding(2) var<storage, read_write> structure_depth_pages: array<u32>;
/// Group 1: Request buffer
@group(1) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
@group(1) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
@group(1) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
// Group 1: Cache insertion data
@group(1) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
@group(1) @binding(1) var<storage, read_write> insertion_data_information: array<InsertionInformation>;
@group(1) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
@group(1) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
@group(1) @binding(4) var<storage, read_write> insertion_data_parents: array<InsertionParent>;
@group(1) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
@group(1) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
@group(1) @binding(7) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
// Group 2: Cache insertion data
@group(2) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
@group(2) @binding(1) var<storage, read_write> insertion_data_information: array<InsertionInformation>;
@group(2) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
@group(2) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
@group(2) @binding(4) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
/// Links inserted pages into their parent, using only the insertion batch's own
/// parent description. No request buffer is involved, so a batch may be
/// produced on a different frame than the one that emitted the requests.
@compute
@workgroup_size(256, 1, 1)
fn write_pointers(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
if(index >= request_buffer_count || index >= insertion_data_page_count_buffer) { return; }
// The write pages pass establishes a one-to-one corresepondancy
// between requests and recycled pages
let meta_inf = request_buffer_meta[index];
let page_index = insertion_data_destination_indices[index];
if(page_index != 0xFFFFFFFF)
let entry_count = min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents));
if(index >= entry_count)
{
structure_pointer_pages[meta_inf.page_index].pointers[meta_inf.children_index]
= child_pointer_make_available(page_index);
structure_depth_pages[page_index] = meta_inf.depth + 1;
return;
}
let parent = insertion_data_parents[index];
if(parent.kind != INSERTION_PARENT_INTERNAL)
{
return;
}
let page_index = insertion_data_destination_indices[index];
if(page_index == DESTINATION_NONE)
{
return;
}
// The parent page may have been recycled while this insertion batch was in
// flight. Only link if it still describes the same node, and never link a
// page to itself.
if(parent.page_index >= PAGE_COUNT || parent.page_index == page_index)
{
return;
}
let location = structure_location_pages[parent.page_index];
if(location.structure_id != parent.structure_id ||
location.node_id != parent.node_id ||
location.producer_id != parent.producer_id)
{
return;
}
structure_pointer_pages[parent.page_index].pointers[parent.children_index]
= child_pointer_make_available(page_index);
structure_depth_pages[page_index] = parent.depth + 1;
}
@@ -8,6 +8,7 @@
/// Group 1: Cache request handler
@group(1) @binding(0) var<storage, read_write> request_handler_count: u32; // Request count
@group(1) @binding(1) var<storage, read_write> request_handler_requests: array<u32>;
@group(1) @binding(2) var<storage, read_write> request_handler_counts: array<u32>;
/// Group 3: Request buffer
@group(2) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
@@ -35,6 +36,8 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
request_information.structure_id = structure_location_pages[page_index].structure_id;
request_information.node_id = structure_location_pages[page_index].node_id;
request_information.children_index = request_location.children_index;
request_information.producer_id = structure_location_pages[page_index].producer_id;
request_information.demand = request_handler_counts[request_index];
// Fill out request meta information
var request_meta: RequestMeta;
+56 -8
View File
@@ -47,10 +47,14 @@ pub struct FixedStructureTable
common_ressources: CacheRessources<1>,
request_handler: CacheRequestHandler<1>,
/// Producer that owns the root structures stored by this table
producer_id: u32,
// To dispatch write request passes per request count
indirect_buffer: IndirectBuffer1D,
write_requests_pass: wgpu::ComputePipeline,
invalidation_pass: wgpu::ComputePipeline,
validation_pass: wgpu::ComputePipeline,
insertion_pass: wgpu::ComputePipeline,
// Raytrace
@@ -60,7 +64,12 @@ pub struct FixedStructureTable
impl FixedStructureTable
{
pub fn new(device: &wgpu::Device, size: usize, max_requests: usize) -> Self
pub fn new(
device: &wgpu::Device,
size: usize,
max_requests: usize,
producer_id: u32,
) -> Self
{
let pointer = CachePointer::new(Some(None));
let pointers = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
@@ -98,7 +107,7 @@ impl FixedStructureTable
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("FixedStructureTable::pipeline_layout"),
bind_group_layouts: &write_requests_bindings,
immediate_size: 0,
immediate_size: size_of::<u32>() as u32,
});
let write_requests_shader_module = device.create_shader_module(include_table_wgsl!(
@@ -153,7 +162,6 @@ impl FixedStructureTable
Some(&CacheInsertionData::<1>::create_bind_group_layout(
device, None,
)),
Some(&CacheRequestBuffer::create_bind_group_layout(device)),
];
let insertion_pipeline_layout =
@@ -175,15 +183,30 @@ impl FixedStructureTable
cache: None,
});
let validation_shader_module = device.create_shader_module(include_table_wgsl!(
"./shaders/fixed_table/validate_insertion.wgsl"
));
let validation_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("FixedStructureTable::validation_pass"),
layout: Some(&insertion_pipeline_layout),
module: &validation_shader_module,
entry_point: Some("validate_external"),
compilation_options: Default::default(),
cache: None,
});
Self {
size,
pointers,
pointers_bind_group,
common_ressources,
request_handler,
producer_id,
indirect_buffer: IndirectBuffer1D::new(device),
write_requests_pass,
invalidation_pass,
validation_pass,
insertion_pass,
raytrace_bind_group,
@@ -229,10 +252,10 @@ impl FixedStructureTable
timestamp_writes: None,
});
write_requests_pass.set_pipeline(&self.write_requests_pass);
write_requests_pass.set_bind_group(0, self.request_handler.bind_group(), &[]);
write_requests_pass.set_bind_group(1, request_buffer.bind_group(), &[]);
write_requests_pass.set_pipeline(&self.write_requests_pass);
write_requests_pass.set_immediates(0, bytemuck::bytes_of(&self.producer_id));
write_requests_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0);
}
@@ -249,7 +272,6 @@ impl FixedStructureTable
device: &wgpu::Device,
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
insertion: &CacheInsertionData<N>,
request: &CacheRequestBuffer,
) where
[(); N * N * N]:,
{
@@ -268,7 +290,6 @@ impl FixedStructureTable
insertion_pass.set_bind_group(0, &self.pointers_bind_group, &[]);
insertion_pass.set_bind_group(1, insertion.bind_group_no_attributes(), &[]);
insertion_pass.set_bind_group(2, request.bind_group(), &[]);
insertion_pass.set_pipeline(&self.insertion_pass);
insertion_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0);
@@ -296,8 +317,35 @@ impl FixedStructureTable
}
}
impl CacheInvalidable for FixedStructureTable
impl<const N: usize> CacheInvalidable<N> for FixedStructureTable
where
[(); N * N * N]:,
{
fn validate_insertion(
&mut self,
device: &wgpu::Device,
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
insertion: &CacheInsertionData<N>,
) {
let workgroup_count_buffer = self.indirect_buffer.workgroup_count(
device,
encoder,
insertion.page_count_buffer(),
256,
);
let mut validate_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("FixedStructureTable::validate_pass"),
timestamp_writes: None,
});
validate_pass.set_bind_group(0, &self.pointers_bind_group, &[]);
validate_pass.set_bind_group(1, insertion.bind_group_no_attributes(), &[]);
validate_pass.set_pipeline(&self.validation_pass);
validate_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0);
}
fn invalidate(
&mut self,
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,