From 92d61b75a85ba6b761f57b54950d90a99d8556d8 Mon Sep 17 00:00:00 2001 From: Albin Chaboissier Date: Mon, 19 Oct 2026 23:14:26 +0200 Subject: [PATCH] Cache pipelines --- src/gpu.rs | 1 + src/gpu/indirect_buffer.rs | 166 +++++++++ src/voxel_cache.rs | 106 +++++- src/voxel_cache/attributes.rs | 40 +- src/voxel_cache/eviction.rs | 28 ++ src/voxel_cache/insertion.rs | 206 +++++++++++ src/voxel_cache/layout.rs | 55 ++- src/voxel_cache/pipelines.rs | 388 ++++++++++++++++++++ src/voxel_cache/requests.rs | 82 ++++- src/voxel_cache/schema.rs | 62 +++- src/voxel_cache/shaders/cache_common.wgsl | 97 +++++ src/voxel_cache/shaders/insertion.wgsl | 99 +++++ src/voxel_cache/shaders/invalidation.wgsl | 52 +++ src/voxel_cache/shaders/write_pointers.wgsl | 29 ++ src/voxel_cache/shaders/write_requests.wgsl | 50 +++ src/voxel_cache/structure.rs | 70 +--- 16 files changed, 1452 insertions(+), 79 deletions(-) create mode 100644 src/gpu/indirect_buffer.rs create mode 100644 src/voxel_cache/insertion.rs create mode 100644 src/voxel_cache/pipelines.rs create mode 100644 src/voxel_cache/shaders/cache_common.wgsl create mode 100644 src/voxel_cache/shaders/insertion.wgsl create mode 100644 src/voxel_cache/shaders/invalidation.wgsl create mode 100644 src/voxel_cache/shaders/write_pointers.wgsl create mode 100644 src/voxel_cache/shaders/write_requests.wgsl diff --git a/src/gpu.rs b/src/gpu.rs index 793750a..b64f630 100644 --- a/src/gpu.rs +++ b/src/gpu.rs @@ -1,3 +1,4 @@ // Main common gpu parallel algorithms pub mod buffer_compactor; +pub mod indirect_buffer; pub mod radix_sort; diff --git a/src/gpu/indirect_buffer.rs b/src/gpu/indirect_buffer.rs new file mode 100644 index 0000000..6427e12 --- /dev/null +++ b/src/gpu/indirect_buffer.rs @@ -0,0 +1,166 @@ +use wgpu::Buffer; +use wgpu::CommandEncoder; + +/// Provides utility object to manage indirect dispatches workgroup count computations on the GPU + +/// Takes in a single u32, and computes the amount of workgroups to dispatch given a workgroup size +pub struct IndirectBuffer1D +{ + /// Buffer used in the indirect dispatch command + indirect_buffer: wgpu::Buffer, + + /// Buffer visible from compute shaders to compute the amount + indirect_storage: wgpu::Buffer, + indirect_storage_bind_group: wgpu::BindGroup, + + bind_group_layout: wgpu::BindGroupLayout, + compute_pipeline: wgpu::ComputePipeline, +} + +impl IndirectBuffer1D +{ + pub fn new(device: &wgpu::Device) -> Self + { + let indirect_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("IndirectBuffer1D::indirect_buffer"), + size: size_of::() as u64, + usage: wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + + let indirect_storage = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("IndirectBuffer1D::indirect_storage"), + size: size_of::() as u64, + usage: wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::COPY_SRC, + mapped_at_creation: false, + }); + + let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("IndirectBuffer1D::bind_group_layout"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: false }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }], + }); + + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("IndirectBuffer1D::bind_group"), + layout: &bind_group_layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: indirect_storage.as_entire_binding(), + }], + }); + + let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("IndirectBuffer1D::shader_module"), + source: wgpu::ShaderSource::Wgsl( + " + struct IndirectDispatchArgs + { + x: u32, + y: u32, + z: u32 + } + + @group(0) @binding(0) indirect_storage: IndirectDispatchArgs; + @group(1) @binding(0) user_count: u32; + + var workgroup_size: u32; + + @compute + @workgroup_size(1, 1, 1) + fn main() + { + let workgroup_count = (user_count / workgroup_size) + select(user_count % workgroup_size == 0, u32(0), u32(1)); + + var args: IndirectDispatchArgs; + args.x = workgroup_count; + args.y = 1; + args.z = 1; + indirect_storage = args; + } + ".into(), + ), + }); + + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("IndirectBuffer1D::pipeline_layout"), + bind_group_layouts: &[ + // Group 0: indirect args buffer + Some(&bind_group_layout), + // Group 1: user count buffer + Some(&bind_group_layout), + ], + + // workgroup size + immediate_size: size_of::() as u32, + }); + + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("IndirectBuffer1D::pipeline"), + layout: Some(&pipeline_layout), + module: &shader_module, + entry_point: Some("main"), + compilation_options: Default::default(), + cache: None, + }); + + Self { + indirect_buffer, + indirect_storage, + indirect_storage_bind_group: bind_group, + bind_group_layout, + compute_pipeline: pipeline, + } + } + + pub fn workgroup_count( + &self, + device: &wgpu::Device, + encoder: &mut CommandEncoder, + count_buffer: &Buffer, + workgroup_size: usize, + ) -> &Buffer + { + // Transient bind group + let user_count_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("IndirectBuffer1D::bind_group"), + layout: &self.bind_group_layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: count_buffer.as_entire_binding(), + }], + }); + + { + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("IndirectBuffer1D::compute_pass"), + timestamp_writes: None, + }); + + pass.set_pipeline(&self.compute_pipeline); + pass.set_bind_group(0, &self.indirect_storage_bind_group, &[]); + pass.set_bind_group(1, &user_count_bind_group, &[]); + pass.set_immediates(0, bytemuck::bytes_of(&workgroup_size)); + + pass.dispatch_workgroups(1, 1, 1); + } + + encoder.copy_buffer_to_buffer( + &self.indirect_storage, + 0, + &self.indirect_buffer, + 0, + Some(self.indirect_storage.size()), + ); + + &self.indirect_buffer + } +} diff --git a/src/voxel_cache.rs b/src/voxel_cache.rs index dd23223..832800b 100644 --- a/src/voxel_cache.rs +++ b/src/voxel_cache.rs @@ -1,13 +1,26 @@ +use wgpu::CommandEncoder; use wgpu::Device; use crate::gpu::radix_sort::RadixSorter; +use crate::gpu_profiler; +use crate::gpu_profiler::ScopeEncoder; +use crate::voxel_cache::attributes::CacheAttributes; use crate::voxel_cache::eviction::CacheEvictor; +use crate::voxel_cache::insertion::CacheInsertionData; +use crate::voxel_cache::layout::CacheLayout; +use crate::voxel_cache::pipelines::CacheInsertionPass; +use crate::voxel_cache::pipelines::CacheInvalidationPass; +use crate::voxel_cache::pipelines::WritePointersPass; +use crate::voxel_cache::pipelines::WriteRequestsPass; +use crate::voxel_cache::requests::CacheRequestBuffer; use crate::voxel_cache::requests::CacheRequestHandler; use crate::voxel_cache::structure::CacheStructure; pub mod attributes; pub mod eviction; +pub mod insertion; pub mod layout; +pub mod pipelines; pub mod requests; pub mod schema; pub mod structure; @@ -45,31 +58,120 @@ where { page_count: usize, structure: CacheStructure, + attributes: CacheAttributes, request_handler: CacheRequestHandler, evictor: CacheEvictor, common_ressources: CacheRessources, + + // Operations + write_requests_pass: WriteRequestsPass, + cache_insertion_pass: CacheInsertionPass, + cache_invalidation_pass: CacheInvalidationPass, + write_pointers_pass: WritePointersPass, + + frame_timestamp: u32, +} + +pub struct VoxelCacheWriter<'cache, const N: usize> +where + [(); N * N * N]:, +{ + cache: &'cache mut VoxelCache, } impl VoxelCache where [(); N * N * N]:, { - pub fn new(device: &Device, page_count: usize) -> Self + pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self { let structure = CacheStructure::new(device, page_count); + let attributes = CacheAttributes::from_cache_layout(device, layout, page_count); let request_handler = CacheRequestHandler::new(device, page_count); let evictor = CacheEvictor::new(device, page_count, 0u32); let common_ressources = CacheRessources::new(device, page_count); + let write_requests_pass = WriteRequestsPass::new(device, page_count, layout); + let cache_insertion_pass = CacheInsertionPass::new(device, page_count, layout); + let cache_invalidation_pass = CacheInvalidationPass::new(device, page_count, layout); + let write_pointers_pass = WritePointersPass::new(device, page_count, layout); + Self { page_count, structure, + attributes, request_handler, evictor, common_ressources, + + write_requests_pass, + cache_insertion_pass, + cache_invalidation_pass, + write_pointers_pass, + + frame_timestamp: 0, } } + + pub fn gather_requests( + &self, + device: &Device, + encoder: &mut ScopeEncoder, + request_buffer: &CacheRequestBuffer, + ) + { + gpu_profiler::begin_scope!(encoder, "gather_requests"); + + self.request_handler + .sort_requests(device, &self.common_ressources, &mut encoder); + self.evictor + .prepare_eviction_list(device, &self.common_ressources, &mut encoder); + + self.write_requests_pass.encode( + &mut encoder, + device, + &self.structure, + &self.request_handler, + request_buffer, + ); + } + + pub fn write_invalidate)>( + &mut self, + encoder: &mut ScopeEncoder, + mut write_ops: F, + ) + { + let writer = VoxelCacheWriter { cache: self }; + write_ops(&writer); + + self.cache_invalidation_pass.encode( + encoder, + &self.structure, + &self.evictor, + self.frame_timestamp, + ); + } + + pub fn write_pointers( + &self, + device: &Device, + encoder: &mut ScopeEncoder, + request_buffer: &CacheRequestBuffer, + insertion: &CacheInsertionData, + ) + { + gpu_profiler::begin_scope!(encoder, "insert_pages"); + + self.write_pointers_pass.encode( + &mut encoder, + device, + &self.structure, + request_buffer, + &self.evictor, + ); + } } // Utilities @@ -123,7 +225,7 @@ fn create_multi_buffers_bind_group( fn create_multi_buffers_bg_bg_layout( device: &Device, - buffers: &[&Buffer], + buffers: &[&wgpu::Buffer], label: Option<&str>, ) -> (wgpu::BindGroupLayout, wgpu::BindGroup) { diff --git a/src/voxel_cache/attributes.rs b/src/voxel_cache/attributes.rs index 00c51c1..7f64370 100644 --- a/src/voxel_cache/attributes.rs +++ b/src/voxel_cache/attributes.rs @@ -1,3 +1,5 @@ +use wgpu::BindGroupLayout; + use crate::voxel_cache::layout::CacheLayout; /// Contains instanciated gpu buffers to hold data for cache attributes @@ -20,22 +22,7 @@ impl CacheAttributes .map(|attribute| attribute.create_buffer(device, N, page_count)) .collect::>(); - let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("CacheAttributes::bind_group_layout"), - entries: &[wgpu::BindGroupLayoutEntry { - binding: 1, - visibility: wgpu::ShaderStages::COMPUTE, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: false }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: Some( - std::num::NonZero::new(attribute_buffers.len() as u32) - .expect("Cannot create cache attributes with no attributes"), - ), - }], - }); + let bind_group_layout = Self::create_bind_group_layout(device, layout); let bind_group_bindings = attribute_buffers .iter() @@ -58,6 +45,27 @@ impl CacheAttributes } } + pub fn create_bind_group_layout(device: &wgpu::Device, layout: &CacheLayout) + -> BindGroupLayout + { + let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("CacheAttributes::bind_group_layout"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: false }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: Some( + std::num::NonZero::new(layout.attributes.len() as u32) + .expect("Cannot create cache attributes with no attributes"), + ), + }], + }); + } + pub fn bind_group_layout(&self) -> &wgpu::BindGroupLayout { &self.bind_group_layout diff --git a/src/voxel_cache/eviction.rs b/src/voxel_cache/eviction.rs index 6ff92a9..775ea73 100644 --- a/src/voxel_cache/eviction.rs +++ b/src/voxel_cache/eviction.rs @@ -1,5 +1,6 @@ /// Contains structure and logic related to eviction logic in the cache. use wgpu::BindGroup; +use wgpu::BindGroupLayout; use wgpu::CommandEncoder; use wgpu::ComputePipeline; use wgpu::include_wgsl; @@ -10,6 +11,8 @@ use crate::gpu_profiler::ScopeEncoder; use crate::gpu_profiler::{self}; use crate::voxel_cache::CacheRessources; use crate::voxel_cache::create_multi_buffers_bg_bg_layout; +use crate::voxel_cache::create_multi_buffers_bind_group; +use crate::voxel_cache::create_multi_buffers_bind_group_layout; /// Retains usage information about pages in the cache under the form of timestamps. /// Produces a list of LRU eviction order, from which the cache can pull pages to recycle @@ -27,6 +30,10 @@ pub struct CacheEvictor reset_lru_list_bind_group: BindGroup, reset_lru_list_pass: ComputePipeline, reset_lru_list_dispatch: u32, + + // For external passes + bind_group_layout: BindGroupLayout, + bind_group: BindGroup, } impl CacheEvictor @@ -70,6 +77,14 @@ impl CacheEvictor cache: None, }); + let bind_group_layout = Self::create_bind_group_layout(device); + let bind_group = create_multi_buffers_bind_group( + device, + &bind_group_layout, + &[×tamp_pages, &lru_list], + Some("CacheEvictor::bind_group"), + ); + Self { page_count, timestamp_pages, @@ -78,6 +93,9 @@ impl CacheEvictor reset_lru_list_bind_group, reset_lru_list_pass, reset_lru_list_dispatch: page_count.div_ceil(256) as u32, + + bind_group_layout, + bind_group, } } @@ -120,4 +138,14 @@ impl CacheEvictor radix_sort::RadixSortDirection::Ascending, ); } + + pub fn bind_group(&self) -> &BindGroup + { + &self.bind_group + } + + pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout + { + create_multi_buffers_bind_group_layout(device, 2, Some("CacheEvictor::bind_group_layout")) + } } diff --git a/src/voxel_cache/insertion.rs b/src/voxel_cache/insertion.rs new file mode 100644 index 0000000..8e68e44 --- /dev/null +++ b/src/voxel_cache/insertion.rs @@ -0,0 +1,206 @@ +use std::num::NonZero; + +use wgpu::BindGroupLayout; +use wgpu::ShaderStages; + +use crate::voxel_cache::layout::CacheLayout; +use crate::voxel_cache::schema::InsertionInformation; +use crate::voxel_cache::schema::LocationPage; + +/// Data to be inserted in a cache insertion operation +pub struct CacheInsertionData +where + [(); N * N * N]:, +{ + /// The amount of pages to insert this structure can hold + max_page_count: usize, + + /// Amount of pages that the structure actually contains + page_count_buffer: wgpu::Buffer, + + /// Information about inserted pages : dense array of [`InsertionInformation`] structs + insertion_information: wgpu::Buffer, + + /// Location of the new nodes : dense array of [`LocationPage`] structs + location_pages: wgpu::Buffer, + + /// Contains the attributes to import in the cache. + attributes: Vec, + + /// Contains the indicies of the page in which the data was written + destination_indices: wgpu::Buffer, + + bind_group_layout: wgpu::BindGroupLayout, + bind_group: wgpu::BindGroup, +} + +impl CacheInsertionData +where + [(); N * N * N]:, +{ + pub fn new(device: &wgpu::Device, max_page_count: usize, layout: &CacheLayout) -> Self + { + let page_count_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("CacheInsertionData::page_count_buffer"), + usage: wgpu::BufferUsages::STORAGE, + mapped_at_creation: false, + size: size_of::() as u64, + }); + + let insertion_information = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("CacheInsertionData::insertion_information"), + usage: wgpu::BufferUsages::STORAGE, + mapped_at_creation: false, + size: (size_of::>() * max_page_count) as u64, + }); + + let location_pages = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("CacheInsertionData::location_pages"), + usage: wgpu::BufferUsages::STORAGE, + mapped_at_creation: false, + size: (size_of::() * max_page_count) as u64, + }); + + let destination_indices = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("CacheInsertionData::destination_indices"), + usage: wgpu::BufferUsages::STORAGE, + mapped_at_creation: false, + size: (size_of::() * max_page_count) as u64, + }); + + let attributes = layout + .attributes + .iter() + .map(|attribute| attribute.create_buffer(device, N, max_page_count)) + .collect::>(); + + let bind_group_bindings = attributes + .iter() + .map(|buffer| buffer.as_entire_buffer_binding()) + .collect::>(); + + let bind_group_layout = Self::create_bind_group_layout(device, layout); + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("CacheInsertionData::bind_group"), + layout: &bind_group_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: page_count_buffer.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: insertion_information.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: location_pages.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: destination_indices.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: destination_indices.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 5, + resource: wgpu::BindingResource::BufferArray(&bind_group_bindings), + }, + ], + }); + + Self { + page_count_buffer, + max_page_count, + insertion_information, + location_pages, + destination_indices, + attributes, + + bind_group_layout, + bind_group, + } + } + + pub fn create_bind_group_layout(device: &wgpu::Device, layout: &CacheLayout) + -> BindGroupLayout + { + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("CacheInsertionData::bind_group_layout"), + entries: &[ + 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, + }, + wgpu::BindGroupLayoutEntry { + binding: 4, + 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: 5, + visibility: ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: false }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: Some(NonZero::new(layout.attributes.len() as u32).unwrap()), + }, + ], + }) + } + + pub fn bind_group(&self) -> &wgpu::BindGroup + { + &self.bind_group + } + + pub fn page_count(&self) -> usize + { + self.max_page_count + } +} diff --git a/src/voxel_cache/layout.rs b/src/voxel_cache/layout.rs index 4e4f7af..9bc18af 100644 --- a/src/voxel_cache/layout.rs +++ b/src/voxel_cache/layout.rs @@ -1,7 +1,7 @@ use wgpu::BufferUsages; /// Defines how a [`VoxelCache`]'s attribute is populated upon populating a page -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CacheAttributeInit { /// Attribute is external : it is copied from the insertion operation @@ -69,4 +69,57 @@ impl CacheLayout self.attributes.push(attribute); index } + + /// Produces a wgsl declaration describing this layout : + /// + /// ```wgsl + /// + /// const ATTRIBUTE_COUNT: u32 = /* attribute count */; + /// const ATTRIBUTE_WORD_COUNTS: array = { + /// /* word count for attribute 0 */, + /// /* word count for attribute 1 */, + /// ... + /// }; + /// + /// const ATTRIBUTE_COPY: array = { + /// /* external? for attribute 0 */, + /// /* external? for attribute 1 */, + /// ... + /// }; + /// + /// ``` + pub fn wgsl_layout_decl(&self) -> String + { + let mut decl = String::new(); + + decl += &format!("const ATTRIBUTE_COUNT: u32 = {};", self.attributes.len()); + + // Word counts + decl += &format!( + "const ATTRIBUTE_WORD_COUNTS: array = {{", + self.attributes.len() + ); + + for attribute in self.attributes.iter() + { + decl += &format!(" {},", attribute.word_count); + } + + decl += "};"; + + // Copy + decl += &format!( + "const ATTRIBUTE_COPY: array = {{", + self.attributes.len() + ); + + for attribute in self.attributes.iter() + { + decl += &format!(" {},", attribute.init == CacheAttributeInit::External); + } + + decl += "};"; + + decl + } } diff --git a/src/voxel_cache/pipelines.rs b/src/voxel_cache/pipelines.rs new file mode 100644 index 0000000..e6104ae --- /dev/null +++ b/src/voxel_cache/pipelines.rs @@ -0,0 +1,388 @@ +use wgpu::CommandEncoder; +use wgpu::ComputePipeline; +use wgpu::Device; + +use crate::gpu::indirect_buffer::IndirectBuffer1D; +use crate::gpu_profiler; +use crate::gpu_profiler::ScopeEncoder; +use crate::voxel_cache::attributes::CacheAttributes; +use crate::voxel_cache::eviction::CacheEvictor; +use crate::voxel_cache::insertion::CacheInsertionData; +use crate::voxel_cache::layout::CacheLayout; +use crate::voxel_cache::requests::CacheRequestBuffer; +use crate::voxel_cache::requests::CacheRequestHandler; +use crate::voxel_cache::structure::CacheStructure; + +macro_rules! programmatic_common_wgsl { + ($children_count:ident, $page_count:ident, $cache_layout:ident) => { + format!( + " +const CHILDREN_COUNT: u32 = u32({}); +const PAGE_COUNT: u32 = u32({}); + +// Cache layout +{} + ", + $children_count, + $page_count, + $cache_layout.wgsl_layout_decl() + ) + .as_str() + }; +} + +macro_rules! include_cache_wgsl { + ($path:literal, $children_count:ident, $page_count:ident, $cache_layout:ident) => {{ + let mut full_shader = String::new(); + + full_shader.push_str(include_str!("./shaders/cache_common.wgsl")); + full_shader.push_str(programmatic_common_wgsl!( + $children_count, + $page_count, + $cache_layout + )); + full_shader.push_str(include_str!($path)); + + wgpu::ShaderModuleDescriptor { + label: Some($path), + source: wgpu::ShaderSource::Wgsl(full_shader.into()), + } + }}; +} + +pub struct WriteRequestsPass +where + [(); N * N * N]:, +{ + pipeline: ComputePipeline, + // To compute indirect dispatch count from request count + indirect_buffer: IndirectBuffer1D, +} + +impl WriteRequestsPass +where + [(); N * N * N]:, +{ + pub fn new(device: &Device, page_count: usize, cache_layout: &CacheLayout) -> Self + { + // Binds + // - structure + // - request buffer + + let bindings = [ + // To get the location information + Some(&CacheStructure::::create_bind_group_layout(device)), + // To get which pages have had a request issued on them + Some(&CacheRequestHandler::::create_bind_group_layout(device)), + // To write the request information to target + Some(&CacheRequestBuffer::create_bind_group_layout(device)), + ]; + + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("WriteRequestsPass::pipeline_layout"), + bind_group_layouts: &bindings, + immediate_size: 0, + }); + + let shader_module = device.create_shader_module(include_cache_wgsl!( + "./shaders/write_requests.wgsl", + N, + page_count, + cache_layout + )); + + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("WriteRequestsPass::pipeline"), + layout: Some(&pipeline_layout), + module: &shader_module, + entry_point: Some("write_requests"), + compilation_options: Default::default(), + cache: None, + }); + + Self { + pipeline, + indirect_buffer: IndirectBuffer1D::new(device), + } + } + + pub fn encode( + &self, + encoder: &mut ScopeEncoder, + device: &Device, + cache_structure: &CacheStructure, + cache_request_handler: &CacheRequestHandler, + target_request_buffer: &CacheRequestBuffer, + ) + { + gpu_profiler::begin_scope!(encoder, "WriteRequests"); + + let indirect_dispatch_buffer = self.indirect_buffer.workgroup_count( + device, + &mut encoder, + cache_request_handler.requset_count_buffer(), + 256, + ); + + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("WriteRequestsPass::pass"), + timestamp_writes: None, + }); + + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, cache_structure.bind_group(), &[]); + pass.set_bind_group(1, cache_request_handler.bind_group(), &[]); + pass.set_bind_group(2, target_request_buffer.bind_group(), &[]); + + pass.dispatch_workgroups_indirect(indirect_dispatch_buffer, 0); + } +} + +/// Inserts new pages in the cache +pub struct CacheInsertionPass +where + [(); N * N * N]:, +{ + pipeline: ComputePipeline, +} + +impl CacheInsertionPass +where + [(); N * N * N]:, +{ + pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self + { + // Binds + // - structure + // - request buffer + + let bindings = [ + // To write the new attributes + Some(&CacheAttributes::::create_bind_group_layout( + device, layout, + )), + // To write the new locations, pointers + Some(&CacheStructure::::create_bind_group_layout(device)), + // New incoming attributes + Some(&CacheInsertionData::::create_bind_group_layout( + device, layout, + )), + // To get recyclable pages, and mark pages dirty + Some(&CacheEvictor::create_bind_group_layout(device)), + ]; + + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("CacheInsertionPass::pipeline_layout"), + bind_group_layouts: &bindings, + immediate_size: 0, + }); + + let shader_module = device.create_shader_module(include_cache_wgsl!( + "./shaders/insertion.wgsl", + N, + page_count, + layout + )); + + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("CacheInsertionPass::pipeline"), + layout: Some(&pipeline_layout), + module: &shader_module, + entry_point: Some("insertion"), + compilation_options: Default::default(), + cache: None, + }); + + Self { pipeline } + } + + pub fn encode( + &self, + encoder: &mut ScopeEncoder, + cache_attributes: &CacheAttributes, + cache_structure: &CacheStructure, + insertion_data: &CacheInsertionData, + cache_evictor: &CacheEvictor, + ) + { + gpu_profiler::begin_scope!(encoder, "PageInsertion"); + + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("CacheInsertionPass::pass"), + timestamp_writes: None, + }); + + pass.set_pipeline(&self.pipeline); + 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(), &[]); + + let workgroups = insertion_data.page_count().div_ceil(256) as u32; + pass.dispatch_workgroups(workgroups, 1, 1); + } +} + +/// Invalidates pointers that are pointing to recycled pages +pub struct CacheInvalidationPass +where + [(); N * N * N]:, +{ + workgroup_count: u32, + pipeline: ComputePipeline, +} + +impl CacheInvalidationPass +where + [(); N * N * N]:, +{ + pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self + { + // Binds + // - structure + // - request buffer + + let bindings = [ + // To find where pages are pointing + Some(&CacheStructure::::create_bind_group_layout(device)), + // To read timestamp on which invalidation is marked + Some(&CacheEvictor::create_bind_group_layout(device)), + ]; + + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("CacheInvalidationPass::pipeline_layout"), + bind_group_layouts: &bindings, + + // For setting the correct timestamp after invalidation + immediate_size: size_of::() as u32, + }); + + let shader_module = device.create_shader_module(include_cache_wgsl!( + "./shaders/invalidation.wgsl", + N, + page_count, + layout + )); + + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("CacheInvalidationPass::pipeline"), + layout: Some(&pipeline_layout), + module: &shader_module, + entry_point: Some("invalidation"), + compilation_options: Default::default(), + cache: None, + }); + + Self { + workgroup_count: page_count.div_ceil(256) as u32, + pipeline, + } + } + + pub fn encode( + &self, + encoder: &mut ScopeEncoder, + cache_structure: &CacheStructure, + cache_evictor: &CacheEvictor, + timestamp: u32, + ) + { + gpu_profiler::begin_scope!(encoder, "CacheInvalidation"); + + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("CacheInvalidationPass::pass"), + timestamp_writes: None, + }); + + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, cache_structure.bind_group(), &[]); + pass.set_bind_group(1, cache_evictor.bind_group(), &[]); + + pass.set_immediates(0, bytemuck::bytes_of(×tamp)); + + pass.dispatch_workgroups(self.workgroup_count, 1, 1); + } +} + +/// Points the pages to the newly cached pages +pub struct WritePointersPass +where + [(); N * N * N]:, +{ + pipeline: ComputePipeline, + indirect_buffer: IndirectBuffer1D, +} + +impl WritePointersPass +where + [(); N * N * N]:, +{ + pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self + { + let bindings = [ + // To find where pages are pointing + Some(&CacheStructure::::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(&CacheEvictor::create_bind_group_layout(device)), + ]; + + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("WritePointersPass::pipeline_layout"), + bind_group_layouts: &bindings, + immediate_size: 0, + }); + + let shader_module = device.create_shader_module(include_cache_wgsl!( + "./shaders/write_pointers.wgsl", + N, + page_count, + layout + )); + + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("WritePointersPass::pipeline"), + layout: Some(&pipeline_layout), + module: &shader_module, + entry_point: Some("write_pointers"), + compilation_options: Default::default(), + cache: None, + }); + + Self { + pipeline, + indirect_buffer: IndirectBuffer1D::new(device), + } + } + + pub fn encode( + &self, + encoder: &mut ScopeEncoder, + device: &Device, + cache_structure: &CacheStructure, + request_buffer: &CacheRequestBuffer, + cache_evictor: &CacheEvictor, + ) + { + gpu_profiler::begin_scope!(encoder, "WritePointers"); + + let indirect_buffer = self.indirect_buffer.workgroup_count( + device, + &mut encoder, + &request_buffer.request_count, + 256, + ); + + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("WritePointersPass::pass"), + timestamp_writes: None, + }); + + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, cache_structure.bind_group(), &[]); + pass.set_bind_group(1, cache_evictor.bind_group(), &[]); + + pass.dispatch_workgroups_indirect(indirect_buffer, 0); + } +} diff --git a/src/voxel_cache/requests.rs b/src/voxel_cache/requests.rs index ef9256c..d03a4eb 100644 --- a/src/voxel_cache/requests.rs +++ b/src/voxel_cache/requests.rs @@ -1,4 +1,5 @@ use wgpu::BindGroup; +use wgpu::BindGroupLayout; use wgpu::CommandEncoder; use wgpu::ComputePipeline; use wgpu::Device; @@ -11,6 +12,8 @@ use crate::gpu_profiler::ScopeEncoder; use crate::gpu_profiler::{self}; use crate::voxel_cache::CacheRessources; use crate::voxel_cache::create_multi_buffers_bg_bg_layout; +use crate::voxel_cache::create_multi_buffers_bind_group; +use crate::voxel_cache::create_multi_buffers_bind_group_layout; use crate::voxel_cache::schema::RequestInformation; use crate::voxel_cache::schema::RequestMeta; @@ -21,15 +24,22 @@ pub struct CacheRequestHandler /// This can then be used to prioritize request based on demand request_counts_pages: wgpu::Buffer, - // Ultimately contains sorted requests + /// Ultimately contains sorted requests sorted_requests: wgpu::Buffer, + /// Number of requests + request_count: wgpu::Buffer, + compactor: NonZeroBufferCompactor, // Pass to reset the requests reset_pass_bind_group: BindGroup, reset_pass: ComputePipeline, reset_pass_dispatch: u32, + + // External bind group + bind_group_layout: BindGroupLayout, + bind_group: BindGroup, } /// Records requests made by the cache @@ -45,6 +55,9 @@ pub struct CacheRequestBuffer /// Buffer containing the meta information about the requests, a dense array of [`voxel_cache::schema::RequestMeta`] request_meta: wgpu::Buffer, + + bind_group_layout: wgpu::BindGroupLayout, + bind_group: wgpu::BindGroup, } impl CacheRequestHandler @@ -63,6 +76,12 @@ impl CacheRequestHandler contents: bytemuck::cast_slice(&vec![0u32; page_count * N * N * N]), }); + let request_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("CacheRequestHandler::request_count"), + usage: wgpu::BufferUsages::STORAGE, + contents: bytemuck::bytes_of(&0u32), + }); + let (reset_pass_bg_layout, reset_pass_bind_group) = create_multi_buffers_bg_bg_layout( device, [request_counts_pages], @@ -85,14 +104,26 @@ impl CacheRequestHandler cache: None, }); + let bind_group_layout = Self::create_bind_group_layout(device); + let bind_group = create_multi_buffers_bind_group( + device, + &bind_group_layout, + &[&request_count, &sorted_requests], + Some("CacheRequestHandler::bind_group"), + ); + Self { request_counts_pages, sorted_requests, + request_count, compactor: NonZeroBufferCompactor::new(device, page_count), reset_pass_bind_group, reset_pass, reset_pass_dispatch: (page_count as u32).div_ceil(256), + + bind_group_layout, + bind_group, } } @@ -105,7 +136,6 @@ impl CacheRequestHandler &self, device: &wgpu::Device, ressources: &CacheRessources, - request_count: &wgpu::Buffer, encoder: &mut ScopeEncoder, ) { @@ -121,7 +151,7 @@ impl CacheRequestHandler ); self.compactor - .copy_count_to_buffer(&mut encoder, request_count); + .copy_count_to_buffer(&mut encoder, &self.request_count); // State: // At this point the `sorted_requests` buffer contains the compacted indices of the request counts @@ -136,13 +166,32 @@ impl CacheRequestHandler device, &ressources.scratch_buffer, &self.sorted_requests, - Some(request_count), + Some(&self.request_count), None, &mut encoder, radix_sort::RadixSortDirection::Descending, ); } + pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout + { + create_multi_buffers_bind_group_layout( + device, + 2, + Some("CacheRequestHandler::bind_group_layout"), + ) + } + + pub fn bind_group(&self) -> &BindGroup + { + &self.bind_group + } + + pub fn requset_count_buffer(&self) -> &wgpu::Buffer + { + &self.request_count + } + /// Resets the RequestHandlers request buffer for a next cache usage. pub fn reset(&self, encoder: &mut ScopeEncoder) { @@ -179,11 +228,36 @@ impl CacheRequestBuffer mapped_at_creation: false, }); + let bind_group_layout = Self::create_bind_group_layout(device); + let bind_group = create_multi_buffers_bind_group( + device, + &bind_group_layout, + &[&request_count, &request_informations, &request_meta], + Some("CacheRequestBuffer::bind_group"), + ); + Self { max_requests, request_count, request_informations, request_meta, + + bind_group_layout, + bind_group, } } + + pub fn create_bind_group_layout(device: &Device) -> BindGroupLayout + { + create_multi_buffers_bind_group_layout( + device, + 3, + Some("CacheRequestBuffer::bind_group_layout"), + ) + } + + pub fn bind_group(&self) -> &BindGroup + { + &self.bind_group + } } diff --git a/src/voxel_cache/schema.rs b/src/voxel_cache/schema.rs index 31ae062..a414f4d 100644 --- a/src/voxel_cache/schema.rs +++ b/src/voxel_cache/schema.rs @@ -1,8 +1,9 @@ +/// Contains definitions of the data layouts for the cache +use std::ops::BitOr; + use bytemuck::Pod; use bytemuck::Zeroable; -/// Contains definitions of the data layouts for the cache - /// CachePointer represents a pointer in the [`VoxelCache`] /// /// Pointers are used in the structure pool of the cache and encodes the N-tree itself @@ -149,3 +150,60 @@ pub struct RequestMeta /// The children on which the request was issued pub children_index: u32, } + +/// Structure information about the children of a node. +/// Used when inserting data in the cache, to setup structure pointers +/// +/// A specific child of a node being inserted can be in four state by +/// +/// Whether it can be subdivided further or not +/// Whether it is considered occupied or not +/// 31st bit : subdivisable? +/// 30th bit : occupied? +#[derive(Clone, Copy, Debug, Zeroable, Pod)] +#[repr(transparent)] +pub struct ChildInformation(u32); + +impl ChildInformation +{ + pub const NONE: Self = Self(0); + pub const SUBDIVISABLE: Self = Self(1 << 31); + pub const OCCUPIED: Self = Self(1 << 30); + + pub fn new(subdivisable: bool, occupied: bool) -> Self + { + let mut n = Self::NONE; + if subdivisable + { + n = n | Self::SUBDIVISABLE; + } + + if occupied + { + n = n | Self::OCCUPIED; + } + + n + } +} + +impl BitOr for ChildInformation +{ + type Output = Self; + + fn bitor(self, rhs: Self) -> Self::Output + { + Self(self.0 | rhs.0) + } +} + +/// Information given for an page insertion operation +#[derive(Debug, Clone, Copy)] +#[repr(C)] +pub struct InsertionInformation +where + [(); N * N * N]:, +{ + /// Information to setup structure pointers + pub children: ChildInformation, +} diff --git a/src/voxel_cache/shaders/cache_common.wgsl b/src/voxel_cache/shaders/cache_common.wgsl new file mode 100644 index 0000000..d3e0d38 --- /dev/null +++ b/src/voxel_cache/shaders/cache_common.wgsl @@ -0,0 +1,97 @@ +// Common helper functions and structures +enable wgpu_binding_array; + +struct CacheIndex +{ + page_index: u32, + child_index: u32, +} + +struct PointerPage +{ + occupancy_low: u32, + occupancy_high: u32, + pointers: array, +} + +struct LocationPage +{ + structure_id: u32, + node_id: u32, +} + +struct DepthPage +{ + depth: u32 +} + +struct RequestInformation +{ + structure_id: u32, + node_id: u32, + children_index: u32 +} + +struct RequestMeta +{ + page_index: u32, + children_index: u32 +} + +struct AttributeArray +{ + values: array +} + +struct InsertionInformation +{ + /// [`ChildInformation`] in schema.rs + children: array +} + +// Takes index of pointer and gives cache index +fn pointer_index_to_cache_index(request_index: u32) -> CacheIndex +{ + var cache_index: CacheIndex; + cache_index.page_index = request_index / CHILDREN_COUNT; + cache_index.children_index = request_index % CHILDREN_COUNT; + return cache_index; +} + +fn child_information_occupied(info: u32) -> bool +{ + return ((info >> 30) & 1) != 0; +} + +fn child_information_subdivided(info: u32) -> bool +{ + return ((info >> 31) & 1) != 0; +} + +// Makes an empty child pointer, which can be subdivisible or not +// but not available +fn child_pointer_empty(subdivisible: bool) -> bool +{ + return select(subdivisible, 1, 0) << 31; +} + +fn child_pointer_subdivided(pointer: u32) -> bool +{ + return ((pointer >> 31) & 1) != 0; +} + +fn child_pointer_available(pointer: u32) -> bool +{ + // both bits set ? + return pointer >> 30 == u32(3); +} + +fn child_pointer_pointer(pointer: u32) -> bool +{ + return pointer & 0x3FFFFFFF; +} + +fn child_pointer_make_available(pointer: u32) -> u32 +{ + return pointer | (3 << 30); +} diff --git a/src/voxel_cache/shaders/insertion.wgsl b/src/voxel_cache/shaders/insertion.wgsl new file mode 100644 index 0000000..dec5d0c --- /dev/null +++ b/src/voxel_cache/shaders/insertion.wgsl @@ -0,0 +1,99 @@ + +// Group 0: cache_attributes +@group(0) @binding(0) cache_attributes: binding_array; + +/// Group 1: Cache structure +@group(1) @binding(0) structure_pointer_pages: array; +@group(1) @binding(1) structure_location_pages: array; +@group(1) @binding(2) structure_depth_pages: array; + +// Group 2: Cahce insertion data +@group(2) @binding(0) insertion_data_page_count_buffer: u32; +@group(2) @binding(1) insertion_data_information: array; +@group(2) @binding(2) insertion_data_location_pages: array; +@group(2) @binding(3) insertion_data_destination_indices: array; +@group(2) @binding(4) insertion_data_attributes: binding_array; + +// Group 3: Cache evictor +@group(3) @binding(0) cache_evictor_timestamps: array; +@group(3) @binding(1) cache_evictor_lru_pages: array; + +@compute +@workgroup_size(256, 1, 1) +fn insertion(@builtin(global_invocation_id) gid: vec3) +{ + let index = gid.x; + let insertion_count = min(array_length(&insertion_data_information), insertion_data_page_count_buffer); + if(index >= insertion_count) { return; } + + // Get a page to evict + let page_index = cache_evictor_lru_pages[index]; + + // Copy new location + 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_location_pointer_pages[page_index] = new_pointers; + + // Copy new depth + // TODO: Copy new depth + + // Copy attributes + for(var attribute = 0; attribute < ATTRIBUTE_COUNT; attribute ++) + { + if(!ATTRIBUTE_COPY[attribute]) + { + continue; + } + + var page_stride = CHILDREN_COUNT * ATTRIBUTE_WORD_COUNT[attribute]; + var dest_offset = page_stride * page_index; + var src_offset = page_stride * index; + + // Copy all words of the attribute page + for(var word = 0; word < page_stride; word ++) + { + cache_attributes[dest_offset + word] = insertion_data_attributes[src_offset + word]; + } + } + + insertion_data_destination_indices[index] = page_index; + + // Mark page as dirty for invalidation + cache_evictor_timestamps[page_index] = 0xFFFFFFFF; +} + +fn insertion_info_to_pointer_page(info: InsertionInformation) -> PointerPage +{ + var page: PointerPage; + + var occupancy_low = u32(0); + var occupancy_high = u32(0); + for(var i = 0; i < CHILDREN_COUNT; i++) + { + let insert_info = info.chilren[i]; + + // Pointer + page.pointers[i] = child_information_subdivided(insert_info); + + // Occupancy + var bit = select(child_information_occupied(insert_info), 1, 0); + + // Dispatch set bit on low or high word + bit <<= i % u32(32); + if(i < 32) + { + occupancy_low |= bit; + } + else + { + occupancy_high |= bit; + } + } + + page.occupancy_low = occupancy_low; + page.occupancy_high = occupancy_high; + + return page; +} diff --git a/src/voxel_cache/shaders/invalidation.wgsl b/src/voxel_cache/shaders/invalidation.wgsl new file mode 100644 index 0000000..b3de7f6 --- /dev/null +++ b/src/voxel_cache/shaders/invalidation.wgsl @@ -0,0 +1,52 @@ +/// Group 0: Cache structure +@group(0) @binding(0) structure_pointer_pages: array; +@group(0) @binding(1) structure_location_pages: array; +@group(0) @binding(2) structure_depth_pages: array; + +// Group 1: Cache evictor +@group(1) @binding(0) cache_evictor_timestamps: array; +@group(1) @binding(1) cache_evictor_lru_pages: array; + +var new_timestamp: u32; + +@compute +@workgroup_size(256, 1, 1) +fn invalidation(@builtin(global_invocation_id) gid: vec3) +{ + let index = gid.x; + if(index >= array_length(structure_pointer_pages)) { return; } + + for(var i = 0; i < CHILDREN_COUNT; i++) + { + if(pointer_invalid(structure_pointer_pages[index].pointers[i])) + { + pointer_invalidate(index, i); + } + } +} + +fn pointer_invalid(pointer: u32) -> bool +{ + if(child_pointer_available(pointer)) + { + let pointer = child_pointer_pointer(pointer); + let pointed_timestamp = cache_evictor_timestamps[pointer]; + + // Is dirty marker ? + return pointed_timestamp == 0xFFFFFFFF; + } + + return false; +} + +fn pointer_invalidate(page_index: u32, child_index: u32) +{ + let pointer = structure_pointer_pages[page_index].pointers[child_index]; + let pointed_page = child_pointer_pointer(pointer); + + // Remove dirty mark + cache_evictor_timestamps[pointed_page] = new_timestamp; + + let new_pointer = child_pointer_empty(child_pointer_subdivided(pointer)); + structure_pointer_pages[page_index].pointers[child_index] = new_pointer; +} diff --git a/src/voxel_cache/shaders/write_pointers.wgsl b/src/voxel_cache/shaders/write_pointers.wgsl new file mode 100644 index 0000000..dff54e5 --- /dev/null +++ b/src/voxel_cache/shaders/write_pointers.wgsl @@ -0,0 +1,29 @@ +/// Group 0: Cache structure +@group(0) @binding(0) structure_pointer_pages: array; +@group(0) @binding(1) structure_location_pages: array; +@group(0) @binding(2) structure_depth_pages: array; + +/// Group 1: Request buffer +@group(1) @binding(0) request_buffer_count: u32; // Request count +@group(1) @binding(1) request_buffer_informations: array; +@group(1) @binding(2) request_buffer_meta: array; + +// Group 2: Cache evictor +@group(2) @binding(0) cache_evictor_timestamps: array; +@group(2) @binding(1) cache_evictor_lru_pages: array; + +@compute +@workgroup_size(256, 1, 1) +fn write_pointers(@builtin(global_invocation_id) gid: vec3) +{ + let index = gid.x; + if(index >= request_buffer_count) { return; } + + // The write pages pass establishes a one-to-one corresepondancy + // between requests and recycled pages + let meta = request_buffer_meta[index]; + let page_index = cache_evictor_lru_pages[index]; + + structure_pointer_pages[meta.page_index].pointers[meta.child_index] + = child_pointer_make_available(page_index); +} diff --git a/src/voxel_cache/shaders/write_requests.wgsl b/src/voxel_cache/shaders/write_requests.wgsl new file mode 100644 index 0000000..46957d0 --- /dev/null +++ b/src/voxel_cache/shaders/write_requests.wgsl @@ -0,0 +1,50 @@ +/// Pipeline to write the requests out in to the request buffer + +/// Group 0: Cache structure +@group(0) @binding(0) structure_pointer_pages: array; +@group(0) @binding(1) structure_location_pages: array; +@group(0) @binding(2) structure_depth_pages: array; + +/// Group 1: Cache request handler +@group(1) @binding(0) request_handler_count: u32; // Request count +@group(1) @binding(1) request_handler_requests: array; + +/// Group 3: Request buffer +@group(2) @binding(0) request_buffer_count: u32; // Request count +@group(2) @binding(1) request_buffer_informations: array; +@group(2) @binding(2) request_buffer_meta: array; + +@compute +@workgroup_size(256, 1, 1) +fn write_requests(@builtin(global_invocation_id) gid: vec3) +{ + let index = gid.x; + + // Max size of request buffer and request count + let max_requests = + max(array_length(&request_buffer_informations), request_handler_count); + if(index >= max_requests) { return; } + + + let request_index = request_handler_requests[index]; + let request_location = pointer_index_to_cache_index(request_index); + let page_index = request_location.page_index; + + // 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; + + // Fill out request meta information + var request_meta: RequestMeta; + request_meta.page_index = page_index; + request_meta.children_index = request_location.children_index; + + // Write them to request buffer + request_buffer_information[index] = request_information; + request_buffer_meta[index] = request_meta; + + // Write request count + request_buffer_count = max_requests; +} diff --git a/src/voxel_cache/structure.rs b/src/voxel_cache/structure.rs index 18916d7..874cb9c 100644 --- a/src/voxel_cache/structure.rs +++ b/src/voxel_cache/structure.rs @@ -4,11 +4,15 @@ use wgpu::Buffer; use wgpu::BufferUsages; use wgpu::util::DeviceExt; +use crate::voxel_cache::create_multi_buffers_bind_group; +use crate::voxel_cache::create_multi_buffers_bind_group_layout; use crate::voxel_cache::schema::DepthPage; use crate::voxel_cache::schema::StructurePage; /// Contains the instanciated buffers relevant to the structure of the trees pub struct CacheStructure +where + [(); N * N * N]:, { pointer_pages: Buffer, location_pages: Buffer, @@ -50,60 +54,13 @@ where contents: bytemuck::cast_slice(&vec![DepthPage::PAGE_UNUSED; page_count]), }); - let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("CacheStructure::bind_group_layout"), - entries: &[ - wgpu::BindGroupLayoutEntry { - binding: Self::POINTER_PAGES_BINDING, - visibility: wgpu::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: Self::LOCATION_PAGES_BINDING, - visibility: wgpu::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: Self::DEPTH_PAGES_BINDING, - visibility: wgpu::ShaderStages::COMPUTE, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: false }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - ], - }); - - let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("CacheStructure::bind_group"), - layout: &bind_group_layout, - entries: &[ - wgpu::BindGroupEntry { - binding: Self::POINTER_PAGES_BINDING, - resource: pointer_pages.as_entire_binding(), - }, - wgpu::BindGroupEntry { - binding: Self::LOCATION_PAGES_BINDING, - resource: pointer_pages.as_entire_binding(), - }, - wgpu::BindGroupEntry { - binding: Self::DEPTH_PAGES_BINDING, - resource: pointer_pages.as_entire_binding(), - }, - ], - }); + let bind_group_layout = Self::create_bind_group_layout(device); + let bind_group = create_multi_buffers_bind_group( + device, + &bind_group_layout, + &[&pointer_pages, &location_pages, &depth_pages], + Some("CacheStructure::bind_group"), + ); CacheStructure { pointer_pages, @@ -115,6 +72,11 @@ where } } + pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout + { + create_multi_buffers_bind_group_layout(device, 3, Some("CacheStructure::bind_group_layout")) + } + pub fn bind_group_layout(&self) -> &BindGroupLayout { &self.bind_group_layout