diff --git a/shaders/compaction.slang b/shaders/compaction.slang index a973b4b..e69a102 100644 --- a/shaders/compaction.slang +++ b/shaders/compaction.slang @@ -3,6 +3,11 @@ RWStructuredBuffer count_buffer; [[vk::binding(1, 0)]] RWStructuredBuffer index_buffer; +[[vk::binding(2, 0)]] +RWStructuredBuffer compacted_buffer; + +[[vk::push_constant]] +uniform uint32_t write_compact; [[vk::binding(0, 1)]] RWStructuredBuffer reduced_buffer; @@ -157,5 +162,18 @@ void scatter( { index_buffer[sum2] = thread_index * 2 + 1; } + + if (write_compact != 0) + { + if (count_buffer[thread_index * 2] != 0 && sum1 < total) + { + compacted_buffer[sum1] = count_buffer[thread_index * 2]; + } + + if (count_buffer[thread_index * 2 + 1] != 0 && sum2 < total) + { + compacted_buffer[sum2] = count_buffer[thread_index * 2 + 1]; + } + } } diff --git a/shaders/compaction.spv b/shaders/compaction.spv index 45d92dd..1e30405 100644 Binary files a/shaders/compaction.spv and b/shaders/compaction.spv differ diff --git a/shaders/gi.slang b/shaders/gi.slang index a70cc70..0c6226a 100644 --- a/shaders/gi.slang +++ b/shaders/gi.slang @@ -82,14 +82,12 @@ RWStructuredBuffer structure_pool; [[vk::binding(1, 0)]] RWStructuredBuffer attributes_pool[2]; [[vk::binding(2, 0)]] -RWStructuredBuffer location_pool; -[[vk::binding(3, 0)]] RWStructuredBuffer request_buffer; -[[vk::binding(4, 0)]] +[[vk::binding(3, 0)]] RWStructuredBuffer usage_buffer; -[[vk::binding(5, 0)]] +[[vk::binding(4, 0)]] RWStructuredBuffer structure_table_pointer; -[[vk::binding(6, 0)]] +[[vk::binding(5, 0)]] RWStructuredBuffer> structure_table_request_buffer; ByteColor fetch_color(uint32_t index, uint32_t child_index) @@ -172,7 +170,6 @@ void gi(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_Gr var voxel_cache : VoxelCache; voxel_cache.structure_pool = structure_pool; voxel_cache.attributes_pool = attributes_pool; - voxel_cache.location_pool = location_pool; voxel_cache.request_buffer = request_buffer; voxel_cache.usage_buffer = usage_buffer; voxel_cache.structure_table_pointer = structure_table_pointer; diff --git a/shaders/ray_cast.slang b/shaders/ray_cast.slang index dd52c2d..1af7044 100644 --- a/shaders/ray_cast.slang +++ b/shaders/ray_cast.slang @@ -81,17 +81,10 @@ public struct RequestBufferElement public Atomic requests[64]; } -public struct LocationPoolElement -{ - public uint32_t structure_id; - public uint32_t structure_locator; -} - public struct VoxelCache { public RWStructuredBuffer structure_pool; public RWStructuredBuffer attributes_pool[2]; - public RWStructuredBuffer location_pool; public RWStructuredBuffer request_buffer; public RWStructuredBuffer usage_buffer; public RWStructuredBuffer structure_table_pointer; @@ -356,7 +349,7 @@ public HitInformation ray_cast( context.ray_direction, position - float3(current_voxel), chunk_index, - t_adv, + max(t_adv, 0.01), stack_index, context.frame_timestamp, context.cache_report); diff --git a/shaders/voxel.slang b/shaders/voxel.slang index 18e4fdd..9864f6f 100644 --- a/shaders/voxel.slang +++ b/shaders/voxel.slang @@ -82,14 +82,12 @@ RWStructuredBuffer structure_pool; [[vk::binding(1, 0)]] RWStructuredBuffer attributes_pool[2]; [[vk::binding(2, 0)]] -RWStructuredBuffer location_pool; -[[vk::binding(3, 0)]] RWStructuredBuffer request_buffer; -[[vk::binding(4, 0)]] +[[vk::binding(3, 0)]] RWStructuredBuffer usage_buffer; -[[vk::binding(5, 0)]] +[[vk::binding(4, 0)]] RWStructuredBuffer structure_table_pointer; -[[vk::binding(6, 0)]] +[[vk::binding(5, 0)]] RWStructuredBuffer> structure_table_request_buffer; ByteColor fetch_color(uint32_t index, uint32_t child_index) @@ -156,7 +154,6 @@ void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_ var voxel_cache : VoxelCache; voxel_cache.structure_pool = structure_pool; voxel_cache.attributes_pool = attributes_pool; - voxel_cache.location_pool = location_pool; voxel_cache.request_buffer = request_buffer; voxel_cache.usage_buffer = usage_buffer; voxel_cache.structure_table_pointer = structure_table_pointer; @@ -179,6 +176,7 @@ void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_ let hit_pos = hit.hit_pos; let hit_normal = fetch_normal(hit.node_index, hit.child_index); let hit_albedo = fetch_color(hit.node_index, hit.child_index).float_color; + // let hit_albedo = hit.color; gbuffer_position.Store(location.xy, float4(hit_pos, 1.)); gbuffer_normal.Store(location.xy, float4(hit_normal, 1.)); diff --git a/shaders/voxel.spv b/shaders/voxel.spv index 788705b..43f5cd1 100644 Binary files a/shaders/voxel.spv and b/shaders/voxel.spv differ diff --git a/src/gpu/radix_sort.rs b/src/gpu/radix_sort.rs index 3f8f0f7..a0eee4d 100644 --- a/src/gpu/radix_sort.rs +++ b/src/gpu/radix_sort.rs @@ -326,6 +326,7 @@ impl RadixSorter keys: &Buffer, values: &Buffer, indirect: Option<&Buffer>, + direct_length: Option, encoder: &mut CommandEncoder, sort_direction: RadixSortDirection, ) @@ -383,7 +384,7 @@ impl RadixSorter } else { - self.max_size as u32 + direct_length.unwrap_or(self.max_size) as u32 }, descending: 0, digit_stride: 0, diff --git a/src/main.rs b/src/main.rs index d2d75f8..350d288 100644 --- a/src/main.rs +++ b/src/main.rs @@ -64,6 +64,7 @@ use crate::voxel_cache::VoxelCache; use crate::voxel_cache::data::ColorBytes; use crate::voxel_cache::data::LocationPoolElement; use crate::voxel_cache::data::StructurePoolElement; +use crate::voxel_cache::layout::VoxelCacheLayout; use crate::voxel_cache::producer_interface::CacheProducerInterface; use crate::voxel_cache::producer_interface::CacheRequest; @@ -188,6 +189,7 @@ impl State max_immediate_size: 112, max_storage_buffers_per_shader_stage: 16, max_binding_array_elements_per_shader_stage: 16, + max_bind_groups: 8, ..Default::default() }, ..Default::default() @@ -203,7 +205,7 @@ impl State //let elt_count = 100_000; //let elt_count = (21 * 4096) as u32; //let elt_count = 3000 as u32; - let elt_count_real = 1_000_000; + let elt_count_real = 500_000; let count_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("count_buffer"), usage: wgpu::BufferUsages::STORAGE, @@ -215,8 +217,8 @@ impl State let org_big_value_buffer = (0..(elt_count as u32)).collect::>(); let org_big_key_buffer = org_big_value_buffer .iter() - //.map(|_| random::()) - .map(|_| random_range(1..256)) + .map(|_| random::()) + //.map(|_| random_range(1..256)) .collect::>(); // let mut prefix = org_big_key_buffer.iter().fold([0; 256], |acc, x| { @@ -330,13 +332,13 @@ impl State let egui_renderer = EguiRenderer::new(&device, surface_format, &window); - let attributes = vec![ - VoxelAttribute { word_count: 1 }, - VoxelAttribute { word_count: 3 }, - ]; + let attributes = VoxelCacheLayout::default() + .add_attribute(voxel_cache::layout::VoxelCacheAttribute { word_count: 1 }) + .add_attribute(voxel_cache::layout::VoxelCacheAttribute { word_count: 3 }); + let mut voxel_cache = - VoxelCache::<4>::new(100_000, device.clone(), queue.clone(), attributes.clone()); - let cache_interface = CacheProducerInterface::new(1024, &device, attributes.clone()); + VoxelCache::<4>::new(100_000, device.clone(), queue.clone(), &attributes); + let cache_interface = CacheProducerInterface::new(1024, &device, &attributes); let terrain_generator = TerrainGenerator::<4>::new(5, "vxls_height.tif", 0.2, "img.jpg"); //let terrain_generator = SdfGenerator::<4>::new(5); @@ -357,6 +359,9 @@ impl State let terrain_width = terrain_generator.chunk_width; let terrain_height = terrain_generator.chunk_height; let terrain_alt = terrain_generator.chunk_alt; + // let terrain_width = 10; + // let terrain_height = 10; + // let terrain_alt = 10; println!( "Chunk count : {}", terrain_width * terrain_height * terrain_width @@ -568,7 +573,7 @@ impl State label: Some("Voxel pipeline layout"), bind_group_layouts: &[ - Some(&voxel_cache.bind_group_layout()), + Some(voxel_cache.user_bind_group_layout()), Some(&ray_march_bind_group_layout), ], immediate_size: size_of::() as u32, @@ -590,7 +595,7 @@ impl State label: Some("Gi pipeline layout"), bind_group_layouts: &[ - Some(&voxel_cache.bind_group_layout()), + Some(&voxel_cache.user_bind_group_layout()), Some(&gi_bind_group_layout), ], immediate_size: size_of::() as u32, @@ -960,7 +965,7 @@ impl State }); renderpass.set_pipeline(&self.pipeline); - renderpass.set_bind_group(0, Some(&self.voxel_cache.lock().bind_group()), &[]); + renderpass.set_bind_group(0, &self.voxel_cache.lock().user_bind_group(), &[]); renderpass.set_bind_group(1, Some(&surface_bg), &[]); let imm = [Immediates { view_proj: self.camera.view_proj().inverse(), @@ -1122,7 +1127,7 @@ impl State DownloadBuffer::read_buffer( &self.device, &self.queue, - &self.voxel_cache.lock().usage_buffer.usage_buffer.slice(..), + &self.voxel_cache.lock().usage_buffer.slice(..), move |slice| { let slice = slice.unwrap(); let cache_slice: &[u32] = bytemuck::cast_slice(&slice); @@ -1136,6 +1141,23 @@ impl State }, ); + // DownloadBuffer::read_buffer( + // &self.device, + // &self.queue, + // &self + // .voxel_cache + // .lock() + // .structure_table + // .request_buffer + // .request_count_buffer() + // .slice(..), + // move |slice| { + // let slice = slice.unwrap(); + // let cache_slice: &[u32] = bytemuck::cast_slice(&slice); + // println!("structure_table count: {}", cache_slice[0]); + // }, + // ); + // ~~ Do cache managment if !self .camera @@ -1205,7 +1227,7 @@ impl State bytemuck::pod_collect_to_vec(&buffer.unwrap()); let generator = cloned_generator; - let gen_test = SineGenerator::<4>::new(5); + //let gen_test = SineGenerator::<4>::new(5); let mut structure_nodes: Vec> = vec![]; let mut color_nodes: Vec<[ColorBytes; 64]> = vec![]; diff --git a/src/voxel_cache.rs b/src/voxel_cache.rs index 6fa6f39..815021d 100644 --- a/src/voxel_cache.rs +++ b/src/voxel_cache.rs @@ -1,9 +1,9 @@ use std::num::NonZero; use bytemuck::Zeroable; -use wgpu::{BindGroup, BindGroupLayout, Buffer, BufferUsages, CommandEncoder, ComputePipeline, Device, Queue, ShaderStages, util::DeviceExt}; +use wgpu::{BindGroup, BindGroupLayout, Buffer, BufferUsages, CommandEncoder, ComputePipeline, Device, Queue, ShaderStages, naga::back::spv::Capability::Shader, util::DeviceExt}; -use crate::voxel_cache::{data::{CacheNodeRequest, CacheResponse, ColorPoolElement, LocationPoolElement, StructurePoolElement}, producer_interface::CacheProducerInterface, request_buffer::RequestBuffer, structure_table::StructureTable, usage_buffer::UsageBuffer}; +use crate::{gpu::radix_sort::{self, RadixSorter}, 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; @@ -13,35 +13,63 @@ 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, - 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: RequestBuffer, + // 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, - voxel_cache_bind_group: BindGroup, structure_table_bind_group_layout: BindGroupLayout, - voxel_cache_render_bind_group_layout: BindGroupLayout, - // Writing requests - request_write_pipeline: ComputePipeline, + request_pass: ComputePipeline, + caching_pass: ComputePipeline, + invalidation_pass: ComputePipeline, + reset_pass: ComputePipeline, + buffer_compactor: NonZeroBufferCompactor, + sorter: RadixSorter, - // User response -> caching - caching_pipeline: ComputePipeline, + // CPU state: + timestamp: u32, - // Invalidation - invalidation_pipeline: ComputePipeline, - - pub usage_buffer: UsageBuffer, + // User stuff + user_bind_group_layout: BindGroupLayout, } #[derive(Clone, Copy)] @@ -69,31 +97,25 @@ impl VoxelCache where [(); N * N * N]:, { - pub fn new(cache_size: usize, device: Device, queue: Queue, attributes: Vec) -> Self + pub fn new(cache_size: usize, device: Device, queue: Queue, layout: &VoxelCacheLayout) -> Self { let structure_pool = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("Structure pool"), + 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("Location pool"), + 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("Depth pool"), - contents: bytemuck::cast_slice(&vec![0xFFFFFFFFu32; cache_size]), - usage: BufferUsages::STORAGE, - }); - // Create attribttues let attributes_pools = - attributes.iter().enumerate() + layout.attributes().iter().enumerate() .map(|(i, x)| device.create_buffer(&wgpu::BufferDescriptor { @@ -104,294 +126,116 @@ where }) ).collect::>(); - let request_buffer = RequestBuffer::new(cache_size, device.clone()); - let usage_buffer = UsageBuffer::new(cache_size, device.clone()); - - let request_interface_bind_group_layout = CacheProducerInterface::::request_side_bind_group_layout(&device, &attributes); - - // Rendering bing group layouts - let voxel_cache_render_bind_group_layout = - device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("voxel_cache_render_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 pool - 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.len() as u32).unwrap()), - }, - // Location pool - 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, - }, - // Request 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, - }, - // Usage buffer - 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 stuff - // Structure table pointers - 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, - }, - - // Structure table request buffer - wgpu::BindGroupLayoutEntry { - binding: 6, - 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 voxel_cache_bind_group_layout = - device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("voxel_cache_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 pool - 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.len() as u32).unwrap()), - }, - // Location pool - 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, - }, - // Depth pool - 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, - }, - // Sorted requests - wgpu::BindGroupLayoutEntry { - binding: 4, - visibility: ShaderStages::COMPUTE, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: true }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - // LRU List - wgpu::BindGroupLayoutEntry { - binding: 5, - visibility: ShaderStages::COMPUTE, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: true }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - // Usage buffer - wgpu::BindGroupLayoutEntry { - binding: 6, - visibility: ShaderStages::COMPUTE, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: false }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - // pools request count - wgpu::BindGroupLayoutEntry { - binding: 7, - visibility: ShaderStages::COMPUTE, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: true }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - ], - }); - - let attributes_bindings = attributes_pools.iter().map(|x| x.as_entire_buffer_binding()).collect::>>(); - let voxel_cache_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("voxel_cache_bind_group"), - layout: &voxel_cache_bind_group_layout, - entries: &[ - // Structure pool - wgpu::BindGroupEntry { - binding: 0, - resource: structure_pool.as_entire_binding(), - }, - // Attributes pool - wgpu::BindGroupEntry { - binding: 1, - resource: wgpu::BindingResource::BufferArray( - attributes_bindings.as_slice() - ), - }, - // Location pool - wgpu::BindGroupEntry { - binding: 2, - resource: location_pool.as_entire_binding(), - }, - // Depth pool - wgpu::BindGroupEntry { - binding: 3, - resource: depth_pool.as_entire_binding(), - }, - // Sorted requests - wgpu::BindGroupEntry { - binding: 4, - resource: request_buffer.index_buffer().as_entire_binding(), - }, - // LRU list - wgpu::BindGroupEntry { - binding: 5, - resource: usage_buffer.sort_buffer().as_entire_binding(), - }, - // Usage buffer - wgpu::BindGroupEntry { - binding: 6, - resource: usage_buffer.usage_buffer().as_entire_binding(), - }, - // Pools request count - wgpu::BindGroupEntry { - binding: 7, - resource: request_buffer.request_count_buffer().as_entire_binding(), - }, - ], + 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 structure_table_bind_group_layout = - device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("structure_table_bind_group_layout"), - entries: &[ - // Pointer table - 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, - }, - // Sorted requests - 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, - }, - // Requests count - 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, - }, - ], - }); + 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], + 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 = attributes.len(); - let wgsl_bindings = + let attribute_count = layout.attributes().len(); + // Common bindings for all pipelines + let wgsl_cache_bindings = format!(" enable wgpu_binding_array; struct StructurePoolElement {{ - occupancy_low: atomic, - occupancy_high: atomic, + occupancy_low: u32, + occupancy_high: u32, pointers: array }} @@ -417,41 +261,52 @@ where values: array, }} + // Structure bind group @group(0) @binding(0) var structure_pool: array; - @group(0) @binding(1) var attributes_pools: binding_array; - @group(0) @binding(2) var location_pool: array; - @group(0) @binding(3) var depth_pool: array; - @group(0) @binding(4) var sorted_requests: array; - @group(0) @binding(5) var lru_list: array; - @group(0) @binding(6) var usage_buffer: array; - @group(0) @binding(7) var pools_request_count: u32; + @group(0) @binding(1) var location_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; + + // 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; - @group(1) @binding(0) var structure_table_pointers: array; - @group(1) @binding(1) var structure_table_sorted_requests: array; - @group(1) @binding(2) var structure_table_request_count: u32; "); - let write_requests_pipeline_layout = + // ~~ Write request pipeline + // Takes sorted requests, writes them out in the ProducerInterface + let request_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("write_requests_pipeline_layout"), + label: Some("VoxelCache::request_pipeline_layout"), bind_group_layouts: &[ - Some(&voxel_cache_bind_group_layout), + Some(&structure_bind_group_layout), + Some(&management_bind_group_layout), + Some(&attributes_bind_group_layout), Some(&structure_table_bind_group_layout), - Some(&request_interface_bind_group_layout), + Some(&cache_interface_bind_group_layout), ], immediate_size: 0, }); // The user bindgroup will be created on the fly - let write_requests = + let request_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("write_requests_pipeline"), - layout: Some(&write_requests_pipeline_layout), + label: Some("VoxelCache::request_pass"), + layout: Some(&request_pipeline_layout), module: &device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("write_requests_pipeline_shader_module"), + label: Some("VoxelCache::request_pass_shader_module"), source: wgpu::ShaderSource::Wgsl( format!(" - {wgsl_bindings} + {wgsl_cache_bindings} struct CacheInterfaceRequest {{ @@ -466,13 +321,13 @@ where child_index: u32 }} - @group(2) @binding(0) var requests: array; - @group(2) @binding(1) var requests_wb: array; - @group(2) @binding(2) var request_count: 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(2) @binding(3) var structure_nodes: array; - @group(2) @binding(4) var color_nodes: array; - @group(2) @binding(5) var locations: array; + @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) @@ -483,16 +338,23 @@ where // One shader invocation per invocation on both structure table domain // and cache domain var index = global_invocation_id.x; - let max_requests_count = min(arrayLength(&requests), arrayLength(&lru_list)); - request_count = min(max_requests_count, pools_request_count + structure_table_request_count); - if(index >= request_count) - {{ - return; - }} + // 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 @@ -508,8 +370,10 @@ where 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; @@ -544,42 +408,51 @@ where let caching_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("caching_pipeline_layout"), + label: Some("VoxelCache::caching_pipeline_layout"), bind_group_layouts: &[ - Some(&voxel_cache_bind_group_layout), + Some(&structure_bind_group_layout), + Some(&management_bind_group_layout), + Some(&attributes_bind_group_layout), Some(&structure_table_bind_group_layout), - Some(&request_interface_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 attributes.iter().enumerate() + 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_nodes[{attribute_index}].values[index * {node_size} + offset]; + = attributes_producer[{attribute_index}].values[producer_index * {node_size} + offset]; }} }} ").as_str(); } let children_count = N * N * N; - let caching_pipeline = + let caching_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("caching_pipeline"), + label: Some("VoxelCache::caching_pipeline"), layout: Some(&caching_pipeline_layout), module: &device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("caching_pipeline_shader_module"), + label: Some("VoxelCache::caching_pipeline_shader_module"), source: wgpu::ShaderSource::Wgsl( format!(" - {wgsl_bindings} + {wgsl_cache_bindings} struct DestinationElement {{ @@ -609,13 +482,13 @@ where child_index: u32 }} - @group(2) @binding(0) var requests: array; - @group(2) @binding(1) var requests_wb: array; - @group(2) @binding(2) var request_count: 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(2) @binding(3) var structure_nodes: array; - @group(2) @binding(4) var attributes_nodes: binding_array; - @group(2) @binding(5) var locations: array; + @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) @@ -632,24 +505,27 @@ where 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 + // ~~ 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); - var bit = u32(1); - if(i % ({children_count} / 2) != 0) - {{ - bit = u32(u32(1) << u32(i % ({children_count} / 2))); - }} + // 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), @@ -657,6 +533,7 @@ where ((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; @@ -665,31 +542,38 @@ where occupancy_low |= turn_on_bit; }} }} - atomicStore(&structure_pool[overwritten_element].occupancy_low, occupancy_low); - atomicStore(&structure_pool[overwritten_element].occupancy_high, occupancy_high); + // 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 - usage_buffer[overwritten_element] = parameters.frame_timestamp + 1; - + // 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 + // ~~ 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 + //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; + //depth_pool[overwritten_element] = depth_pool[requests_wb[index].node_index] + 1; }} }} @@ -708,23 +592,25 @@ where // that have been replaces base on timestamp information let invalidation_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("invalidation_pipeline_layout"), + label: Some("VoxelCache::invalidation_pipeline_layout"), bind_group_layouts: &[ - Some(&voxel_cache_bind_group_layout), + 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_pipeline = + let invalidation_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("invalidation_pipeline"), + label: Some("VoxelCache::invalidation_pass"), layout: Some(&invalidation_pipeline_layout), module: &device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("invalidation_pipeline_shader_module"), + label: Some("VoxelCache::invalidation_pass_shader_module"), source: wgpu::ShaderSource::Wgsl( format!(" - {wgsl_bindings} + {wgsl_cache_bindings} var frame_timestamp: u32; @@ -738,41 +624,45 @@ where let total_pool = arrayLength(&structure_pool); let total_table = arrayLength(&structure_table_pointers); - if index < total_pool + 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; - }} - }} + 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; - }} - index -= total_pool; - if index < total_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; - }} - }} + }} }} ") @@ -784,79 +674,192 @@ where 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, + }); + + // ~~ 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: StructureTable::new(device.clone(), queue.clone()), + structure_table, queue, device, structure_pool, attributes_pools, - depth_pool, location_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, - voxel_cache_bind_group, structure_table_bind_group_layout, - voxel_cache_render_bind_group_layout, - // Write requests stage - request_write_pipeline: write_requests, + request_pass, + caching_pass, + invalidation_pass, + reset_pass, + buffer_compactor, + sorter, - // Caching operation - caching_pipeline, + timestamp: 0, - // Invalidation - invalidation_pipeline, + user_bind_group_layout, } } - pub fn bind_group_layout(&self) -> BindGroupLayout + pub fn user_bind_group_layout(&self) -> &BindGroupLayout { - self.voxel_cache_render_bind_group_layout.clone() + &self.user_bind_group_layout } - pub fn bind_group(&self) -> BindGroup + 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("voxel_cache_render_bind_group"), - layout: &self.voxel_cache_render_bind_group_layout, + 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(), }, - // Color pool + // Attribute pool wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::BufferArray(attributes_bindings.as_slice()), }, - // Location pool - wgpu::BindGroupEntry { - binding: 2, - resource: self.location_pool.as_entire_binding(), - }, // Request buffer wgpu::BindGroupEntry { - binding: 3, - resource: self.request_buffer.request_buffer().as_entire_binding(), + binding: 2, + resource: self.request_buffer.as_entire_binding(), }, // Usage buffer wgpu::BindGroupEntry { - binding: 4, - resource: self.usage_buffer.usage_buffer().as_entire_binding(), + binding: 3, + resource: self.usage_buffer.as_entire_binding(), }, // Structure table // Structure table pointers wgpu::BindGroupEntry { - binding: 5, + binding: 4, resource: self.structure_table.pointer_table.as_entire_binding(), }, // Pools request count wgpu::BindGroupEntry { - binding: 6, + binding: 5, resource: self.structure_table.request_buffer.request_buffer().as_entire_binding(), }, ], @@ -865,58 +868,82 @@ where fn structure_table_bind_group(&self) -> BindGroup { - self.device.create_bind_group(&wgpu::BindGroupDescriptor - { - label: Some("structure_table_bind_group"), - layout: &self.structure_table_bind_group_layout, - entries: - &[ - wgpu::BindGroupEntry - { - binding: 0, - resource: self.structure_table.pointer_table.as_entire_binding(), - }, - wgpu::BindGroupEntry - { - binding: 1, - resource: self.structure_table.request_buffer.index_buffer().as_entire_binding(), - }, - wgpu::BindGroupEntry - { - binding: 2, - resource: self.structure_table.request_buffer.request_count_buffer().as_entire_binding(), - }, - ], - }) + 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 CommandEncoder, request_interface: &CacheProducerInterface) { - // Sort requests, reset request buffers to count requests - self.usage_buffer.sort_usage(encoder); - self.request_buffer.sort_requests(encoder); + // Sort request buffer + { + self.buffer_compactor + .compact_buffer( + &self.device, + encoder, + &self.request_buffer, + &self.sorted_request_buffer, + Some(&self.cache_scratch_buffer) + ); + self.buffer_compactor.copy_count_to_buffer(encoder, &self.request_count_buffer); + self.sorter + .sort( + &self.device, + &self.cache_scratch_buffer, + &self.sorted_request_buffer, + Some(&self.request_count_buffer), + None, + encoder, + radix_sort::RadixSortDirection::Descending + ); + } + + // Copy usage to scratch to preserve during sort + encoder.copy_buffer_to_buffer( + &self.usage_buffer, + 0, + &self.cache_scratch_buffer, + 0, (self.size * size_of::()) as u64); + + // Sort usage + self.sorter + .sort( + &self.device, + &self.cache_scratch_buffer, + &self.lru_list, + None, + Some(self.size), + encoder, + radix_sort::RadixSortDirection::Ascending + ); // Lowest (oldest) first + self.structure_table .request_buffer_mut() .sort_requests(encoder); // Sorted requests are now in the group - let mut write_requests_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { - label: Some("write_requests_pass"), + let mut request_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("VoxelCache::write_requests_pass"), timestamp_writes: None, }); - write_requests_pass.set_bind_group(0, Some(&self.voxel_cache_bind_group), &[]); - write_requests_pass.set_bind_group(1, Some(&self.structure_table_bind_group()), &[]); - write_requests_pass.set_bind_group(2, Some(&request_interface.request_side_bind_group), &[]); - write_requests_pass.set_pipeline(&self.request_write_pipeline); + 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); - write_requests_pass.dispatch_workgroups(workgroup_invocation_count as u32, 1, 1); - drop(write_requests_pass); - self.request_buffer.reset_requests(encoder); + request_pass.dispatch_workgroups(workgroup_invocation_count as u32, 1, 1); + drop(request_pass); + self.structure_table .request_buffer_mut() .reset_requests(encoder); @@ -924,14 +951,14 @@ where pub fn current_timestamp(&self) -> u32 { - self.usage_buffer.timestamp() + 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("cache_insertion_pass"), + label: Some("VoxelCache::cache_insertion_pass"), timestamp_writes: None, }); @@ -941,14 +968,17 @@ where // ~~~ Write data + Dirty flagging/timestamp update ~~~ { - cache_insertion_pass.set_pipeline(&self.caching_pipeline); - cache_insertion_pass.set_bind_group(0, Some(&self.voxel_cache_bind_group), &[]); - cache_insertion_pass.set_bind_group(1, Some(&structure_table_bind_group), &[]); - cache_insertion_pass.set_bind_group(2, Some(&cache_interface.request_side_bind_group), &[]); + 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.usage_buffer.timestamp(), + frame_timestamp: self.current_timestamp(), write_pointers: 0, // false }), ); @@ -962,10 +992,10 @@ where // ~~~ Invalidate pointers ~~~ { - cache_insertion_pass.set_pipeline(&self.invalidation_pipeline); - cache_insertion_pass.set_bind_group(2, None, &[]); + 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.usage_buffer.timestamp())); + .set_immediates(0, bytemuck::bytes_of(&self.timestamp)); // Compute dispatch amounts let shader_invocation_count = self.size + self.structure_table.allocation_table.len(); @@ -976,12 +1006,12 @@ where // ~~~ Write new pointers ~~~ { - cache_insertion_pass.set_pipeline(&self.caching_pipeline); - cache_insertion_pass.set_bind_group(2, Some(&cache_interface.request_side_bind_group), &[]); + 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.usage_buffer.timestamp(), + frame_timestamp: self.current_timestamp(), write_pointers: 1, // true }), ); @@ -993,11 +1023,68 @@ where 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.usage_buffer.next_frame(); + 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 + ) +} diff --git a/src/voxel_cache/indirect_buffer.rs b/src/voxel_cache/indirect_buffer.rs index 06a8d91..ff915d3 100644 --- a/src/voxel_cache/indirect_buffer.rs +++ b/src/voxel_cache/indirect_buffer.rs @@ -1,3 +1,4 @@ +use bytemuck::bytes_of; use wgpu::BindGroup; use wgpu::BindGroupLayout; use wgpu::Buffer; @@ -67,6 +68,17 @@ impl NonZeroBufferCompactor }, count: None, }, + // Optional compacted layout + 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, + }, ], }); @@ -116,7 +128,7 @@ impl NonZeroBufferCompactor device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("compaction_pipeline_layout"), bind_group_layouts: &[Some(&count_buffer_bg_layout), Some(&compaction_bg_layout)], - immediate_size: 0, + immediate_size: size_of::() as u32, // Bool : Write to compacted buffer ? }); let compaction_shader_module = unsafe { @@ -201,6 +213,7 @@ impl NonZeroBufferCompactor encoder: &mut CommandEncoder, count_buffer: &Buffer, index_buffer: &Buffer, + compact_buffer: Option<&Buffer>, ) { let count_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { @@ -215,6 +228,10 @@ impl NonZeroBufferCompactor binding: 1, resource: index_buffer.as_entire_binding(), }, + wgpu::BindGroupEntry { + binding: 2, + resource: compact_buffer.unwrap_or(&count_buffer).as_entire_binding(), + }, ], }); let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { @@ -235,6 +252,17 @@ impl NonZeroBufferCompactor // We can now reapply the partial running sum on the subblocks compute_pass.set_pipeline(&self.scatter_pipeline); + compute_pass.set_immediates( + 0, + if compact_buffer.is_some() + { + bytes_of(&1) + } + else + { + bytes_of(&0) + }, + ); compute_pass.dispatch_workgroups(self.block_count as u32, 1, 1); } } diff --git a/src/voxel_cache/layout.rs b/src/voxel_cache/layout.rs new file mode 100644 index 0000000..de38719 --- /dev/null +++ b/src/voxel_cache/layout.rs @@ -0,0 +1,25 @@ +#[derive(Clone, PartialEq, Eq, Default)] +pub struct VoxelCacheLayout +{ + pub(super) attributes: Vec, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub struct VoxelCacheAttribute +{ + pub word_count: u32, +} + +impl VoxelCacheLayout +{ + pub fn add_attribute(mut self, attribute: VoxelCacheAttribute) -> Self + { + self.attributes.push(attribute); + self + } + + pub fn attributes(&self) -> &[VoxelCacheAttribute] + { + &self.attributes + } +} diff --git a/src/voxel_cache/producer_interface.rs b/src/voxel_cache/producer_interface.rs index 3b76446..7c15265 100644 --- a/src/voxel_cache/producer_interface.rs +++ b/src/voxel_cache/producer_interface.rs @@ -21,6 +21,8 @@ use crate::voxel_cache::VoxelAttribute; use crate::voxel_cache::data::ColorPoolElement; use crate::voxel_cache::data::LocationPoolElement; use crate::voxel_cache::data::StructurePoolElement; +use crate::voxel_cache::layout::VoxelCacheAttribute; +use crate::voxel_cache::layout::VoxelCacheLayout; #[derive(Clone, Copy, Zeroable, Pod)] #[repr(C)] @@ -67,7 +69,7 @@ impl CacheProducerInterface where [(); N * N * N]:, { - pub fn new(size: usize, device: &Device, attributes: Vec) -> Self + pub fn new(size: usize, device: &Device, layout: &VoxelCacheLayout) -> Self { let requests = device.create_buffer(&wgpu::BufferDescriptor { label: Some("cache_interface_request_buffer"), @@ -91,7 +93,8 @@ where }); // Create attributes - let attributes_nodes = attributes + let attributes_nodes = layout + .attributes() .iter() .enumerate() .map(|(i, x)| { @@ -119,7 +122,7 @@ where }); let request_side_bind_group_layout = - Self::request_side_bind_group_layout(device, &attributes); + Self::request_side_bind_group_layout(device, layout.attributes()); let producer_side_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("cache_interface_producer_side_bind_group_layout"), @@ -166,7 +169,7 @@ where has_dynamic_offset: false, min_binding_size: None, }, - count: Some(NonZero::new(attributes.len() as u32).unwrap()), + count: Some(NonZero::new(layout.attributes().len() as u32).unwrap()), }, // Location nodes BindGroupLayoutEntry { @@ -309,7 +312,7 @@ where pub fn request_side_bind_group_layout( device: &Device, - attributes: &[VoxelAttribute], + attributes: &[VoxelCacheAttribute], ) -> BindGroupLayout { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { diff --git a/src/voxel_cache/request_buffer.rs b/src/voxel_cache/request_buffer.rs index ac2dedd..a7a203f 100644 --- a/src/voxel_cache/request_buffer.rs +++ b/src/voxel_cache/request_buffer.rs @@ -265,6 +265,7 @@ where encoder, &self.request_buffer, &self.index_buffer, + None, ); self.buffer_compactor @@ -287,6 +288,7 @@ where &self.keys_buffer, &self.index_buffer, Some(&self.request_count), + None, encoder, radix_sort::RadixSortDirection::Descending, ); diff --git a/src/voxel_cache/usage_buffer.rs b/src/voxel_cache/usage_buffer.rs index d2ee664..ab68c35 100644 --- a/src/voxel_cache/usage_buffer.rs +++ b/src/voxel_cache/usage_buffer.rs @@ -183,6 +183,7 @@ impl UsageBuffer &self.key_buffer, &self.index_buffer, None, + None, encoder, crate::gpu::radix_sort::RadixSortDirection::Ascending, );