From 48ff78f58dd3d98612621bc76f7c41240c916fa9 Mon Sep 17 00:00:00 2001 From: Albin Chaboissier Date: Thu, 15 Oct 2026 23:01:44 +0200 Subject: [PATCH] voxel_cache rewrite 1 --- src/gpu.rs | 1 + .../buffer_compactor.rs} | 0 src/voxel_cache.rs | 1315 ++--------------- src/voxel_cache/attributes.rs | 70 + src/voxel_cache/data.rs | 105 -- src/voxel_cache/eviction.rs | 123 ++ src/voxel_cache/layout.rs | 132 +- src/voxel_cache/producer_interface.rs | 390 ----- src/voxel_cache/request_buffer.rs | 296 ---- src/voxel_cache/requests.rs | 189 +++ src/voxel_cache/schema.rs | 151 ++ src/voxel_cache/shaders/eviction.wgsl | 17 + src/voxel_cache/shaders/requests.wgsl | 15 + src/voxel_cache/structure.rs | 127 ++ src/voxel_cache/structure_table.rs | 129 -- src/voxel_cache/usage_buffer.rs | 191 --- 16 files changed, 837 insertions(+), 2414 deletions(-) rename src/{voxel_cache/indirect_buffer.rs => gpu/buffer_compactor.rs} (100%) create mode 100644 src/voxel_cache/attributes.rs delete mode 100644 src/voxel_cache/data.rs create mode 100644 src/voxel_cache/eviction.rs delete mode 100644 src/voxel_cache/producer_interface.rs delete mode 100644 src/voxel_cache/request_buffer.rs create mode 100644 src/voxel_cache/requests.rs create mode 100644 src/voxel_cache/schema.rs create mode 100644 src/voxel_cache/shaders/eviction.wgsl create mode 100644 src/voxel_cache/shaders/requests.wgsl create mode 100644 src/voxel_cache/structure.rs delete mode 100644 src/voxel_cache/structure_table.rs delete mode 100644 src/voxel_cache/usage_buffer.rs diff --git a/src/gpu.rs b/src/gpu.rs index 73f1ea4..793750a 100644 --- a/src/gpu.rs +++ b/src/gpu.rs @@ -1,2 +1,3 @@ // Main common gpu parallel algorithms +pub mod buffer_compactor; pub mod radix_sort; diff --git a/src/voxel_cache/indirect_buffer.rs b/src/gpu/buffer_compactor.rs similarity index 100% rename from src/voxel_cache/indirect_buffer.rs rename to src/gpu/buffer_compactor.rs diff --git a/src/voxel_cache.rs b/src/voxel_cache.rs index 498a1fb..dd23223 100644 --- a/src/voxel_cache.rs +++ b/src/voxel_cache.rs @@ -1,1270 +1,133 @@ -use std::num::NonZero; +use wgpu::Device; -use bytemuck::{Zeroable, bytes_of}; -use tiff::encoder; -use wgpu::{BindGroup, BindGroupLayout, Buffer, BufferUsages, CommandEncoder, ComputePassDescriptor, ComputePipeline, Device, Queue, ShaderStages, naga::back::spv::Capability::Shader, util::DeviceExt}; +use crate::gpu::radix_sort::RadixSorter; +use crate::voxel_cache::eviction::CacheEvictor; +use crate::voxel_cache::requests::CacheRequestHandler; +use crate::voxel_cache::structure::CacheStructure; -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 attributes; +pub mod eviction; pub mod layout; +pub mod requests; +pub mod schema; +pub mod structure; + +/// Stores some ressources that can be reused throughout the modules of the cache +struct CacheRessources +{ + scratch_buffer: wgpu::Buffer, + radix_sorter: RadixSorter, +} + +impl CacheRessources +{ + pub fn new(device: &Device, page_count: usize) -> Self + { + let scratch_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("CacheRessources::scratch_buffer"), + usage: wgpu::BufferUsages::STORAGE, + size: (size_of::() * page_count * N * N * N) as u64, + mapped_at_creation: false, + }); + + let radix_sorter = RadixSorter::new(device, page_count * N * N * N); + + Self { + scratch_buffer, + radix_sorter, + } + } +} pub struct VoxelCache +where + [(); N * N * N]:, { - size: usize, - device: Device, - queue: Queue, + page_count: usize, + structure: CacheStructure, + request_handler: CacheRequestHandler, + evictor: CacheEvictor, - // 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, - - // To store the amount of pages that have been written in this insertion - written_pages: PageList, - - 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) } + common_ressources: CacheRessources, } impl VoxelCache where [(); N * N * N]:, { - pub fn new(cache_size: usize, device: Device, queue: Queue, layout: &VoxelCacheLayout) -> Self + pub fn new(device: &Device, page_count: usize) -> 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 structure = CacheStructure::new(device, 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 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, - }); - - let written_pages = PageList::new(&device, cache_size); - - // 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), - Some(written_pages.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() - { - copy_loops += &attribute.wgsl_copy_loop( - "attributes_pools", - "attributes_producer", - "overwritten_element", - "producer_index", - children_count, - attribute_index); - } - - 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; - - @group(5) @binding(0) var written_pages_count: u32; - @group(5) @binding(1) var written_pages_indices: 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; - }} - - written_pages_count = total; - - // Get index from lru eviction list - let overwritten_element = lru_list[index]; - - // Write into the written pages list - written_pages_indices[index] = overwritten_element; - - 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, - written_pages: PageList::new(&device, cache_size), - - 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, + page_count, + structure, + request_handler, + evictor, + common_ressources, } } - - 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<'_, '_, CommandEncoder>, 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 - } - - { - let mut indirect_usage_copy_pass = encoder.begin_profiled_compute_pass("indrect_compute_pass"); - - 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_profiled_compute_pass("VoxelCache::write_requests_pass"); - - 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 ScopeEncoder<'_, '_, 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_profiled_compute_pass("VoxelCache::cache_insertion_pass"); - // let mut cache_insertion_pass = encoder.begin_compute_pass(&ComputePassDescriptor - // { - // label: Some("mozeifj"), - // 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 ~~~ - { - gpu_profiler::begin_scope!(cache_insertion_pass, "Write pages"); - 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 ~~~ - { - gpu_profiler::begin_scope!(cache_insertion_pass, "Invalidation"); - 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 ~~~ - { - gpu_profiler::begin_scope!(cache_insertion_pass, "Pointer write"); - 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 - { - gpu_profiler::begin_scope!(cache_insertion_pass, "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; - } - - pub fn written_page_list(&self) -> &PageList - { - &self.written_pages - } - -} - -pub struct PageList -{ - max_size: usize, - // u32: page_count - count_buffer: Buffer, - - // Buffer of u32 indices into pages - list_buffer: Buffer, - - bind_group_layout: BindGroupLayout, - bind_group: BindGroup, -} - -impl PageList -{ - pub fn new(device: &Device, max_size: usize) -> Self - { - let count_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor - { - label: Some("PageList::count_buffer"), - contents: bytes_of(&0), - usage: BufferUsages::STORAGE, - }); - - let list_buffer = device.create_buffer(&wgpu::BufferDescriptor - { - label: Some("PageList::list_buffer"), - usage: BufferUsages::STORAGE, - size: (size_of::() * max_size) as u64, - mapped_at_creation: false, - }); - - let (bind_group_layout, bind_group) = create_multi_buffers_bg_bg_layout(device, &[&count_buffer, &list_buffer], Some("PageList::bind_group")); - PageList - { - max_size, - count_buffer, - list_buffer, - bind_group_layout, - bind_group, - } - } - - pub fn max_size(&self) -> usize { - self.max_size - } - - pub fn count_buffer(&self) -> &Buffer { - &self.count_buffer - } - - pub fn list_buffer(&self) -> &Buffer { - &self.list_buffer - } - - pub fn bind_group_layout(&self) -> &BindGroupLayout { - &self.bind_group_layout - } - - pub fn bind_group(&self) -> &BindGroup { - &self.bind_group - } } // Utilities -fn create_multi_buffers_bind_group_layout(device: &Device, count: u32, label: Option<&str>) -> BindGroupLayout +fn create_multi_buffers_bind_group_layout( + device: &Device, + count: u32, + label: Option<&str>, +) -> wgpu::BindGroupLayout { - let entries = (0..count).map(|i| - wgpu::BindGroupLayoutEntry - { + 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 }, + 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, - } - ).collect::>(); + }) + .collect::>(); - device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor - { + 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 +fn create_multi_buffers_bind_group( + device: &Device, + layout: &wgpu::BindGroupLayout, + buffers: &[&wgpu::Buffer], + label: Option<&str>, +) -> wgpu::BindGroup { - let entries = buffers.iter().enumerate().map(|(i, buffer)| - wgpu::BindGroupEntry - { + let entries = buffers + .iter() + .enumerate() + .map(|(i, buffer)| wgpu::BindGroupEntry { binding: i as u32, resource: buffer.as_entire_binding(), - } - ).collect::>(); + }) + .collect::>(); - device.create_bind_group(&wgpu::BindGroupDescriptor - { + 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) +fn create_multi_buffers_bg_bg_layout( + device: &Device, + buffers: &[&Buffer], + label: Option<&str>, +) -> (wgpu::BindGroupLayout, wgpu::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 - ) + (layout, bg) } diff --git a/src/voxel_cache/attributes.rs b/src/voxel_cache/attributes.rs new file mode 100644 index 0000000..00c51c1 --- /dev/null +++ b/src/voxel_cache/attributes.rs @@ -0,0 +1,70 @@ +use crate::voxel_cache::layout::CacheLayout; + +/// Contains instanciated gpu buffers to hold data for cache attributes +pub struct CacheAttributes +{ + attribute_buffers: Vec, + + bind_group_layout: wgpu::BindGroupLayout, + bind_group: wgpu::BindGroup, +} + +impl CacheAttributes +{ + pub fn from_cache_layout(device: &wgpu::Device, layout: &CacheLayout, page_count: usize) + -> Self + { + let attribute_buffers = layout + .attributes + .iter() + .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_bindings = attribute_buffers + .iter() + .map(|buffer| buffer.as_entire_buffer_binding()) + .collect::>(); + + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("CacheAttributes::bind_group"), + layout: &bind_group_layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::BufferArray(&bind_group_bindings), + }], + }); + + CacheAttributes { + attribute_buffers, + bind_group_layout, + bind_group, + } + } + + pub fn bind_group_layout(&self) -> &wgpu::BindGroupLayout + { + &self.bind_group_layout + } + + pub fn bind_group(&self) -> &wgpu::BindGroup + { + &self.bind_group + } +} diff --git a/src/voxel_cache/data.rs b/src/voxel_cache/data.rs deleted file mode 100644 index 2696ded..0000000 --- a/src/voxel_cache/data.rs +++ /dev/null @@ -1,105 +0,0 @@ -use bytemuck::Pod; -use bytemuck::Zeroable; -use wgpu::Buffer; - -use crate::sparse_tree::Color; - -#[derive(Clone, Copy, Zeroable, Pod, Debug)] -#[repr(C)] -pub struct CacheNodeRequest -{ - // Requested ressource - pub structure_id: u32, - pub structure_locator: u32, - - // Write back info - pub node_index: u32, - pub child_index: u32, -} - -pub struct RequestBufferElement -where - [(); N * N * N]:, -{ - request_count: [u32; N * N * N], -} - -#[repr(C)] -pub struct StructurePoolElement -where - [(); N * N * N]:, -{ - pub occupancy_low: u32, - pub occupancy_high: u32, - pub pointers: [StructurePointer; N * N * N], -} - -pub struct DestinationElement -{ - pub node: u32, - pub child: u32, -} - -pub struct ColorBytes(pub u8, pub u8, pub u8, pub u8); - -impl From for ColorBytes -{ - fn from(value: Color) -> Self - { - Self( - (value.0 * 255.) as u8, - (value.1 * 255.) as u8, - (value.2 * 255.) as u8, - (value.3 * 255.) as u8, - ) - } -} - -pub struct ColorPoolElement -where - [(); N * N * N]:, -{ - colors: [ColorBytes; N * N * N], -} - -pub struct LocationPoolElement -{ - pub structure_id: u32, - pub structure_locator: u32, -} - -pub struct CacheResponse -{ - // Each buffer contains the same amount of elements (structure of arrays style) - - // Cache data to bring in - pub structure_nodes: Buffer, - pub color_nodes: Buffer, - pub locations: Buffer, - - // Which nodes this extends : node_index + child_index - pub parents: Buffer, -} - -#[derive(Clone, Copy, Pod, Zeroable)] -#[repr(transparent)] -pub struct StructurePointer(pub u32); - -impl StructurePointer -{ - pub fn new(subdivided: bool, occupied: bool) -> Self - { - StructurePointer(((subdivided as u32) << 31) | ((occupied as u32) << 30)) - } -} - -#[derive(Clone, Copy, Zeroable)] -#[repr(C)] -pub struct ExplicitNTreeNode -where - [(); N * N * N]:, -{ - pub structure: [StructurePointer; N * N * N], - pub colors: [Color; N * N * N], - pub normals: [(f32, f32, f32); N * N * N], -} diff --git a/src/voxel_cache/eviction.rs b/src/voxel_cache/eviction.rs new file mode 100644 index 0000000..6ff92a9 --- /dev/null +++ b/src/voxel_cache/eviction.rs @@ -0,0 +1,123 @@ +/// Contains structure and logic related to eviction logic in the cache. +use wgpu::BindGroup; +use wgpu::CommandEncoder; +use wgpu::ComputePipeline; +use wgpu::include_wgsl; +use wgpu::util::DeviceExt; + +use crate::gpu::radix_sort; +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; + +/// 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 +pub struct CacheEvictor +{ + page_count: usize, + + /// Contains a u32 timestamp per page, so that we know when a page was last used + timestamp_pages: wgpu::Buffer, + + /// Contains indices in LRU order, after sorting + lru_list: wgpu::Buffer, + + // Reset lru list pass + reset_lru_list_bind_group: BindGroup, + reset_lru_list_pass: ComputePipeline, + reset_lru_list_dispatch: u32, +} + +impl CacheEvictor +{ + pub fn new(device: &wgpu::Device, page_count: usize, initial_timestamp: u32) -> Self + { + let timestamp_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("CacheUsage::timestamp_pages"), + usage: wgpu::BufferUsages::STORAGE, + contents: bytemuck::cast_slice(&vec![initial_timestamp; page_count]), + }); + + let lru_list = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("CacheUsage::lru_list"), + usage: wgpu::BufferUsages::STORAGE, + size: (page_count * size_of::()) as u64, + mapped_at_creation: false, + }); + + let (reset_lru_list_bg_layout, reset_lru_list_bind_group) = + create_multi_buffers_bg_bg_layout( + device, + [lru_list], + Some("CacheEvictor::reset_lru_list_bind_group"), + ); + + let reset_lru_list_pipeline_layout = + device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("CacheEvictor::reset_lru_list_pipeline_layout"), + bind_group_layouts: &[Some(&reset_lru_list_bg_layout)], + immediate_size: 0, + }); + + let reset_lru_list_pass = + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("CacheEvictor::reset_lru_list_pass"), + layout: Some(&reset_lru_list_pipeline_layout), + module: &device.create_shader_module(include_wgsl!("./shaders/eviction.wgsl")), + entry_point: Some("reset_lru_list"), + compilation_options: wgpu::PipelineCompilationOptions::default(), + cache: None, + }); + + Self { + page_count, + timestamp_pages, + lru_list, + + reset_lru_list_bind_group, + reset_lru_list_pass, + reset_lru_list_dispatch: page_count.div_ceil(256) as u32, + } + } + + pub fn prepare_eviction_list( + &self, + device: &wgpu::Device, + ressources: &CacheRessources, + encoder: &mut ScopeEncoder, + ) + { + gpu_profiler::begin_scope!(encoder, "CacheEvictor::prepare_eviction_list"); + // Use the scratch buffer as the sort work buffer + encoder.copy_buffer_to_buffer( + &self.timestamp_pages, + 0, + &ressources.scratch_buffer, + 0, + self.timestamp_pages.size(), + ); + + // Reset lru list + { + let mut reset_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("CacheEvictor::reset_pass"), + timestamp_writes: None, + }); + + reset_pass.set_bind_group(0, Some(&self.reset_lru_list_bind_group), &[]); + reset_pass.set_pipeline(&self.reset_lru_list_pass); + reset_pass.dispatch_workgroups(self.reset_lru_list_dispatch, 1, 1); + } + + ressources.radix_sorter.sort( + device, + &ressources.scratch_buffer, + &self.lru_list, + None, + Some(self.page_count), + &mut encoder, + radix_sort::RadixSortDirection::Ascending, + ); + } +} diff --git a/src/voxel_cache/layout.rs b/src/voxel_cache/layout.rs index 33aa5a1..4e4f7af 100644 --- a/src/voxel_cache/layout.rs +++ b/src/voxel_cache/layout.rs @@ -1,94 +1,72 @@ -#[derive(Clone, PartialEq, Eq, Default)] -pub struct VoxelCacheLayout -{ - pub(super) attributes: Vec, -} +use wgpu::BufferUsages; -#[derive(Clone, Copy, PartialEq, Eq)] -pub enum VoxelCacheAttributeRate +/// Defines how a [`VoxelCache`]'s attribute is populated upon populating a page +#[derive(Clone, Copy, Debug)] +pub enum CacheAttributeInit { - /// Attribute is per page - Page, + /// Attribute is external : it is copied from the insertion operation + External, - /// Attribute is per pointer in pages - Pointer, -} - -#[derive(Clone, Copy, PartialEq, Eq)] -pub enum VoxelCacheAttributeInit -{ - Copy, + /// Attribute will not be touched by the cache mechanism. It is left to the discrecy of the + /// cache user. + /// + /// Some applications requires pieces of data into the resident data of the cache that are + /// computed on the fly : e.g. global illumination DontTouch, } -#[derive(Clone, Copy, PartialEq, Eq)] -pub struct VoxelCacheAttribute +/// Describes an attribute of a [`VoxelCache`] +#[derive(Clone, Copy, Debug)] +pub struct CacheAttribute { + pub label: Option<&'static str>, pub word_count: u32, - pub rate: VoxelCacheAttributeRate, - pub init: VoxelCacheAttributeInit, + pub init: CacheAttributeInit, } -impl VoxelCacheLayout +impl CacheAttribute { - pub fn add_attribute(&mut self, attribute: VoxelCacheAttribute) -> usize + /// Creates the wgpu buffer necessary to store this attribute in the cache + pub fn create_buffer( + &self, + device: &wgpu::Device, + child_count: usize, + page_count: usize, + ) -> wgpu::Buffer + { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some( + format!( + "VoxelCacheAttribute ({}) {} word(s)", + self.label.unwrap_or("no-name"), + self.word_count + ) + .as_str(), + ), + size: (self.word_count as usize * page_count * child_count) as u64, + usage: BufferUsages::STORAGE, + mapped_at_creation: false, + }) + } +} + +#[derive(Clone, Default)] +pub struct CacheLayout +{ + pub(super) attributes: Vec, +} + +impl CacheLayout +{ + /// Adds a new [`VoxelCacheAttribute`] in the layout + /// + /// Attributes are added starting from 0 counting up + /// + /// Returns the index of the new added attirbute + pub fn add_attribute(&mut self, attribute: CacheAttribute) -> usize { let index = self.attributes.len(); self.attributes.push(attribute); index } - - pub fn attributes(&self) -> &[VoxelCacheAttribute] - { - &self.attributes - } -} - -impl VoxelCacheAttribute -{ - pub fn wgsl_copy_loop( - &self, - source_array: &str, - dest_array: &str, - - source_page_index: &str, - dest_page_index: &str, - - child_count: usize, - attribute_index: usize, - ) -> String - { - match self.init - { - VoxelCacheAttributeInit::Copy => - { - let real_child_count = match self.rate - { - VoxelCacheAttributeRate::Page => 1, - VoxelCacheAttributeRate::Pointer => child_count, - }; - let word_count = self.word_count; - let node_size = real_child_count * word_count as usize; - format!( - " - // Iterate on every children - for(var i = 0u; i < {real_child_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; - - {source_array}[{attribute_index}].values[{source_page_index} * {node_size} + offset] - = {dest_array}[{attribute_index}].values[{dest_page_index} * {node_size} + offset]; - }} - }} - - " - ) - } - VoxelCacheAttributeInit::DontTouch => String::from("// Attribute is DontTouch"), - } - } } diff --git a/src/voxel_cache/producer_interface.rs b/src/voxel_cache/producer_interface.rs deleted file mode 100644 index 7c15265..0000000 --- a/src/voxel_cache/producer_interface.rs +++ /dev/null @@ -1,390 +0,0 @@ -// The cache emits requests, and receives answer to these requests -// The cache producer interface provides the necessary buffers to contains -// these, so that use applications can fullfill the requests - -use std::num::NonZero; - -use bytemuck::Pod; -use bytemuck::Zeroable; -use wgpu::BindGroup; -use wgpu::BindGroupEntry; -use wgpu::BindGroupLayout; -use wgpu::BindGroupLayoutEntry; -use wgpu::Buffer; -use wgpu::BufferUsages; -use wgpu::CommandEncoder; -use wgpu::Device; -use wgpu::Queue; -use wgpu::util::DownloadBuffer; - -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)] -pub struct CacheRequest -{ - pub structure_id: u32, - pub locator: u32, - pub child_index: u32, -} - -pub(super) struct CacheRequestWbInfo -{ - node_index: u32, - child_index: u32, -} - -pub struct CacheProducerInterface -where - [(); N * N * N]:, -{ - // Request emissions - pub(super) size: usize, - - // Contains the specific node being requested - pub(super) requests: Buffer, - - // Contains how many request have effectively been emitted - pub(super) request_count: Buffer, - - // Contains on which node the request was done - pub(super) requests_wb_info: Buffer, - // Request fullfillment - pub(super) structure_nodes: Buffer, - pub(super) attributes_nodes: Vec, - pub(super) location_nodes: Buffer, - - pub(super) request_side_bind_group_layout: BindGroupLayout, - pub(super) request_side_bind_group: BindGroup, - - pub(super) producer_side_bind_group_layout: BindGroupLayout, - pub(super) producer_side_bind_group: BindGroup, -} -impl CacheProducerInterface -where - [(); N * N * N]:, -{ - pub fn new(size: usize, device: &Device, layout: &VoxelCacheLayout) -> Self - { - let requests = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("cache_interface_request_buffer"), - size: (size_of::() * size) as u64, - usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, - mapped_at_creation: false, - }); - - let requests_wb_info = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("cache_interface_writeback_info"), - size: (size_of::() * size) as u64, - usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, - mapped_at_creation: false, - }); - - let structure_nodes = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("cache_interface_structure_nodes"), - size: (size_of::>() * size) as u64, - usage: BufferUsages::STORAGE | BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - - // Create attributes - let attributes_nodes = 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 * size * size_of::()) as u64, - usage: BufferUsages::STORAGE | BufferUsages::COPY_DST, - mapped_at_creation: false, - }) - }) - .collect::>(); - - let location_nodes = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("cache_interface_structure_nodes"), - size: (size_of::() * size) as u64, - usage: BufferUsages::STORAGE | BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - - let request_count = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("cache_interface_request_count"), - size: (size_of::()) as u64, - usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, - mapped_at_creation: false, - }); - - let request_side_bind_group_layout = - 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"), - entries: &[ - // Reqests - BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::COMPUTE, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: true }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - // Request count - BindGroupLayoutEntry { - binding: 1, - visibility: wgpu::ShaderStages::COMPUTE, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: true }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - // Structure nodes - BindGroupLayoutEntry { - binding: 2, - 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, - }, - // Attributes nodes - BindGroupLayoutEntry { - binding: 3, - 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(NonZero::new(layout.attributes().len() as u32).unwrap()), - }, - // Location nodes - BindGroupLayoutEntry { - binding: 4, - 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, - }, - ], - }); - - // Bind groups - let attributes_bindings = attributes_nodes - .iter() - .map(|x| x.as_entire_buffer_binding()) - .collect::>>(); - let request_side_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("cache_interface_request_side_bind_group"), - layout: &request_side_bind_group_layout, - entries: &[ - BindGroupEntry { - binding: 0, - resource: requests.as_entire_binding(), - }, - BindGroupEntry { - binding: 1, - resource: requests_wb_info.as_entire_binding(), - }, - BindGroupEntry { - binding: 2, - resource: request_count.as_entire_binding(), - }, - BindGroupEntry { - binding: 3, - resource: structure_nodes.as_entire_binding(), - }, - BindGroupEntry { - binding: 4, - resource: wgpu::BindingResource::BufferArray(&attributes_bindings), - }, - BindGroupEntry { - binding: 5, - resource: location_nodes.as_entire_binding(), - }, - ], - }); - - let producer_side_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("cache_interface_producer_side_bind_group"), - layout: &producer_side_bind_group_layout, - entries: &[ - BindGroupEntry { - binding: 0, - resource: requests.as_entire_binding(), - }, - BindGroupEntry { - binding: 1, - resource: request_count.as_entire_binding(), - }, - BindGroupEntry { - binding: 2, - resource: structure_nodes.as_entire_binding(), - }, - BindGroupEntry { - binding: 3, - resource: wgpu::BindingResource::BufferArray(&attributes_bindings), - }, - BindGroupEntry { - binding: 4, - resource: location_nodes.as_entire_binding(), - }, - ], - }); - - Self { - size, - requests, - request_count, - requests_wb_info, - structure_nodes, - attributes_nodes, - location_nodes, - - request_side_bind_group_layout, - request_side_bind_group, - producer_side_bind_group_layout, - producer_side_bind_group, - } - } - - pub fn requests_buffer(&self) -> &Buffer - { - &self.requests - } - - pub fn structure_nodes_buffer(&self) -> &Buffer - { - &self.structure_nodes - } - - pub fn attributes_buffers(&self) -> &[Buffer] - { - &self.attributes_nodes - } - - pub fn location_nodes_buffer(&self) -> &Buffer - { - &self.location_nodes - } - - pub fn total_request_count(&self, device: &Device, queue: &Queue) -> u32 - { - let (tx, rx) = std::sync::mpsc::sync_channel(1); - wgpu::util::DownloadBuffer::read_buffer( - device, - queue, - &self.request_count.slice(0..), - move |download_buffer| { - let vec = download_buffer.unwrap().to_vec(); - let value = u32::from_ne_bytes(std::array::from_fn(|i| vec[i])); - let _ = tx.try_send(value); - }, - ); - - loop - { - if let Ok(value) = rx.try_recv() - { - return value; - } - device.poll(wgpu::wgt::PollType::Poll).unwrap(); - } - - //panic!("Could not retrieve total request count."); - } - - pub fn request_side_bind_group_layout( - device: &Device, - attributes: &[VoxelCacheAttribute], - ) -> BindGroupLayout - { - device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("cache_interface_request_side_bind_group_layout"), - entries: &[ - // Reqests - 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, - }, - // Requests writeback - 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: None, - }, - // Request count - BindGroupLayoutEntry { - binding: 2, - 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, - }, - // Structure nodes - BindGroupLayoutEntry { - binding: 3, - 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, - }, - // Attributes nodes - BindGroupLayoutEntry { - binding: 4, - 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(NonZero::new(attributes.len() as u32).unwrap()), - }, - // Location nodes - BindGroupLayoutEntry { - binding: 5, - 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, - }, - ], - }) - } -} diff --git a/src/voxel_cache/request_buffer.rs b/src/voxel_cache/request_buffer.rs deleted file mode 100644 index a7a203f..0000000 --- a/src/voxel_cache/request_buffer.rs +++ /dev/null @@ -1,296 +0,0 @@ -use bytemuck::bytes_of; -use wgpu::BindGroup; -use wgpu::BindGroupEntry; -use wgpu::Buffer; -use wgpu::BufferUsages; -use wgpu::CommandEncoder; -use wgpu::ComputePipeline; -use wgpu::Device; -use wgpu::ShaderStages; - -use crate::gpu::radix_sort; -use crate::gpu::radix_sort::RadixSorter; -use crate::voxel_cache::data::RequestBufferElement; -use crate::voxel_cache::indirect_buffer::NonZeroBufferCompactor; - -pub struct RequestBuffer -{ - pub device: Device, - pub cache_size: usize, - - pub request_buffer: Buffer, - pub keys_buffer: Buffer, - pub index_buffer: Buffer, - - pub request_count: Buffer, - - pub sorter: RadixSorter, - pub buffer_compactor: NonZeroBufferCompactor, - pub bindgroup: BindGroup, - pub reset_pass: ComputePipeline, - pub copy_pass: ComputePipeline, -} - -impl RequestBuffer -where - [(); N * N * N]:, -{ - pub fn new(cache_size: usize, device: Device) -> Self - { - let buffer_sizes = (size_of::() * cache_size * N * N * N) as u64; - // Contains request counts - let request_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some(format!("request_buffer_{N}").as_str()), - size: buffer_sizes, - usage: BufferUsages::STORAGE | BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - - // Contains indices compacted by compactor, and later sorted - let index_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some(format!("request_index_buffer_{N}").as_str()), - size: buffer_sizes, - usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, - mapped_at_creation: false, - }); - - // Used as keys for the sorter - let keys_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some(format!("request_sort_buffer_{N}").as_str()), - size: buffer_sizes, - usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, - mapped_at_creation: false, - }); - - // Amount of requests produced by non zero compactor - let request_count = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("request_count_storage_buffer"), - usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC | BufferUsages::COPY_DST, - size: size_of::() as u64, - mapped_at_creation: false, - }); - - let bindgroup_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("RequestCount::bindgroup_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, - }, - ], - }); - - let bindgroup = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("RequestCount::bindgroup"), - layout: &bindgroup_layout, - entries: &[ - BindGroupEntry { - binding: 0, - resource: request_buffer.as_entire_binding(), - }, - BindGroupEntry { - binding: 1, - resource: index_buffer.as_entire_binding(), - }, - BindGroupEntry { - binding: 2, - resource: keys_buffer.as_entire_binding(), - }, - BindGroupEntry { - binding: 3, - resource: request_count.as_entire_binding(), - }, - ], - }); - - let pipeline_layouts = &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("request_buffer_pipeline_layout"), - bind_group_layouts: &[Some(&bindgroup_layout)], - immediate_size: size_of::() as u32, - }); - - let reset_pass = - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("RequestBuffer::reset_pass"), - layout: Some(pipeline_layouts), - module: &device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("RequestBuffer::reset_pass_module"), - source: wgpu::ShaderSource::Wgsl( - #[allow(clippy::useless_format)] - format!(" - @group(0) @binding(0) var request_buffer: array; - @group(0) @binding(1) var index_buffer: array; - @group(0) @binding(2) var keys_buffer: array; - @group(0) @binding(3) var request_count: u32; - - @compute - @workgroup_size(256, 1, 1) - fn main( - @builtin(global_invocation_id) global_invocation_id: vec3 - ) - {{ - let total = arrayLength(&request_buffer); - if(global_invocation_id.x >= total) {{return;}} - request_buffer[global_invocation_id.x] = 0; - }} - ") - .into(), - ), - }), - entry_point: Some("main"), - compilation_options: Default::default(), - cache: None, - }); - - // This pipeline handles copying the request counts into the key buffer - // according to the compacted index_buffer - let copy_pass = - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("RequestBuffer::copy_pass"), - layout: Some(pipeline_layouts), - module: &device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("RequestBuffer::copy_pass_module"), - source: wgpu::ShaderSource::Wgsl( - #[allow(clippy::useless_format)] - format!(" - @group(0) @binding(0) var request_buffer: array; - @group(0) @binding(1) var index_buffer: array; - @group(0) @binding(2) var keys_buffer: array; - @group(0) @binding(3) var request_count: u32; - - @compute - @workgroup_size(256, 1, 1) - fn main( - @builtin(global_invocation_id) global_invocation_id: vec3 - ) - {{ - if(global_invocation_id.x >= request_count) {{return;}} - keys_buffer[global_invocation_id.x] = request_buffer[index_buffer[global_invocation_id.x]]; - }} - ") - .into(), - ), - }), - entry_point: Some("main"), - compilation_options: Default::default(), - cache: None, - }); - - Self { - cache_size, - request_buffer, - index_buffer, - keys_buffer, - request_count, - reset_pass, - copy_pass, - bindgroup, - buffer_compactor: NonZeroBufferCompactor::new(&device, cache_size * N * N * N), - sorter: RadixSorter::new(&device, cache_size * N * N * N), - device, - } - } - - pub fn request_buffer(&self) -> &Buffer - { - &self.request_buffer - } - - pub fn request_count_buffer(&self) -> &Buffer - { - &self.request_count - } - - pub fn index_buffer(&self) -> &Buffer - { - &self.index_buffer - } - - pub fn reset_requests(&self, encoder: &mut CommandEncoder) - { - let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { - label: Some("request_buffer_reset_compute_pass"), - timestamp_writes: None, - }); - - compute_pass.set_bind_group(0, Some(&self.bindgroup), &[]); - compute_pass.set_pipeline(&self.reset_pass); - - let shader_invocations = self.cache_size * N * N * N; // one invocation per element - let workgroup_invocations = shader_invocations.div_ceil(256); - compute_pass.dispatch_workgroups(workgroup_invocations as u32, 1, 1); - } - - pub fn sort_requests(&self, encoder: &mut CommandEncoder) - { - // Compact list - self.buffer_compactor.compact_buffer( - &self.device, - encoder, - &self.request_buffer, - &self.index_buffer, - None, - ); - - self.buffer_compactor - .copy_count_to_buffer(encoder, &self.request_count); - - let mut copy_keys_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { - label: Some("RequestBuffer::copy_keys_pass"), - timestamp_writes: None, - }); - - copy_keys_pass.set_bind_group(0, Some(&self.bindgroup), &[]); - copy_keys_pass.set_pipeline(&self.copy_pass); - let shader_invocations = self.cache_size * N * N * N; // one invocation per element - let workgroup_invocations = shader_invocations.div_ceil(256) as u32; - copy_keys_pass.dispatch_workgroups(workgroup_invocations, 1, 1); - drop(copy_keys_pass); - - self.sorter.sort( - &self.device, - &self.keys_buffer, - &self.index_buffer, - Some(&self.request_count), - None, - encoder, - radix_sort::RadixSortDirection::Descending, - ); - } -} diff --git a/src/voxel_cache/requests.rs b/src/voxel_cache/requests.rs new file mode 100644 index 0000000..ef9256c --- /dev/null +++ b/src/voxel_cache/requests.rs @@ -0,0 +1,189 @@ +use wgpu::BindGroup; +use wgpu::CommandEncoder; +use wgpu::ComputePipeline; +use wgpu::Device; +use wgpu::include_wgsl; +use wgpu::util::DeviceExt; + +use crate::gpu::buffer_compactor::NonZeroBufferCompactor; +use crate::gpu::radix_sort::{self}; +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::schema::RequestInformation; +use crate::voxel_cache::schema::RequestMeta; + +/// Records, handles, and produces a list of requested data inside the cache +pub struct CacheRequestHandler +{ + /// Contains a u32 per pointer of the cache, that records an amount of request by the cache user. + /// This can then be used to prioritize request based on demand + request_counts_pages: wgpu::Buffer, + + // Ultimately contains sorted requests + sorted_requests: wgpu::Buffer, + + compactor: NonZeroBufferCompactor, + + // Pass to reset the requests + reset_pass_bind_group: BindGroup, + reset_pass: ComputePipeline, + reset_pass_dispatch: u32, +} + +/// Records requests made by the cache +pub struct CacheRequestBuffer +{ + pub max_requests: usize, + + /// Buffer containing the amount of requests made by the cache, under max requsets + pub request_count: wgpu::Buffer, + + /// Buffer containing the requsets made by the cache, a dense array of [`voxel_cache::schema::RequestInformation`] + pub request_informations: wgpu::Buffer, + + /// Buffer containing the meta information about the requests, a dense array of [`voxel_cache::schema::RequestMeta`] + request_meta: wgpu::Buffer, +} + +impl CacheRequestHandler +{ + pub fn new(device: &wgpu::Device, page_count: usize) -> Self + { + let request_counts_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("CacheRequestHandler::request_counts_pages"), + usage: wgpu::BufferUsages::STORAGE, + contents: bytemuck::cast_slice(&vec![0u32; page_count * N * N * N]), + }); + + let sorted_requests = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("CacheRequestHandler::sorted_requests"), + usage: wgpu::BufferUsages::STORAGE, + contents: bytemuck::cast_slice(&vec![0u32; page_count * N * N * N]), + }); + + let (reset_pass_bg_layout, reset_pass_bind_group) = create_multi_buffers_bg_bg_layout( + device, + [request_counts_pages], + Some("CacheRequestHandler::reset_pass_bind_group"), + ); + + let reset_pass_pipeline_layout = + device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("CacheRequestHandler::reset_pass_pipeline_layout"), + bind_group_layouts: &[Some(&reset_pass_bg_layout)], + immediate_size: 0, + }); + + let reset_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("CacheRequestHandler::reset_pass"), + layout: Some(&reset_pass_pipeline_layout), + module: &device.create_shader_module(include_wgsl!("./shaders/requests.wgsl")), + entry_point: Some("reset_requests"), + compilation_options: wgpu::PipelineCompilationOptions::default(), + cache: None, + }); + + Self { + request_counts_pages, + sorted_requests, + compactor: NonZeroBufferCompactor::new(device, page_count), + + reset_pass_bind_group, + reset_pass, + reset_pass_dispatch: (page_count as u32).div_ceil(256), + } + } + + /// Sorts the requests currently held by the request handler in order to process them. + /// + /// Uses both the sorter and the scratch buffer in the ressources + /// + /// The `request_count` buffer will contain the amount of request produced this time. + pub fn sort_requests( + &self, + device: &wgpu::Device, + ressources: &CacheRessources, + request_count: &wgpu::Buffer, + encoder: &mut ScopeEncoder, + ) + { + gpu_profiler::begin_scope!(encoder, "RequestHandler::sort_requests"); + + // First perform a fast compaction sort + self.compactor.compact_buffer( + device, + &mut encoder, + &self.request_counts_pages, + &self.sorted_requests, + Some(&ressources.scratch_buffer), + ); + + self.compactor + .copy_count_to_buffer(&mut encoder, request_count); + + // State: + // At this point the `sorted_requests` buffer contains the compacted indices of the request counts + // and the scratch buffer contains the associated values + + // The indices can now be sorted using `sorted_requests` as values and + // `ressources.scratch_buffer` as keys for a sort operation + + // We use the amount of non zero request as the indirect count so that we can sort only the + // compacted, non-null requests + ressources.radix_sorter.sort( + device, + &ressources.scratch_buffer, + &self.sorted_requests, + Some(request_count), + None, + &mut encoder, + radix_sort::RadixSortDirection::Descending, + ); + } + + /// Resets the RequestHandlers request buffer for a next cache usage. + pub fn reset(&self, encoder: &mut ScopeEncoder) + { + let mut compute_pass = encoder.begin_profiled_compute_pass("CacheRequestHandler::reset"); + + compute_pass.set_bind_group(0, Some(&self.reset_pass_bind_group), &[]); + compute_pass.set_pipeline(&self.reset_pass); + compute_pass.dispatch_workgroups(self.reset_pass_dispatch, 1, 1); + } +} + +impl CacheRequestBuffer +{ + /// Creates a request buffer that can contain at most `max_amount` requests + pub fn new(device: &Device, max_requests: usize) -> Self + { + let request_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("CacheRequestBuffer::request_count"), + usage: wgpu::BufferUsages::STORAGE, + contents: bytemuck::bytes_of(&0u32), + }); + + let request_informations = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("CacheRequestBuffer::request_informations"), + usage: wgpu::BufferUsages::STORAGE, + size: (size_of::() * max_requests) as u64, + mapped_at_creation: false, + }); + + let request_meta = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("CacheRequestBuffer::request_meta"), + usage: wgpu::BufferUsages::STORAGE, + size: (size_of::() * max_requests) as u64, + mapped_at_creation: false, + }); + + Self { + max_requests, + request_count, + request_informations, + request_meta, + } + } +} diff --git a/src/voxel_cache/schema.rs b/src/voxel_cache/schema.rs new file mode 100644 index 0000000..31ae062 --- /dev/null +++ b/src/voxel_cache/schema.rs @@ -0,0 +1,151 @@ +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 +/// +/// Three states are possible : +/// +/// - unsubdivisable: This children of the node cannot be subdivided further +/// - subdivisable: This children of the node can be subdivided further ... +/// - unavailable: ... but is not currently available in the cache +/// - available: ... is currently available in the cache and the pointer is valid +/// +/// +/// The layout is the following +/// +/// - bit 31: subdivisable? +/// - bit 30: available? +/// - bit 0..29: pointer (only relevant if available is 1) +/// +#[derive(Clone, Copy, Debug, Zeroable, Pod)] +#[repr(transparent)] +pub struct CachePointer(u32); + +impl CachePointer +{ + /// First option represents subdivisability + /// Second option represents availability + /// + /// None -> unsubdivisable + /// Some(None) -> subdivisable not available + /// Some(Some(ptr)) -> subdivisable, available a pointer ptr + pub fn new(value: Option>) -> Self + { + CachePointer(match value + { + Some(available) => match available + { + Some(pointer) => + { + assert_eq!( + pointer >> 30, + 0, + "Provided pointer is to big and does not fit in CachePointer. Last two bits must be null." + ); + (1 << 31) | (1 << 30) | pointer + } + None => 1 << 31, + }, + None => 0, + }) + } + + pub fn as_option(&self) -> Option> + { + let subdivisable = (self.0 >> 31) != 0; + let available = ((self.0 >> 30) & 1) != 0; + let pointer = self.0 & 0x3FFFFFFF; + + match (subdivisable, available) + { + (false, true) => panic!("Invalid cache pointer. (not subdivisable and available)"), + (false, _) if pointer != 0 => + { + panic!("Invalid cache pointer. (non null unsubdivisable pointer)") + } + (false, _) => None, + (true, false) => Some(None), + (true, true) => Some(Some(pointer)), + } + } +} + +impl From for CachePointer +{ + fn from(value: u32) -> Self + { + CachePointer(value) + } +} + +/// Pages encoding the structure of the trees in the cache. +/// Occupancy mask is a mask containing a bit per children, based on whether it can be skipped +/// during raytracing. This can help faster tracing, and coalesce skips. +#[derive(Debug, Clone, Copy)] +#[repr(C)] +pub struct StructurePage +where + [(); N * N * N]:, +{ + pub occupancy_mask: u64, + pub pointers: [CachePointer; N * N * N], +} + +/// Data stored alongside cache structure so that application can locate a +/// particular request +#[derive(Debug, Clone, Copy, Zeroable, Pod)] +#[repr(C)] +pub struct LocationPage +{ + /// Identifier for the structure to which the node pertains + pub structure_id: u32, + + /// Identifier for locating this particular node within the structure + pub node_id: u32, +} + +/// Page storing the depth of the current node related to its root. +/// - 0xFFFFFFFF: Page unused +/// - 0..0xFFFFFFFF(excl): Depth +#[derive(Debug, Clone, Copy, Zeroable, Pod)] +#[repr(C)] +pub struct DepthPage(pub u32); + +impl DepthPage +{ + pub const PAGE_UNUSED: Self = DepthPage(u32::MAX); +} + +/// When the cache requests some information, it produces this structure, +/// which contains the node on which a subdivision is requested, as well which particular +/// children is needed +#[derive(Debug, Clone, Copy, Zeroable, Pod)] +#[repr(C)] +pub struct RequestInformation +{ + /// Identifier for the structure to which the node pertains + pub structure_id: u32, + + /// Identifier for locating this particular node within the structure + pub node_id: u32, + + /// The index of the children on which the request was issued + pub children_index: u32, +} + +/// Metainformation kept along each request, to know which node made the demand +#[derive(Debug, Clone, Copy, Zeroable, Pod)] +#[repr(C)] +pub struct RequestMeta +{ + /// The page on which the request was issued, with the special value 0xFFFFFFFF if the request + /// is external + pub page_index: u32, + + /// The children on which the request was issued + pub children_index: u32, +} diff --git a/src/voxel_cache/shaders/eviction.wgsl b/src/voxel_cache/shaders/eviction.wgsl new file mode 100644 index 0000000..a24d726 --- /dev/null +++ b/src/voxel_cache/shaders/eviction.wgsl @@ -0,0 +1,17 @@ +@group(0) @binding(0) lru_list: array; + +/// Resets the lru list +@compute +@workgroups(256, 1, 1) +fn reset_lru_list(@builting(global_invocation_id) global_invocation_id: vec3) +{ + let index = global_invocation_id.x; + if(index >= array_length(&request_count_pages)) + { + return; + } + + // Indicies must be reset to id, so that the sort operation can use them as values, + // and the timestamps as keys + request_count_pages = index; +} diff --git a/src/voxel_cache/shaders/requests.wgsl b/src/voxel_cache/shaders/requests.wgsl new file mode 100644 index 0000000..075fd4e --- /dev/null +++ b/src/voxel_cache/shaders/requests.wgsl @@ -0,0 +1,15 @@ +@group(0) @binding(0) request_count_pages: array; + +/// Resets the requests +@compute +@workgroups(256, 1, 1) +fn reset_requests(@builting(global_invocation_id) global_invocation_id: vec3) +{ + let index = global_invocation_id.x; + if(index >= array_length(&request_count_pages)) + { + return; + } + + request_count_pages = 0; +} diff --git a/src/voxel_cache/structure.rs b/src/voxel_cache/structure.rs new file mode 100644 index 0000000..18916d7 --- /dev/null +++ b/src/voxel_cache/structure.rs @@ -0,0 +1,127 @@ +use wgpu::BindGroup; +use wgpu::BindGroupLayout; +use wgpu::Buffer; +use wgpu::BufferUsages; +use wgpu::util::DeviceExt; + +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 +{ + pointer_pages: Buffer, + location_pages: Buffer, + depth_pages: Buffer, + + bind_group_layout: BindGroupLayout, + bind_group: BindGroup, +} + +impl CacheStructure +where + [(); N * N * N]:, +{ + pub const POINTER_PAGES_BINDING: u32 = 0; + pub const LOCATION_PAGES_BINDING: u32 = 1; + pub const DEPTH_PAGES_BINDING: u32 = 2; + + pub fn new(device: &wgpu::Device, page_count: usize) -> Self + { + let pointer_pages = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("CacheStructure::pointer_pages"), + size: (size_of::>() * page_count) as u64, + usage: BufferUsages::STORAGE, + mapped_at_creation: false, + }); + + let location_pages = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("CacheStructure::location_pages"), + size: (size_of::>() * page_count) as u64, + usage: BufferUsages::STORAGE, + mapped_at_creation: false, + }); + + // Depth pages need to be initialized to unused, this prioritizes them in the + // depth sort used in the eviction pass + let depth_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("CacheStructure::location_pages"), + usage: BufferUsages::STORAGE, + 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(), + }, + ], + }); + + CacheStructure { + pointer_pages, + location_pages, + depth_pages, + + bind_group_layout, + bind_group, + } + } + + pub fn bind_group_layout(&self) -> &BindGroupLayout + { + &self.bind_group_layout + } + + pub fn bind_group(&self) -> &BindGroup + { + &self.bind_group + } +} diff --git a/src/voxel_cache/structure_table.rs b/src/voxel_cache/structure_table.rs deleted file mode 100644 index 3da63c4..0000000 --- a/src/voxel_cache/structure_table.rs +++ /dev/null @@ -1,129 +0,0 @@ -use std::num::NonZero; - -use wgpu::Buffer; -use wgpu::BufferUsages; -use wgpu::CommandEncoder; -use wgpu::Device; -use wgpu::Queue; -use wgpu::util::StagingBelt; - -use crate::voxel_cache::data::StructurePointer; -use crate::voxel_cache::request_buffer::RequestBuffer; - -// Stores root pointers to the cache -pub struct StructureTable -{ - pub(crate) device: Device, - pub(crate) queue: Queue, - pub(crate) allocation_table: Vec, - pub(crate) available_slots: usize, - pub(crate) pointer_table: Buffer, - pub(crate) request_buffer: RequestBuffer<1>, - pub(crate) write_staging: StagingBelt, -} - -impl StructureTable -{ - pub fn new(device: Device, queue: Queue) -> Self - { - let pointer_table = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("structure_table_pointer_table"), - size: size_of::() as u64, - usage: BufferUsages::STORAGE | BufferUsages::COPY_DST | BufferUsages::COPY_SRC, - mapped_at_creation: false, - }); - - StructureTable { - request_buffer: RequestBuffer::new(1, device.clone()), - write_staging: StagingBelt::new(device.clone(), size_of::() as u64), - device, - queue, - allocation_table: vec![false], - available_slots: 1, - pointer_table, - } - } - - fn double_capacity(&mut self, encoder: &mut CommandEncoder) - { - self.available_slots += self.allocation_table.len(); - self.allocation_table - .extend(vec![false; self.allocation_table.len()]); - - // Copy buffers into bigger buffers - let pointer_table = self.device.create_buffer(&wgpu::BufferDescriptor { - label: Some("structure_table_pointer_table"), - size: size_of::() as u64 * self.allocation_table.len() as u64, - usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC | BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - - encoder.copy_buffer_to_buffer( - &self.pointer_table, - 0, - &pointer_table, - 0, - self.pointer_table.size(), - ); - - self.pointer_table = pointer_table; - self.request_buffer = RequestBuffer::new(self.allocation_table.len(), self.device.clone()); - } - - pub fn request_buffer(&self) -> &RequestBuffer<1> - { - &self.request_buffer - } - - pub fn request_buffer_mut(&mut self) -> &mut RequestBuffer<1> - { - &mut self.request_buffer - } - - pub fn remove_structure(&mut self, structure_id: u32) - { - self.available_slots += 1; - self.allocation_table[structure_id as usize] = false; - } - - // Returns a structure Id - pub fn allocate_structure(&mut self, subdivided: bool) -> u32 - { - let mut encoder = self - .device - .create_command_encoder(&wgpu::CommandEncoderDescriptor { - label: Some("structure_table_resize_encoder"), - }); - - // Get first available element - if self.available_slots == 0 - { - self.double_capacity(&mut encoder); - } - let (first_id, _) = self - .allocation_table - .iter() - .enumerate() - .filter(|(_, allocated)| !**allocated) - .next() - .unwrap(); - self.allocation_table[first_id] = true; - self.available_slots -= 1; - - // Write empty pointer to new pointer - self.write_staging - .write_buffer( - &mut encoder, - &self.pointer_table, - size_of::() as u64 * first_id as u64, - NonZero::new(size_of::() as u64).unwrap(), - ) - .copy_from_slice(bytemuck::bytes_of( - &StructurePointer::new(subdivided, false).0, - )); - self.write_staging.finish_and_recall_on_submit(&encoder); - self.queue.submit([encoder.finish()]); - - first_id as u32 - } -} diff --git a/src/voxel_cache/usage_buffer.rs b/src/voxel_cache/usage_buffer.rs deleted file mode 100644 index ab68c35..0000000 --- a/src/voxel_cache/usage_buffer.rs +++ /dev/null @@ -1,191 +0,0 @@ -use std::ops::Div; - -use bytemuck::bytes_of; -use wgpu::BindGroup; -use wgpu::BindGroupEntry; -use wgpu::Buffer; -use wgpu::BufferUsages; -use wgpu::CommandEncoder; -use wgpu::ComputePipeline; -use wgpu::Device; -use wgpu::ShaderStages; - -use crate::gpu::radix_sort::RadixSorter; - -pub struct UsageBuffer -{ - pub cache_size: usize, - pub current_timestamp: u32, - - pub usage_buffer: Buffer, - pub key_buffer: Buffer, - pub index_buffer: Buffer, - - pub index_bind_group: BindGroup, - pub init_indices_pass: ComputePipeline, - - pub sorter: RadixSorter, - pub device: Device, -} - -impl UsageBuffer -{ - pub fn new(cache_size: usize, device: Device) -> Self - { - let initial_timestamp = 0; - let usage_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("UsageBuffer::usage_buffer"), - size: (size_of::() * cache_size) as u64, - usage: BufferUsages::STORAGE | BufferUsages::COPY_DST | BufferUsages::COPY_SRC, - mapped_at_creation: true, - }); - - let key_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("UsageBuffer::key_buffer"), - size: (size_of::() * cache_size) as u64, - usage: BufferUsages::STORAGE | BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - - let index_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("UsageBuffer::key_buffer"), - size: (size_of::() * cache_size) as u64, - usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, - mapped_at_creation: false, - }); - - usage_buffer - .get_mapped_range_mut(0..) - .unwrap() - .copy_from_slice(bytemuck::cast_slice( - vec![initial_timestamp; cache_size].as_slice(), - )); - usage_buffer.unmap(); - - let bindgroup_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("UsageBuffer::bindgroup_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, - }], - }); - - let index_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("UsageBuffer::index_bindgroup"), - layout: &bindgroup_layout, - entries: &[BindGroupEntry { - binding: 0, - resource: index_buffer.as_entire_binding(), - }], - }); - - let pipeline_layout = &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("UsageBuffer::pipeline_layout"), - bind_group_layouts: &[Some(&bindgroup_layout)], - immediate_size: 0, - }); - - let init_indices_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("UsageBuffer::init_indices_pass"), - layout: Some(pipeline_layout), - module: &device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("clear_chunk_requests shader module"), - source: wgpu::ShaderSource::Wgsl( - " - @group(0) @binding(0) var index_buffer: array; - - @compute - @workgroup_size(256) - fn main( - @builtin(global_invocation_id) global_invocation_id: vec3 - ) - {{ - let total = arrayLength(&index_buffer); - if(global_invocation_id.x < total) - {{ - index_buffer[global_invocation_id.x] = global_invocation_id.x; - }} - }} - " - .into(), - ), - }), - entry_point: Some("main"), - compilation_options: Default::default(), - cache: None, - }); - - Self { - cache_size, - current_timestamp: initial_timestamp, - usage_buffer, - key_buffer, - index_buffer, - index_bind_group, - init_indices_pass, - sorter: RadixSorter::new(&device, cache_size), - device, - } - } - - pub fn timestamp(&self) -> u32 - { - self.current_timestamp - } - - pub fn next_frame(&mut self) - { - let (new_timestamp, _) = self.current_timestamp.overflowing_add(1); - self.current_timestamp = new_timestamp; - } - - pub fn usage_buffer(&self) -> &Buffer - { - &self.usage_buffer - } - - pub fn sort_buffer(&self) -> &Buffer - { - &self.index_buffer - } - - pub fn sort_usage(&self, encoder: &mut CommandEncoder) - { - // Copy keys to sort buffer - encoder.copy_buffer_to_buffer( - &self.usage_buffer, - 0, - &self.key_buffer, - 0, - (self.cache_size * size_of::()) as u64, - ); - - // Compute pass to initialize sorting indices - let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { - label: Some("UsageBuffer::compute_pass"), - timestamp_writes: None, - }); - - compute_pass.set_bind_group(0, &self.index_bind_group, &[]); - compute_pass.set_pipeline(&self.init_indices_pass); - compute_pass.dispatch_workgroups(self.cache_size.div_ceil(256) as u32, 1, 1); - - drop(compute_pass); - - self.sorter.sort( - &self.device, - &self.key_buffer, - &self.index_buffer, - None, - None, - encoder, - crate::gpu::radix_sort::RadixSortDirection::Ascending, - ); - } -}