use std::num::NonZero; use bytemuck::Zeroable; use tiff::encoder; use wgpu::{BindGroup, BindGroupLayout, Buffer, BufferUsages, CommandEncoder, ComputePipeline, Device, Queue, ShaderStages, naga::back::spv::Capability::Shader, util::DeviceExt}; use crate::{gpu::radix_sort::{self, RadixSorter}, gpu_profiler::{self, ProfilingEncoder, ScopeEncoder, begin_scope}, voxel_cache::{data::{CacheNodeRequest, CacheResponse, ColorPoolElement, LocationPoolElement, StructurePoolElement}, indirect_buffer::NonZeroBufferCompactor, layout::VoxelCacheLayout, producer_interface::CacheProducerInterface, request_buffer::RequestBuffer, structure_table::StructureTable, usage_buffer::UsageBuffer}}; pub mod request_buffer; pub mod structure_table; pub mod usage_buffer; pub mod producer_interface; pub mod indirect_buffer; pub mod data; pub mod layout; pub struct VoxelCache { size: usize, device: Device, queue: Queue, // Contains pointers to subnodes structure_pool: Buffer, // Contains location information per node for end application location_pool: Buffer, // Contains the depth of node from its structure table indirection depth_pool: Buffer, // User attributes attributes_pools: Vec, // Structure table acts as a root locating structure // It allows having an entry point into the cache pub structure_table: StructureTable, // Request buffer records request per cache page request_buffer: Buffer, // Amounts of requests for this frame request_count_buffer: Buffer, // List indices of most requested pages subdivisions sorted_request_buffer: Buffer, // Usage buffer records usage timestamps per cache page pub usage_buffer: Buffer, // List of LRU pages obtained from usage_buffer lru_list: Buffer, // Scratch buffer of u32 spanning whole cache for operations cache_scratch_buffer: Buffer, structure_bind_group: BindGroup, management_bind_group: BindGroup, attributes_bind_group: BindGroup, structure_table_bind_group_layout: BindGroupLayout, request_pass: ComputePipeline, caching_pass: ComputePipeline, invalidation_pass: ComputePipeline, reset_pass: ComputePipeline, indirect_usage_copy_pass: ComputePipeline, buffer_compactor: NonZeroBufferCompactor, sorter: RadixSorter, // CPU state: timestamp: u32, // User stuff user_bind_group_layout: BindGroupLayout, } #[derive(Clone, Copy)] pub struct VoxelAttribute { pub word_count: u32 } #[derive(Zeroable, bytemuck::Pod, Clone, Copy)] #[repr(C)] struct CachingPipelineImmediates { frame_timestamp: u32, write_pointers: u32, // Boolean } unsafe fn as_raw_bytes(slice: &[T]) -> &[u8] { let size = slice.len() * size_of::(); unsafe { std::slice::from_raw_parts(slice.as_ptr() as *const u8, size) } } impl VoxelCache where [(); N * N * N]:, { pub fn new(cache_size: usize, device: Device, queue: Queue, layout: &VoxelCacheLayout) -> Self { let structure_pool = device.create_buffer(&wgpu::BufferDescriptor { label: Some("VoxelCache::structure_pool"), size: (size_of::>() * cache_size) as u64, usage: BufferUsages::STORAGE, mapped_at_creation: false, }); let location_pool = device.create_buffer(&wgpu::BufferDescriptor { label: Some("VoxelCache::location_pool"), size: (size_of::() * cache_size) as u64, usage: BufferUsages::STORAGE, mapped_at_creation: false, }); let depth_pool = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("VoxelCache::depth_pool"), usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, contents: bytemuck::cast_slice(vec![u32::MAX; cache_size].as_slice()), // Fill empty nodes with max depth, so they end up first }); // Create attribttues let attributes_pools = layout.attributes().iter().enumerate() .map(|(i, x)| device.create_buffer(&wgpu::BufferDescriptor { label: Some(format!("VoxelCache<{N}>::attributes[{i}]").as_str()), size: ((x.word_count as usize) * N * N * N * cache_size * size_of::()) as u64, usage: BufferUsages::STORAGE, mapped_at_creation: false, }) ).collect::>(); let request_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("VoxelCache::request_buffer"), size: (size_of::() * cache_size * N * N * N) as u64, usage: BufferUsages::STORAGE, mapped_at_creation: false, }); let request_count_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("VoxelCache::request_count_buffer"), size: size_of::() as u64, usage: BufferUsages::STORAGE | BufferUsages::COPY_DST, mapped_at_creation: false, }); let sorted_request_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("VoxelCache::request_buffer"), size: (size_of::() * cache_size * N * N * N) as u64, usage: BufferUsages::STORAGE, mapped_at_creation: false, }); let usage_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("VoxelCache::usage_buffer"), size: (size_of::() * cache_size) as u64, usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, mapped_at_creation: false, }); let lru_list = device.create_buffer(&wgpu::BufferDescriptor { label: Some("VoxelCache::lru_buffer"), size: (size_of::() * cache_size) as u64, usage: BufferUsages::STORAGE, mapped_at_creation: false, }); let cache_scratch_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("VoxelCache::cache_scratch_buffer"), size: (size_of::() * cache_size * N * N * N) as u64, usage: BufferUsages::STORAGE | BufferUsages::COPY_DST, mapped_at_creation: false, }); // Attributes let (attributes_bind_group, attributes_bind_group_layout) = { let attributes_bind_group_layout = device.create_bind_group_layout( &wgpu::BindGroupLayoutDescriptor { label: Some("VoxelCache::attributes_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: Some(NonZero::new(layout.attributes().len() as u32).unwrap()), } ], }); let attributes_bindings = attributes_pools.iter() .map(|pool| pool.as_entire_buffer_binding()) .collect::>(); (device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("VoxelCache::attributes_bind_group"), layout: &attributes_bind_group_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::BufferArray(&attributes_bindings), } ] }), attributes_bind_group_layout) }; let (structure_bind_group_layout, structure_bind_group) = create_multi_buffers_bg_bg_layout( &device, &[&structure_pool, &location_pool, &depth_pool], Some("VoxelCache::structure_bind_group")); let (management_bind_group_layout, management_bind_group) = create_multi_buffers_bg_bg_layout( &device, &[&lru_list, &sorted_request_buffer, &usage_buffer, &request_buffer, &request_count_buffer, &cache_scratch_buffer], Some("VoxelCache::management_bind_group")); let structure_table_bind_group_layout = create_multi_buffers_bind_group_layout(&device, 3, Some("VoxelCache::structure_table_bind_group_layout")); let cache_interface_bind_group_layout = CacheProducerInterface::request_side_bind_group_layout(&device, layout.attributes()); let children_count = N*N*N; let attribute_count = layout.attributes().len(); // Common bindings for all pipelines let wgsl_cache_bindings = format!(" enable wgpu_binding_array; struct StructurePoolElement {{ occupancy_low: u32, occupancy_high: u32, pointers: array }} struct ColorPoolElement {{ colors: array }} struct LocationPoolElement {{ structure_id: u32, structure_locator: u32 }} struct SortedRequestsElement {{ node: u32, child: u32 }} struct AttributeArray {{ values: array, }} // Structure bind group @group(0) @binding(0) var structure_pool: array; @group(0) @binding(1) var location_pool: array; @group(0) @binding(2) var depth_pool: array; // Management bind group @group(1) @binding(0) var lru_list: array; @group(1) @binding(1) var sorted_requests: array; @group(1) @binding(2) var usage_buffer: array; @group(1) @binding(3) var request_buffer: array; @group(1) @binding(4) var cache_request_count: u32; @group(1) @binding(5) var cache_scratch_buffer: array; // Attributes bind group @group(2) @binding(0) var attributes_pools: binding_array; // Structure table bind group @group(3) @binding(0) var structure_table_pointers: array; @group(3) @binding(1) var structure_table_sorted_requests: array; @group(3) @binding(2) var structure_table_request_count: u32; "); // ~~ Write request pipeline // Takes sorted requests, writes them out in the ProducerInterface let request_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("VoxelCache::request_pipeline_layout"), bind_group_layouts: &[ Some(&structure_bind_group_layout), Some(&management_bind_group_layout), Some(&attributes_bind_group_layout), Some(&structure_table_bind_group_layout), Some(&cache_interface_bind_group_layout), ], immediate_size: 0, }); // The user bindgroup will be created on the fly let request_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("VoxelCache::request_pass"), layout: Some(&request_pipeline_layout), module: &device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("VoxelCache::request_pass_shader_module"), source: wgpu::ShaderSource::Wgsl( format!(" {wgsl_cache_bindings} struct CacheInterfaceRequest {{ structure_id: u32, locator: u32, child_index: u32 }} struct CacheInterfaceRequestWb {{ node_index: u32, child_index: u32 }} @group(4) @binding(0) var requests: array; @group(4) @binding(1) var requests_wb: array; @group(4) @binding(2) var request_count: u32; @group(4) @binding(3) var structure_nodes: array; @group(4) @binding(4) var attributes_producer: binding_array; // Unused here @group(4) @binding(5) var locations: array; @compute @workgroup_size(64) fn main( @builtin(global_invocation_id) global_invocation_id: vec3 ) {{ // One shader invocation per invocation on both structure table domain // and cache domain var index = global_invocation_id.x; // Can't take more than the user size provided, and size of cache let max_requests_count = min(arrayLength(&requests), arrayLength(&lru_list)); // The amount of requests is the amount of requests on the // structure table and on the cache request_count = min(max_requests_count, cache_request_count + structure_table_request_count); // Bounds check if(index >= request_count) {{ return; }} // Invocation falls into structure table if(index < structure_table_request_count) {{ var request: CacheInterfaceRequest; // Index in structure table IS structure id request.structure_id = structure_table_sorted_requests[index]; request.locator = 0; // Root request -> locator 0 request.child_index = 0xFFFFFFFF; // child index u32::MAX -> var request_wb: CacheInterfaceRequestWb; request_wb.node_index = request.structure_id; request_wb.child_index = 0xFFFFFFFF; // child index u32::MAX -> // Structure table request // Write request requests[index] = request; requests_wb[index] = request_wb; return; }} // Invocation falls into cache let pool_index = index - structure_table_request_count; // Get child and node from request index let sorted_requests_node = sorted_requests[pool_index] / 64; let sorted_requests_child = sorted_requests[pool_index] % 64; // Request location comes from location pool var request: CacheInterfaceRequest; request.structure_id = location_pool[sorted_requests_node].structure_id; request.locator = location_pool[sorted_requests_node].structure_locator; request.child_index = sorted_requests_child; var request_wb: CacheInterfaceRequestWb; request_wb.node_index = sorted_requests_node; request_wb.child_index = sorted_requests_child; // Write request requests[index] = request; requests_wb[index] = request_wb; }} " ) .into(), ), }), entry_point: Some("main"), compilation_options: Default::default(), cache: None, }); // ~~~ Caching pipeline ~~~ // Pipeline that takes user fulling ~some~ requests // and writes them to the cache based on the eviction list let caching_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("VoxelCache::caching_pipeline_layout"), bind_group_layouts: &[ Some(&structure_bind_group_layout), Some(&management_bind_group_layout), Some(&attributes_bind_group_layout), Some(&structure_table_bind_group_layout), Some(&cache_interface_bind_group_layout), ], immediate_size: size_of::() as u32, // Current frame timestamp }); // Generate attributes copy loops let mut copy_loops = String::new(); for (attribute_index, attribute) in layout.attributes().iter().enumerate() { let node_size = attribute.word_count * children_count as u32; let word_count = attribute.word_count; copy_loops += format!(" // Iterate on every children for(var i = 0u; i < {children_count}; i++){{ // Iterate on every word of the attribute for(var j = 0u; j < {word_count}; j++){{ // Offset within child let offset = i * {word_count} + j; attributes_pools[{attribute_index}].values[overwritten_element * {node_size} + offset] = attributes_producer[{attribute_index}].values[producer_index * {node_size} + offset]; }} }} ").as_str(); } let children_count = N * N * N; let caching_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("VoxelCache::caching_pipeline"), layout: Some(&caching_pipeline_layout), module: &device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("VoxelCache::caching_pipeline_shader_module"), source: wgpu::ShaderSource::Wgsl( format!(" {wgsl_cache_bindings} struct DestinationElement {{ node: u32, child: u32 }} struct CachingPipelineImmediates {{ frame_timestamp: u32, write_pointers: u32 }} var parameters: CachingPipelineImmediates; struct CacheInterfaceRequest {{ structure_id: u32, locator: u32, child_index: u32 }} struct CacheInterfaceRequestWb {{ node_index: u32, child_index: u32 }} @group(4) @binding(0) var requests: array; @group(4) @binding(1) var requests_wb: array; @group(4) @binding(2) var request_count: u32; @group(4) @binding(3) var structure_nodes: array; @group(4) @binding(4) var attributes_producer: binding_array; @group(4) @binding(5) var locations: array; @compute @workgroup_size(64) fn main( @builtin(global_invocation_id) global_invocation_id: vec3 ) {{ // Copy with indirection let index = global_invocation_id.x; let total = arrayLength(&structure_nodes); let total_cache = arrayLength(&lru_list); if(index >= total || index >= total_cache) {{ return; }} // Get index from lru eviction list let overwritten_element = lru_list[index]; if(parameters.write_pointers == 0 && usage_buffer[overwritten_element] != parameters.frame_timestamp) {{ // ~~ Phase 1 ~~ // Copy into cache page var occupancy_high = u32(0); var occupancy_low = u32(0); for(var i = 0; i < {children_count}; i++) {{ // Write structure pointer based on subdivision structure_pool[overwritten_element].pointers[i] = select(u32(0), u32(1)<<31, (structure_nodes[index].pointers[i] >> 31) != 0); // Occupancy bit var bit = u32(u32(1) << u32(i % ({children_count} / 2))); // Turn bit on if node is marked occupied let turn_on_bit = select( u32(0), bit, ((structure_nodes[index].pointers[i] >> 30) & 1) != 0 ); // Write bit on low/high 32bit part if(i >= {children_count} / 2) {{ occupancy_high |= turn_on_bit; }}else {{ occupancy_low |= turn_on_bit; }} }} // Write occupancy masks structure_pool[overwritten_element].occupancy_low = occupancy_low; structure_pool[overwritten_element].occupancy_high = occupancy_high; // GENERATED CODE : // Copy produced attributes let producer_index = index; {copy_loops} // Write location location_pool[overwritten_element] = locations[index]; // Mark dirty/correct timestamp, used for invalidation usage_buffer[overwritten_element] = parameters.frame_timestamp + 1; }} if(parameters.write_pointers != 0 && usage_buffer[overwritten_element] != parameters.frame_timestamp) {{ // ~~ Phase 2 ~~ // Point parent to new page let new_pointer = (1 << 31) | (1 << 30) | overwritten_element; if(requests_wb[index].child_index == 0xFFFFFFFF) {{ structure_table_pointers[requests_wb[index].node_index] = new_pointer; depth_pool[overwritten_element] = 0; }} else if(usage_buffer[requests_wb[index].node_index] != parameters.frame_timestamp + 1) {{ structure_pool[requests_wb[index].node_index].pointers[requests_wb[index].child_index] = new_pointer; depth_pool[overwritten_element] = depth_pool[requests_wb[index].node_index] + 1; }} }} }} ") .into(), ), }), entry_point: Some("main"), compilation_options: Default::default(), cache: None, }); // ~~~ Invalidation pipeline ~~~ // Pipeline invalidates old nodes that points to ones // that have been replaces base on timestamp information let invalidation_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("VoxelCache::invalidation_pipeline_layout"), bind_group_layouts: &[ Some(&structure_bind_group_layout), Some(&management_bind_group_layout), Some(&attributes_bind_group_layout), Some(&structure_table_bind_group_layout), ], immediate_size: size_of::() as u32, // frame_timestamp }); let invalidation_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("VoxelCache::invalidation_pass"), layout: Some(&invalidation_pipeline_layout), module: &device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("VoxelCache::invalidation_pass_shader_module"), source: wgpu::ShaderSource::Wgsl( format!(" {wgsl_cache_bindings} var frame_timestamp: u32; @compute @workgroup_size(64) fn main( @builtin(global_invocation_id) global_invocation_id: vec3 ) {{ var index = global_invocation_id.x; let total_pool = arrayLength(&structure_pool); let total_table = arrayLength(&structure_table_pointers); if(index < total_table) {{ // Invocation falls in structure table let structure_pointer = structure_table_pointers[index]; // Is pointer pointing to something valid let pointer_valid = ((structure_pointer >> 30) & 1) != 0; let pointer_subdiv = ((structure_pointer >> 31) & 1) != 0; let pointer = structure_pointer & 0x3FFFFFFF; let pointed_timestamp = usage_buffer[pointer]; if(pointed_timestamp == frame_timestamp + 1 && pointer_valid && pointer_subdiv) // Future // timestamp // -> new page {{ // Invalidate structure_table_pointers[index] &= select(u32(0), u32(1), pointer_subdiv) << 31; }} }} index -= total_table; if(index < total_pool) {{ // Invocation falls in cache for(var i = 0; i < {children_count}; i += 1) {{ let structure_pointer = structure_pool[index].pointers[i]; let pointer = structure_pointer & 0x3FFFFFFF; let pointer_subdiv = ((structure_pointer >> 31) & 1) != 0; let pointed_timestamp = usage_buffer[pointer]; if(pointed_timestamp == frame_timestamp + 1) // Future // timestamp // -> new page {{ // Invalidate structure_pool[index].pointers[i] = select(u32(0), u32(1), pointer_subdiv) << 31; }} }} return; }} }} ") .into(), ), }), entry_point: Some("main"), compilation_options: Default::default(), cache: None, }); // ~~~ Reset pipeline ~~~ // Pipeline resets the necessary state between frames // that have been replaces base on timestamp information let reset_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("VoxelCache::reset_pass"), layout: Some(&invalidation_pipeline_layout), module: &device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("VoxelCache::reset_pass_shader_module"), source: wgpu::ShaderSource::Wgsl( format!(" {wgsl_cache_bindings} @compute @workgroup_size(64) fn main( @builtin(global_invocation_id) global_invocation_id: vec3 ) {{ var index = global_invocation_id.x; let total_pool = arrayLength(&structure_pool); if(index < total_pool) {{ // Reset LRU list for next sort lru_list[index] = index; // Reset requests for(var i = u32(0); i < u32({children_count}); i++) {{ request_buffer[index * u32({children_count}) + i] = 0; }} return; }} }} ") .into(), ), }), entry_point: Some("main"), compilation_options: Default::default(), cache: None, }); // ~~~ Indirect usage copy pipeline ~~~ // Copies usage according to indicies already sorted by depth in the lru list // So they can be further sorted by usage let indirect_usage_copy_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("VoxelCache::indirect_usage_copy_pass"), layout: Some(&invalidation_pipeline_layout), module: &device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("VoxelCache::indirect_usage_copy_pass_shader_module"), source: wgpu::ShaderSource::Wgsl( format!(" {wgsl_cache_bindings} @compute @workgroup_size(64) fn main( @builtin(global_invocation_id) global_invocation_id: vec3 ) {{ var index = global_invocation_id.x; let total_pool = arrayLength(&lru_list); var sorted_index = lru_list[index]; var usage = usage_buffer[sorted_index]; cache_scratch_buffer[index] = usage; }} ") .into(), ), }), entry_point: Some("main"), compilation_options: Default::default(), cache: None, }); // ~~ Structure table let structure_table = StructureTable::new(device.clone(), queue.clone()); // ~~ Create user bind groups let user_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("VoxelCache::user_bind_group_layout"), entries: &[ // Structure pool 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, }, // Attributes 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: Some(NonZero::new(attributes_pools.len() as u32).unwrap()), }, // Request Buffer 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, }, // Usage Buffer 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, }, // Structure table pointers 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, }, // Structure table request buffer 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: None, }, ], }); let buffer_compactor = NonZeroBufferCompactor::new(&device, cache_size * children_count); let sorter = RadixSorter::new(&device, cache_size * children_count); Self { size: cache_size, structure_table, queue, device, structure_pool, attributes_pools, location_pool, depth_pool, request_buffer, sorted_request_buffer, request_count_buffer, usage_buffer, lru_list, cache_scratch_buffer, structure_bind_group, management_bind_group, attributes_bind_group, structure_table_bind_group_layout, request_pass, caching_pass, invalidation_pass, reset_pass, indirect_usage_copy_pass, buffer_compactor, sorter, timestamp: 0, user_bind_group_layout, } } pub fn user_bind_group_layout(&self) -> &BindGroupLayout { &self.user_bind_group_layout } pub fn user_bind_group(&self) -> BindGroup { let attributes_bindings = self.attributes_pools.iter().map(|x| x.as_entire_buffer_binding()).collect::>>(); self.device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("VoxelCache::user_bind_group"), layout: &self.user_bind_group_layout, entries: &[ // Structure pool wgpu::BindGroupEntry { binding: 0, resource: self.structure_pool.as_entire_binding(), }, // Attribute pool wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::BufferArray(attributes_bindings.as_slice()), }, // Request buffer wgpu::BindGroupEntry { binding: 2, resource: self.request_buffer.as_entire_binding(), }, // Usage buffer wgpu::BindGroupEntry { binding: 3, resource: self.usage_buffer.as_entire_binding(), }, // Structure table // Structure table pointers wgpu::BindGroupEntry { binding: 4, resource: self.structure_table.pointer_table.as_entire_binding(), }, // Pools request count wgpu::BindGroupEntry { binding: 5, resource: self.structure_table.request_buffer.request_buffer().as_entire_binding(), }, ], }) } fn structure_table_bind_group(&self) -> BindGroup { create_multi_buffers_bind_group(&self.device, &self.structure_table_bind_group_layout, &[ &self.structure_table.pointer_table, self.structure_table.request_buffer.index_buffer(), self.structure_table.request_buffer.request_count_buffer() ], Some("VoxelCache::structure_table_bind_group")) } pub fn cache_post_render(&mut self, encoder: &mut ScopeEncoder, request_interface: &CacheProducerInterface) { gpu_profiler::begin_scope!(encoder, "cache_post_render"); // Sort request buffer { gpu_profiler::begin_scope!(encoder, "request_sort"); { gpu_profiler::begin_scope!(encoder, "compaction"); self.buffer_compactor .compact_buffer( &self.device, &mut encoder, &self.request_buffer, &self.sorted_request_buffer, Some(&self.cache_scratch_buffer) ); self.buffer_compactor.copy_count_to_buffer(&mut encoder, &self.request_count_buffer); } { gpu_profiler::begin_scope!(encoder, "radix_sort"); self.sorter .sort( &self.device, &self.cache_scratch_buffer, &self.sorted_request_buffer, Some(&self.request_count_buffer), None, &mut encoder, radix_sort::RadixSortDirection::Descending ); } } // Usage sorting { gpu_profiler::begin_scope!(encoder, "usage_sorting"); // Copy depth to scratch to preserve during sort encoder.copy_buffer_to_buffer( &self.depth_pool, 0, &self.cache_scratch_buffer, 0, (self.size * size_of::()) as u64); { gpu_profiler::begin_scope!(encoder, "depth_radix"); // First sort by depth // Deeper nodes are first now self.sorter .sort( &self.device, &self.cache_scratch_buffer, &self.lru_list, None, Some(self.size), &mut encoder, radix_sort::RadixSortDirection::Descending ); // Lowest (oldest) first } { gpu_profiler::begin_scope!(encoder, "indirect_copy"); let mut indirect_usage_copy_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("VoxelCache::indirect_usage_copy_pass"), timestamp_writes: None, }); indirect_usage_copy_pass.set_bind_group(0, Some(&self.structure_bind_group), &[]); indirect_usage_copy_pass.set_bind_group(1, Some(&self.management_bind_group), &[]); indirect_usage_copy_pass.set_bind_group(2, Some(&self.attributes_bind_group), &[]); indirect_usage_copy_pass.set_bind_group(3, Some(&self.structure_table_bind_group()), &[]); indirect_usage_copy_pass.set_pipeline(&self.indirect_usage_copy_pass); indirect_usage_copy_pass.dispatch_workgroups(self.size.div_ceil(64) as u32, 1, 1); drop(indirect_usage_copy_pass); } { gpu_profiler::begin_scope!(encoder, "usage_radix"); // Sort usage self.sorter .sort( &self.device, &self.cache_scratch_buffer, &self.lru_list, None, Some(self.size), &mut encoder, radix_sort::RadixSortDirection::Ascending ); // Lowest (oldest) first } } { gpu_profiler::begin_scope!(encoder, "structure_table"); self.structure_table .request_buffer_mut() .sort_requests(&mut encoder); } // Sorted requests are now in the group gpu_profiler::begin_scope!(encoder, "request_pass"); let mut request_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("VoxelCache::write_requests_pass"), timestamp_writes: None, }); request_pass.set_bind_group(0, Some(&self.structure_bind_group), &[]); request_pass.set_bind_group(1, Some(&self.management_bind_group), &[]); request_pass.set_bind_group(2, Some(&self.attributes_bind_group), &[]); request_pass.set_bind_group(3, Some(&self.structure_table_bind_group()), &[]); request_pass.set_bind_group(4, Some(&request_interface.request_side_bind_group), &[]); request_pass.set_pipeline(&self.request_pass); // Compute necessary shader invocations let shader_invocation_count = request_interface.size; let workgroup_invocation_count = shader_invocation_count.div_ceil(64); request_pass.dispatch_workgroups(workgroup_invocation_count as u32, 1, 1); drop(request_pass); self.structure_table .request_buffer_mut() .reset_requests(&mut encoder); } pub fn current_timestamp(&self) -> u32 { self.timestamp } pub fn cache_insert(&mut self, encoder: &mut CommandEncoder, cache_interface: &CacheProducerInterface) { // Each of the entry of the cache insertion, is matched with the usage list to evict let mut cache_insertion_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("VoxelCache::cache_insertion_pass"), timestamp_writes: None, }); // Copy insertions to evicted lru // Point parents to children let structure_table_bind_group = self.structure_table_bind_group(); // ~~~ Write data + Dirty flagging/timestamp update ~~~ { cache_insertion_pass.set_bind_group(0, Some(&self.structure_bind_group), &[]); cache_insertion_pass.set_bind_group(1, Some(&self.management_bind_group), &[]); cache_insertion_pass.set_bind_group(2, Some(&self.attributes_bind_group), &[]); cache_insertion_pass.set_bind_group(3, Some(&structure_table_bind_group), &[]); cache_insertion_pass.set_bind_group(4, Some(&cache_interface.request_side_bind_group), &[]); cache_insertion_pass.set_pipeline(&self.caching_pass); cache_insertion_pass.set_immediates( 0, bytemuck::bytes_of(&CachingPipelineImmediates { frame_timestamp: self.current_timestamp(), write_pointers: 0, // false }), ); // Compute dispatch amounts let shader_invocation_count = cache_interface.size; let workgroup_invocations = shader_invocation_count.div_ceil(64); cache_insertion_pass.dispatch_workgroups(workgroup_invocations as u32, 1, 1); } // ~~~ Invalidate pointers ~~~ { cache_insertion_pass.set_pipeline(&self.invalidation_pass); cache_insertion_pass.set_bind_group(4, None, &[]); cache_insertion_pass .set_immediates(0, bytemuck::bytes_of(&self.timestamp)); // Compute dispatch amounts let shader_invocation_count = self.size + self.structure_table.allocation_table.len(); let workgroup_invocations = shader_invocation_count.div_ceil(64); cache_insertion_pass.dispatch_workgroups(workgroup_invocations as u32, 1, 1); } // ~~~ Write new pointers ~~~ { cache_insertion_pass.set_pipeline(&self.caching_pass); cache_insertion_pass.set_bind_group(4, Some(&cache_interface.request_side_bind_group), &[]); cache_insertion_pass.set_immediates( 0, bytemuck::bytes_of(&CachingPipelineImmediates { frame_timestamp: self.current_timestamp(), write_pointers: 1, // true }), ); // Compute dispatch amounts let shader_invocation_count = cache_interface.size; let workgroup_invocations = shader_invocation_count.div_ceil(64); cache_insertion_pass.dispatch_workgroups(workgroup_invocations as u32, 1, 1); } // Reset state { cache_insertion_pass.set_pipeline(&self.reset_pass); cache_insertion_pass.set_bind_group(4, None, &[]); let shader_invocation_count = self.size; let workgroup_invocations = shader_invocation_count.div_ceil(64); cache_insertion_pass.dispatch_workgroups(workgroup_invocations as u32, 1, 1); } } pub fn next_frame(&mut self) { self.timestamp += 1; } } // Utilities fn create_multi_buffers_bind_group_layout(device: &Device, count: u32, label: Option<&str>) -> BindGroupLayout { let entries = (0..count).map(|i| wgpu::BindGroupLayoutEntry { binding: i, visibility: ShaderStages::COMPUTE, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: false }, has_dynamic_offset: false, min_binding_size: None }, count: None, } ).collect::>(); device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label, entries: &entries, }) } fn create_multi_buffers_bind_group(device: &Device, layout: &BindGroupLayout, buffers: &[&Buffer], label: Option<&str>) -> BindGroup { let entries = buffers.iter().enumerate().map(|(i, buffer)| wgpu::BindGroupEntry { binding: i as u32, resource: buffer.as_entire_binding(), } ).collect::>(); device.create_bind_group(&wgpu::BindGroupDescriptor { label, layout, entries: &entries, }) } fn create_multi_buffers_bg_bg_layout(device: &Device, buffers: &[&Buffer], label: Option<&str>) -> (BindGroupLayout, BindGroup) { let layout = create_multi_buffers_bind_group_layout(device, buffers.len() as u32, label); let bg = create_multi_buffers_bind_group(device, &layout, buffers, label); ( layout, bg ) }