From 1117647ca701941de7e297a8ef66e51c55270e7f Mon Sep 17 00:00:00 2001 From: Albin Chaboissier Date: Sun, 8 Nov 2026 01:47:30 +0100 Subject: [PATCH] topk implementation --- src/gi_pipeline.rs | 3 +- src/gpu.rs | 1 + src/gpu/radix_sort.rs | 5 + src/gpu/shaders/top_k.wgsl | 119 ++++ src/gpu/top_k.rs | 635 +++++++++++++++++++ src/main.rs | 12 +- src/production.rs | 60 ++ src/production/host_production.rs | 69 ++ src/production/tree_locator.rs | 422 ++++++++++++ src/terrain.rs | 10 +- src/voxel_cache.rs | 22 +- src/voxel_cache/requests.rs | 154 ++++- src/voxel_cache/shaders/gather_requests.wgsl | 25 + src/voxel_cache/shaders/invalidation.wgsl | 5 +- src/voxel_cache/tables.rs | 17 +- 15 files changed, 1518 insertions(+), 41 deletions(-) create mode 100644 src/gpu/shaders/top_k.wgsl create mode 100644 src/gpu/top_k.rs create mode 100644 src/production.rs create mode 100644 src/production/host_production.rs create mode 100644 src/production/tree_locator.rs create mode 100644 src/voxel_cache/shaders/gather_requests.wgsl diff --git a/src/gi_pipeline.rs b/src/gi_pipeline.rs index 508b54c..c0b01d0 100644 --- a/src/gi_pipeline.rs +++ b/src/gi_pipeline.rs @@ -23,6 +23,7 @@ where pub fn new( device: &wgpu::Device, cache_size: usize, + max_requests: usize, cache_layout: &mut voxel_cache::CacheLayout, ) -> Self { @@ -38,7 +39,7 @@ where init: voxel_cache::CacheAttributeInit::DontTouch, }); - let voxel_cache = VoxelCache::new(device, cache_size, cache_layout); + let voxel_cache = VoxelCache::new(device, cache_size, max_requests, cache_layout); Self { voxel_cache, diff --git a/src/gpu.rs b/src/gpu.rs index f2346ba..91d3555 100644 --- a/src/gpu.rs +++ b/src/gpu.rs @@ -2,6 +2,7 @@ pub mod buffer_compactor; pub mod indirect_buffer; pub mod radix_sort; +pub mod top_k; // Utilities pub fn create_multi_buffers_bind_group_layout( diff --git a/src/gpu/radix_sort.rs b/src/gpu/radix_sort.rs index 2ea149f..9ccea5e 100644 --- a/src/gpu/radix_sort.rs +++ b/src/gpu/radix_sort.rs @@ -320,6 +320,11 @@ impl RadixSorter } } + /// Performs a radix sort on the `key` based on the `values`. + /// The keys are paired one-to-one with the values. At the end both keys and values are sorted. + /// An indirect count can be passed in `indirect` as a buffer of a single u32 on GPU. + /// A CPU side length can be passed in `direct_length` + /// `sort_direction` dictates the direction of the sort. pub fn sort( &self, device: &Device, diff --git a/src/gpu/shaders/top_k.wgsl b/src/gpu/shaders/top_k.wgsl new file mode 100644 index 0000000..b962dba --- /dev/null +++ b/src/gpu/shaders/top_k.wgsl @@ -0,0 +1,119 @@ +// Top-k selection over a dense array of u32 request counts. +// +// The Rust side prepends the following constants: +// const BIN_COUNT: u32; +// const SUB_BINS: u32; +// const LOG_SUB_BINS: u32; +// const WORKGROUP_SIZE: u32; + +@group(0) @binding(0) var requests: array; +@group(0) @binding(1) var histogram: array>; +@group(0) @binding(2) var threshold: i32; +@group(0) @binding(3) var selected_count: atomic; +@group(0) @binding(4) var selected_indices: array; + +struct TopKParams +{ + element_count: u32, + k: u32, +} + +var params: TopKParams; + +// Monotonic log-scale quantization. Counts of zero are never candidates, but +// the function is kept total so it is safe to call with any value. +fn quantize(count: u32) -> u32 +{ + if (count == 0u) + { + return 0u; + } + + let exponent = 31u - countLeadingZeros(count); + var extra: u32; + + if (exponent >= LOG_SUB_BINS) + { + extra = (count >> (exponent - LOG_SUB_BINS)) & (SUB_BINS - 1u); + } + else + { + extra = (count << (LOG_SUB_BINS - exponent)) & (SUB_BINS - 1u); + } + + return exponent * SUB_BINS + extra; +} + +// Pass 1: quantize every non-zero count and accumulate the global histogram. +@compute +@workgroup_size(WORKGROUP_SIZE, 1, 1) +fn histogram_pass(@builtin(global_invocation_id) global_id: vec3) +{ + let index = global_id.x; + if (index >= params.element_count) + { + return; + } + + let count = requests[index]; + if (count == 0u) + { + return; + } + + let bin = quantize(count); + atomicAdd(&histogram[bin], 1u); +} + +// Pass 2: scan the histogram from the highest bin down until adding the +// current bin would reach k. The current bin becomes the threshold. +// A threshold of -1 means that every non-zero element is selected. +@compute +@workgroup_size(1, 1, 1) +fn threshold_pass() +{ + var sum: u32 = 0u; + var threshold_bin: i32 = -1; + + for (var bin: u32 = BIN_COUNT; bin > 0u; bin = bin - 1u) + { + let count = atomicLoad(&histogram[bin - 1u]); + + if (sum + count >= params.k) + { + threshold_bin = i32(bin - 1u); + break; + } + + sum = sum + count; + } + + threshold = threshold_bin; + atomicStore(&selected_count, 0u); +} + +// Pass 3: emit the indices whose quantized bin is strictly above the +// threshold. The order of the output list is arbitrary. +@compute +@workgroup_size(WORKGROUP_SIZE, 1, 1) +fn select_pass(@builtin(global_invocation_id) global_id: vec3) +{ + let index = global_id.x; + if (index >= params.element_count) + { + return; + } + + let count = requests[index]; + if (count == 0u) + { + return; + } + + let bin = quantize(count); + if (i32(bin) > threshold) + { + let slot = atomicAdd(&selected_count, 1u); + selected_indices[slot] = index; + } +} diff --git a/src/gpu/top_k.rs b/src/gpu/top_k.rs new file mode 100644 index 0000000..38c8298 --- /dev/null +++ b/src/gpu/top_k.rs @@ -0,0 +1,635 @@ +//! GPU top-k selection over a dense array of `u32` request counts. +//! +//! The selector runs three compute passes: +//! 1. Quantize every non-zero count into [`BIN_COUNT`] log-scale bins and build +//! a global histogram. +//! 2. Scan the histogram from the highest bin down until adding the current bin +//! would reach `k`, producing a threshold bin. +//! 3. Emit the indices of the elements whose bin is strictly above the +//! threshold bin. +//! +//! The number of selected elements is therefore at most `k` (in practice it is +//! strictly less than `k` when `k > 0`, because the whole threshold bin is +//! excluded). The threshold bin and the selected count are exposed so a later +//! pass can fill the remaining slots to reach exactly `k`. +//! +//! The output list is unordered: indices are appended with atomics. +//! +//! The selector uses shader immediates, so the device must enable +//! [`wgpu::Features::IMMEDIATES`] and expose a `max_immediate_size` of at least +//! `size_of::()` (8 bytes). + +use bytemuck::bytes_of; +use wgpu::BindGroupLayout; +use wgpu::Buffer; +use wgpu::BufferUsages; +use wgpu::CommandEncoder; +use wgpu::ComputePipeline; +use wgpu::Device; +use wgpu::ShaderStages; +use wgpu::util::DeviceExt; + +/// Number of quantization bins. +pub const BIN_COUNT: u32 = 256; + +/// Number of sub-bins per power-of-two octave. +const SUB_BINS: u32 = BIN_COUNT / 32; + +/// Number of mantissa bits kept by the quantizer. +const LOG_SUB_BINS: u32 = SUB_BINS.trailing_zeros(); + +/// Threads per workgroup for the histogram and selection passes. +const WORKGROUP_SIZE: u32 = 256; + +const _: () = assert!(BIN_COUNT % 32 == 0); +const _: () = assert!(SUB_BINS.is_power_of_two()); + +/// Parameters passed to the shader through immediates. +#[repr(C)] +#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +struct TopKParams +{ + element_count: u32, + k: u32, +} + +/// GPU top-k selector over a dense array of request counts. +/// +/// The selector owns its scratch and output buffers, so a single instance +/// cannot be used for two overlapping selections. Create one instance per +/// concurrent selection, or copy the results before the next call. +pub struct TopKSelector +{ + max_selected: u32, + + histogram: Buffer, + threshold: Buffer, + selected_count: Buffer, + selected_indices: Buffer, + + bind_group_layout: BindGroupLayout, + histogram_pass: ComputePipeline, + threshold_pass: ComputePipeline, + select_pass: ComputePipeline, +} + +impl TopKSelector +{ + /// Creates a selector that can output at most `max_selected` indices. + pub fn new(device: &Device, max_selected: u32) -> Self + { + assert!( + device.features().contains(wgpu::Features::IMMEDIATES), + "TopKSelector requires the IMMEDIATES feature" + ); + assert!( + device.limits().max_immediate_size >= size_of::() as u32, + "TopKSelector requires a max_immediate_size of at least {} bytes", + size_of::() + ); + + let histogram = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("TopKSelector::histogram"), + size: (BIN_COUNT as u64) * (size_of::() as u64), + usage: BufferUsages::STORAGE | BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + + let threshold = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("TopKSelector::threshold"), + contents: bytes_of(&-1i32), + usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, + }); + + let selected_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("TopKSelector::selected_count"), + contents: bytes_of(&0u32), + usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, + }); + + // Avoid zero-sized buffers when `max_selected == 0`. + let selected_indices = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("TopKSelector::selected_indices"), + size: (max_selected.max(1) as u64) * (size_of::() as u64), + usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, + mapped_at_creation: false, + }); + + let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("TopKSelector::bind_group_layout"), + entries: &[ + // Requests: read-only dense array of counts + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: true }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + // Histogram + 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, + }, + // Threshold bin + 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, + }, + // Selected count + 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, + }, + // Selected indices + 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, + }, + ], + }); + + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("TopKSelector::pipeline_layout"), + bind_group_layouts: &[Some(&bind_group_layout)], + immediate_size: size_of::() as u32, + }); + + // Inject the quantization constants so the Rust and WGSL sides cannot + // drift apart. + let header = format!( + "const BIN_COUNT: u32 = {}u;\n\ + const SUB_BINS: u32 = {}u;\n\ + const LOG_SUB_BINS: u32 = {}u;\n\ + const WORKGROUP_SIZE: u32 = {}u;\n", + BIN_COUNT, SUB_BINS, LOG_SUB_BINS, WORKGROUP_SIZE + ); + + let mut shader_source = String::with_capacity(header.len() + 2048); + shader_source.push_str(&header); + shader_source.push_str(include_str!("./shaders/top_k.wgsl")); + + let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("TopKSelector::shader_module"), + source: wgpu::ShaderSource::Wgsl(shader_source.into()), + }); + + let compilation_options = wgpu::PipelineCompilationOptions::default(); + + let histogram_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("TopKSelector::histogram_pass"), + layout: Some(&pipeline_layout), + module: &shader_module, + entry_point: Some("histogram_pass"), + compilation_options: compilation_options.clone(), + cache: None, + }); + + let threshold_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("TopKSelector::threshold_pass"), + layout: Some(&pipeline_layout), + module: &shader_module, + entry_point: Some("threshold_pass"), + compilation_options: compilation_options.clone(), + cache: None, + }); + + let select_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("TopKSelector::select_pass"), + layout: Some(&pipeline_layout), + module: &shader_module, + entry_point: Some("select_pass"), + compilation_options, + cache: None, + }); + + Self { + max_selected, + histogram, + threshold, + selected_count, + selected_indices, + bind_group_layout, + histogram_pass, + threshold_pass, + select_pass, + } + } + + /// Runs the three top-k passes over `requests[0..element_count]`. + /// + /// `k` is the requested number of elements and must not exceed the + /// `max_selected` capacity given to [`TopKSelector::new`]. + /// + /// After this call: + /// - [`Self::selected_count_buffer`] contains the number of emitted indices. + /// - [`Self::selected_indices_buffer`] contains that many indices, in an + /// arbitrary order. + /// - [`Self::threshold_buffer`] contains the threshold bin, or `-1` if all + /// non-zero elements were selected. + pub fn select( + &self, + device: &Device, + encoder: &mut CommandEncoder, + requests: &Buffer, + element_count: u32, + k: u32, + ) + { + assert!( + k <= self.max_selected, + "TopKSelector: k ({k}) exceeds the max_selected capacity ({})", + self.max_selected + ); + assert!( + requests.size() >= (element_count as u64) * (size_of::() as u64), + "TopKSelector: requests buffer is too small for {element_count} elements" + ); + + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("TopKSelector::bind_group"), + layout: &self.bind_group_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: requests.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: self.histogram.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: self.threshold.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: self.selected_count.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: self.selected_indices.as_entire_binding(), + }, + ], + }); + + // The histogram is rebuilt from scratch on every call. + encoder.clear_buffer(&self.histogram, 0, None); + + let params = TopKParams { element_count, k }; + let params_bytes = bytes_of(¶ms); + let workgroup_count = element_count.div_ceil(WORKGROUP_SIZE).max(1); + + let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("TopKSelector::select"), + timestamp_writes: None, + }); + + compute_pass.set_bind_group(0, &bind_group, &[]); + + compute_pass.set_pipeline(&self.histogram_pass); + compute_pass.set_immediates(0, params_bytes); + compute_pass.dispatch_workgroups(workgroup_count, 1, 1); + + compute_pass.set_pipeline(&self.threshold_pass); + compute_pass.set_immediates(0, params_bytes); + compute_pass.dispatch_workgroups(1, 1, 1); + + compute_pass.set_pipeline(&self.select_pass); + compute_pass.set_immediates(0, params_bytes); + compute_pass.dispatch_workgroups(workgroup_count, 1, 1); + } + + /// Number of indices emitted by the last [`Self::select`] call. + pub fn selected_count_buffer(&self) -> &Buffer + { + &self.selected_count + } + + /// Indices emitted by the last [`Self::select`] call, in arbitrary order. + pub fn selected_indices_buffer(&self) -> &Buffer + { + &self.selected_indices + } + + /// Threshold bin of the last [`Self::select`] call, or `-1` if every + /// non-zero element was selected. + pub fn threshold_buffer(&self) -> &Buffer + { + &self.threshold + } + + /// Maximum number of indices this selector can emit. + pub fn max_selected(&self) -> u32 + { + self.max_selected + } +} + +#[cfg(test)] +mod tests +{ + use super::*; + + /// CPU mirror of the WGSL quantizer. + fn quantize_cpu(count: u32) -> u32 + { + if count == 0 + { + return 0; + } + + let exponent = 31 - count.leading_zeros(); + let extra = if exponent >= LOG_SUB_BINS + { + (count >> (exponent - LOG_SUB_BINS)) & (SUB_BINS - 1) + } + else + { + (count << (LOG_SUB_BINS - exponent)) & (SUB_BINS - 1) + }; + + exponent * SUB_BINS + extra + } + + /// CPU mirror of the three passes. + fn select_cpu(counts: &[u32], k: u32) -> (Vec, i32) + { + let mut histogram = vec![0u32; BIN_COUNT as usize]; + + for &count in counts + { + if count != 0 + { + histogram[quantize_cpu(count) as usize] += 1; + } + } + + let mut sum = 0u32; + let mut threshold = -1i32; + + for bin in (0..BIN_COUNT as usize).rev() + { + let count = histogram[bin]; + + if sum + count >= k + { + threshold = bin as i32; + break; + } + + sum += count; + } + + let selected = counts + .iter() + .enumerate() + .filter(|&(_, &count)| count != 0 && quantize_cpu(count) as i32 > threshold) + .map(|(index, _)| index as u32) + .collect(); + + (selected, threshold) + } + + fn next_random(state: &mut u64) -> u32 + { + *state ^= *state << 13; + *state ^= *state >> 7; + *state ^= *state << 17; + (*state >> 32) as u32 + } + + #[test] + fn quantize_is_monotonic() + { + let mut previous = 0; + + for count in 1..100_000u32 + { + let bin = quantize_cpu(count); + assert!(bin >= previous, "quantize({count}) = {bin} < {previous}"); + assert!(bin < BIN_COUNT); + previous = bin; + } + + let mut state = 0x1234_5678_9abc_def0u64; + let mut values = (0..10_000) + .map(|_| next_random(&mut state)) + .collect::>(); + values.sort_unstable(); + + let mut previous = 0; + for count in values + { + let bin = quantize_cpu(count); + assert!(bin >= previous); + assert!(bin < BIN_COUNT); + previous = bin; + } + } + + #[test] + fn quantize_handles_zero_and_max() + { + assert_eq!(quantize_cpu(0), 0); + assert!(quantize_cpu(u32::MAX) < BIN_COUNT); + } + + #[test] + fn selection_never_exceeds_k() + { + let mut state = 0x0ddc_0ffe_e15e_beefu64; + + for _ in 0..100 + { + let len = 1 + (next_random(&mut state) % 1000) as usize; + let counts = (0..len) + .map(|_| next_random(&mut state) % 64) + .collect::>(); + + for k in 0..=20 + { + let (selected, threshold) = select_cpu(&counts, k); + + assert!(selected.len() <= k as usize); + + let mut sorted = selected.clone(); + sorted.sort_unstable(); + sorted.dedup(); + assert_eq!(sorted.len(), selected.len(), "duplicate indices"); + + for &index in &selected + { + let count = counts[index as usize]; + assert!(count != 0); + assert!(quantize_cpu(count) as i32 > threshold); + } + } + } + } + + #[test] + fn selection_excludes_the_threshold_bin() + { + let counts = [1, 5, 3, 5, 2]; + let (selected, _) = select_cpu(&counts, 3); + + // The two 5s are above the threshold bin; the 3 is in the threshold + // bin and is therefore excluded. + assert_eq!(selected.len(), 2); + assert!(selected.iter().all(|&index| counts[index as usize] == 5)); + } + + #[test] + fn selection_with_fewer_candidates_than_k() + { + let counts = [1, 0, 2, 0, 3]; + let (selected, threshold) = select_cpu(&counts, 10); + + assert_eq!(threshold, -1); + assert_eq!(selected.len(), 3); + } + + #[test] + fn selection_with_k_zero() + { + let counts = [1, 2, 3]; + let (selected, _) = select_cpu(&counts, 0); + + assert!(selected.is_empty()); + } + + #[test] + fn selection_with_all_equal_counts_selects_nothing() + { + let counts = [7, 7, 7, 7]; + let (selected, _) = select_cpu(&counts, 2); + + assert!(selected.is_empty()); + } + + #[test] + fn selection_with_all_zero_counts() + { + let counts = [0, 0, 0, 0]; + let (selected, threshold) = select_cpu(&counts, 2); + + assert_eq!(threshold, -1); + assert!(selected.is_empty()); + } + + #[test] + #[ignore = "requires a GPU adapter with the IMMEDIATES feature"] + fn gpu_selection_smoke_test() + { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let adapter = + pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) + .expect("no GPU adapter available"); + let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { + required_features: wgpu::Features::IMMEDIATES, + required_limits: wgpu::Limits { + max_immediate_size: 112, + ..Default::default() + }, + ..Default::default() + })) + .expect("failed to create GPU device"); + + let counts: [u32; 5] = [1, 5, 3, 5, 2]; + let requests = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("TopKSelector::test_requests"), + contents: bytemuck::cast_slice(&counts), + usage: BufferUsages::STORAGE, + }); + + let selector = TopKSelector::new(&device, 8); + + // Run the selection twice to verify that the histogram is cleared and + // `selected_count` is reset between calls. + for _ in 0..2 + { + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("TopKSelector::test_encoder"), + }); + selector.select(&device, &mut encoder, &requests, counts.len() as u32, 3); + queue.submit([encoder.finish()]); + + let (count, indices) = read_selection(&device, &queue, &selector); + + // The two 5s are above the threshold bin, which contains the 3. + assert_eq!(count, 2); + assert_eq!(indices, vec![1, 3]); + } + } + + /// Reads back the selected count and the sorted selected indices. + fn read_selection( + device: &wgpu::Device, + queue: &wgpu::Queue, + selector: &TopKSelector, + ) -> (u32, Vec) + { + let count = std::sync::Arc::new(std::sync::Mutex::new(None)); + let count_clone = count.clone(); + wgpu::util::DownloadBuffer::read_buffer( + device, + queue, + &selector.selected_count_buffer().slice(..), + move |buffer| { + let bytes = buffer.unwrap(); + *count_clone.lock().unwrap() = Some(bytemuck::pod_read_unaligned::(&bytes)); + }, + ); + + let indices = std::sync::Arc::new(std::sync::Mutex::new(None)); + let indices_clone = indices.clone(); + wgpu::util::DownloadBuffer::read_buffer( + device, + queue, + &selector.selected_indices_buffer().slice(..), + move |buffer| { + let bytes = buffer.unwrap(); + *indices_clone.lock().unwrap() = + Some(bytemuck::pod_collect_to_vec::(&bytes)); + }, + ); + + device + .poll(wgpu::wgt::PollType::wait_indefinitely()) + .unwrap(); + + let count = *count.lock().unwrap().as_ref().unwrap(); + let mut indices = indices.lock().unwrap().as_ref().unwrap()[0..count as usize].to_vec(); + indices.sort_unstable(); + + (count, indices) + } +} diff --git a/src/main.rs b/src/main.rs index 93bfb0b..0078c24 100644 --- a/src/main.rs +++ b/src/main.rs @@ -361,8 +361,9 @@ impl State init: voxel_cache::CacheAttributeInit::External, }); - let voxel_cache = VoxelCache::<4>::new(&device, 150_000, &layout); let request_buffer = CacheRequestBuffer::new(&device, 1024); + let voxel_cache = + VoxelCache::<4>::new(&device, 150_000, request_buffer.max_requests, &layout); let insertion_data = CacheInsertionData::new(&device, 1024, &layout); //let terrain_generator = TerrainGenerator::<4>::new(5, "vxls_height.tif", 0.2, "img.jpg"); @@ -395,13 +396,18 @@ impl State let mut chunk_pos_map = HashMap::new(); let total_chunk_count = terrain_height * terrain_width * terrain_alt; - //let structure_table = FixedStructureTable::new(&device, total_chunk_count); + let structure_table_request_buffer = CacheRequestBuffer::new(&device, 128); + //let structure_table = FixedStructureTable::new( + // &device, + // total_chunk_count, + // structure_table_request_buffer.max_requests, + //); let structure_table = ToroidalStructureTable::new( &device, (terrain_width, terrain_alt, terrain_height), Vec3::ZERO, + structure_table_request_buffer.max_requests, ); - let structure_table_request_buffer = CacheRequestBuffer::new(&device, 128); let structure_table_insertion_data = CacheInsertionData::new(&device, 128, &layout); let chunk_instances = (0..terrain_alt) .cartesian_product(0..terrain_height) diff --git a/src/production.rs b/src/production.rs new file mode 100644 index 0000000..9e08eea --- /dev/null +++ b/src/production.rs @@ -0,0 +1,60 @@ +use bytemuck::Pod; +use bytemuck::Zeroable; + +use crate::voxel_cache::schema::InsertionInformation; + +/// A structure locator format to locate node within an ntree +pub mod tree_locator; + +/// Facilities for voxel production on the host (CPU) side +pub mod host_production; + +/// This module contains definition and common logic to produce voxel data to feed a [`VoxelCache`] + +/// A cache might hold data owned by multiple different producers. To discriminate where to route the +/// request, a node is always tagged by a [`ProducerId`]. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Zeroable, Pod)] +#[repr(transparent)] +pub struct ProducerId(pub u32); + +/// A producer can manage differnet independent voxel structure, with their own roots. +/// As such a producer can tag, to its discretion, its own structure with an Id. +/// +/// All node of a same tree thus share the same structure Id +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Zeroable, Pod)] +#[repr(transparent)] +pub struct StructureId(pub u32); + +/// A request can come from anywhere inside the structure. The producer can thus tag each node with +/// a locator, to know where the request was issued. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Zeroable, Pod)] +#[repr(transparent)] +pub struct StructureLocator(pub u32); + +/// For structs which can be used as a voxel attribute source +pub trait VoxelAttributes: 'static + Clone + Send + Sync +{ + /// The amount of attributes this struct holds + fn attribute_count() -> usize; + + /// Must returns the words for a single attribute. + fn attribute(&self, attribute_index: usize) -> &[u32]; +} + +/// Represents something that can produce a voxel node. +pub trait VoxelProducer +where + [(); N * N * N]:, +{ + /// The voxel data produced by this producer + type Output: VoxelAttributes; + + /// A pure function that can produce a voxel node based on the owner produer id, requesting structure, and the + /// requesting location within the structure + fn produce( + &self, + producer_id: ProducerId, + id: StructureId, + locator: StructureLocator, + ) -> (InsertionInformation, [Self::Output; N * N * N]); +} diff --git a/src/production/host_production.rs b/src/production/host_production.rs new file mode 100644 index 0000000..9c9345e --- /dev/null +++ b/src/production/host_production.rs @@ -0,0 +1,69 @@ +use rayon::ThreadPool; +use rayon::iter::IndexedParallelIterator; +use rayon::iter::IntoParallelRefIterator; +use rayon::iter::IntoParallelRefMutIterator; +use rayon::iter::ParallelIterator; + +use crate::production::VoxelProducer; +use crate::voxel_cache::insertion::CacheInsertionData; +use crate::voxel_cache::requests::CacheRequestBuffer; +use crate::voxel_cache::schema::InsertionInformation; +use crate::voxel_cache::schema::RequestInformation; + +/// Handles requests made by the cache on the host +pub struct HostRequestHandler> +where + [(); N * N * N]:, +{ + producer: P, + thread_pool: ThreadPool, +} + +impl + Sync> HostRequestHandler +where + [(); N * N * N]:, +{ + pub fn new(producer: P, thread_pool: ThreadPool) -> Self + { + Self { + producer, + thread_pool, + } + } + + pub fn fullfill( + &self, + device: &wgpu::Device, + queue: &wgpu::Queue, + request_buffer: &CacheRequestBuffer, + insertion: &CacheInsertionData, + ) + { + request_buffer.host_download_requests(device, queue, |requests| {}); + } + + pub fn produce_requests( + &self, + requests: &[RequestInformation], + informations: &mut [InsertionInformation], + attributes: &mut [[P::Output; N * N * N]], + ) + { + self.thread_pool.install(|| { + requests + .par_iter() + .zip(informations.par_iter_mut()) + .zip(attributes.par_iter_mut()) + .for_each(|((request, dest_information), dest_attributes)| { + let (info, attributes) = self.producer.produce( + super::ProducerId(0), + super::StructureId(request.structure_id), + super::StructureLocator(request.node_id), + ); + + *dest_information = info; + *dest_attributes = attributes; + }); + }) + } +} diff --git a/src/production/tree_locator.rs b/src/production/tree_locator.rs new file mode 100644 index 0000000..0cec62e --- /dev/null +++ b/src/production/tree_locator.rs @@ -0,0 +1,422 @@ +use itertools::Itertools; + +use crate::production::StructureLocator; + +/// Compact location of a specific node within a Voxel tree data strcutrure : depth + location +/// +/// The location is encoded as one number per coordinate. +/// A coordinate is interpreted as base `N` number. +/// The base `N` digits represent the path take from the root down to the node, therminated by a +/// `1` digit. +/// +/// Thus a encoded location of `1` refers to the root : Only node of depth 0 +/// +/// an encoded location of `1032` for a 4-tree, refers to from the root : going into the 0th +/// child, then 3rd child, then 2nd child. It refers to a node of depth 3. +/// +#[derive(Clone, Copy, Debug)] +pub struct TreeLocator +{ + x: u32, + y: u32, + z: u32, +} + +impl From for TreeLocator +{ + fn from(value: StructureLocator) -> Self + { + let mut value = value.0; + let mut locator = Self::root(); + let n = N as u32; + + while value != 1 + { + let z = value % n; + value /= n; + let y = value % n; + value /= n; + let x = value % n; + value /= n; + + locator = locator.child(x, y, z) + } + locator + } +} + +impl From> for StructureLocator +{ + fn from(mut value: TreeLocator) -> StructureLocator + { + let mut locator = 1u32; + while !value.is_root() + { + let (x, y, z) = value.local_coords(); + value = value.parent().unwrap(); + + locator *= N as u32; + locator += x; + + locator *= N as u32; + locator += y; + + locator *= N as u32; + locator += z; + } + + StructureLocator(locator) + } +} + +impl TreeLocator +{ + pub const ROOT: TreeLocator = TreeLocator { x: 1, y: 1, z: 1 }; + + pub fn root() -> Self + { + Self::ROOT + } + + /// Returns the locator of node at `depth`, with coordinates, in that depth coordinate space, + /// `node_x` `node_y` `node_z`. + /// + /// The `node_*` must be in the `0..N^depth` range. + pub fn from_node_coords(depth: u32, node_x: u32, node_y: u32, node_z: u32) -> Self + { + // Check coordinate bounds + assert!( + node_x < N.pow(depth) as u32, + "Node coordinates out of bounds." + ); + assert!( + node_y < N.pow(depth) as u32, + "Node coordinates out of bounds." + ); + assert!( + node_z < N.pow(depth) as u32, + "Node coordinates out of bounds." + ); + + if depth == 0 + { + return Self::ROOT; + } + + // Puts a one in base-N on the Nth digit + let one = N.pow(depth) as u32; + Self { + x: one + node_x, + y: one + node_y, + z: one + node_z, + } + } + + /// Computes the maximum depth supported for this tree arity + pub fn max_depth() -> u32 + { + (u32::MAX as usize).ilog(N) - 1 + } + + pub fn is_root(&self) -> bool + { + self.x == 1 && self.y == 1 && self.z == 1 + } + + /// Returns the depth of the node located by `self`, 0 being the root + pub fn depth(&self) -> u32 + { + // A number k takes floor(log_n(k)) + 1 digits in base n + + // This is digits - 1 as the locator contains a 1 on the front + self.x.ilog(N as u32) + } + + /// Returns the size in voxels of this node considering that a node at `max_depth` represents 1 + /// voxel + pub fn node_size(&self, max_depth: u32) -> u32 + { + let depth = self.depth(); + + // 0 if voxel, max_depth if root + let height = max_depth - depth; + + N.pow(height) as u32 + } + + /// Returns the locator of this node's parent, `None` if `self` is the root + pub fn parent(&self) -> Option + { + if self.is_root() + { + None + } + else + { + Some(Self { + x: self.x / N as u32, + y: self.y / N as u32, + z: self.z / N as u32, + }) + } + } + + /// Returns the [`TreeLocator`] of the children of this node with coordinates `child_x`, + /// `child_y`, `child_z` within this node. + /// + /// The `child_*` coordinates must be in the `0..N` range. + pub fn child(&self, child_x: u32, child_y: u32, child_z: u32) -> Self + { + // Check children bounds + assert!(child_x < N as u32, "Out of bounds child coordinate."); + assert!(child_y < N as u32, "Out of bounds child coordinate."); + assert!(child_z < N as u32, "Out of bounds child coordinate."); + + // Check depth bounds + assert!( + self.x.checked_mul(N as u32).is_some(), + "TreeLocator too deep" + ); + assert!( + self.y.checked_mul(N as u32).is_some(), + "TreeLocator too deep" + ); + assert!( + self.z.checked_mul(N as u32).is_some(), + "TreeLocator too deep" + ); + + let n = N as u32; + Self { + x: self.x * n + child_x, + y: self.y * n + child_y, + z: self.z * n + child_z, + } + } + + /// Returns an iterator on the children of this node + pub fn children(&self) -> impl Iterator + { + (0..N as u32) + .cartesian_product(0..N as u32) + .cartesian_product(0..N as u32) + .map(|((x, y), z)| self.child(x, y, z)) + } + + /// Returns the coordinate of this node inside its parent. + /// The returned coordinate are in `0..N` + pub fn local_coords(&self) -> (u32, u32, u32) + { + if self.is_root() + { + return (0, 0, 0); + } + + let x = self.x % N as u32; + let y = self.y % N as u32; + let z = self.z % N as u32; + + (x, y, z) + } +} + +#[cfg(test)] +mod tests +{ + use super::*; + + fn raw(l: TreeLocator) -> (u32, u32, u32) + { + (l.x, l.y, l.z) + } + + #[test] + fn root_is_depth_zero() + { + let r = TreeLocator::<4>::root(); + assert!(r.is_root()); + assert_eq!(r.depth(), 0); + assert_eq!(raw(r), (1, 1, 1)); + assert!(r.parent().is_none()); + assert_eq!(r.local_coords(), (0, 0, 0)); + } + + #[test] + fn child_encoding_matches_doc_example() + { + // Doc: `1032` in base 4 => child 0, then 3, then 2 => depth 3. + let l = TreeLocator::<4>::root() + .child(0, 0, 0) + .child(3, 3, 3) + .child(2, 2, 2); + + // 0b1032 in base 4 = 1*64 + 0*16 + 3*4 + 2 = 78 + assert_eq!(raw(l), (78, 78, 78)); + assert_eq!(l.depth(), 3); + assert!(!l.is_root()); + } + + #[test] + fn child_uses_independent_coordinates() + { + let c = TreeLocator::<4>::root().child(1, 2, 3); + assert_eq!(raw(c), (4 + 1, 4 + 2, 4 + 3)); + assert_eq!(c.depth(), 1); + assert_eq!(c.local_coords(), (1, 2, 3)); + } + + #[test] + fn parent_undoes_child() + { + let root = TreeLocator::<4>::root(); + let c = root.child(3, 0, 2); + let gc = c.child(1, 1, 0); + + assert_eq!(raw(gc.parent().unwrap()), raw(c)); + assert_eq!(raw(c.parent().unwrap()), raw(root)); + } + + #[test] + fn from_node_coords_depth_zero_is_root() + { + let l = TreeLocator::<4>::from_node_coords(0, 0, 0, 0); + assert!(l.is_root()); + } + + #[test] + fn from_node_coords_matches_child_walk() + { + // Node (5, 2, 7) at depth 2 in a 4-tree (coords in 0..16). + // Base 4: x = 11, y = 02, z = 13. + let direct = TreeLocator::<4>::from_node_coords(2, 5, 2, 7); + let walked = TreeLocator::<4>::root().child(1, 0, 1).child(1, 2, 3); + + assert_eq!(raw(direct), raw(walked)); + assert_eq!(direct.depth(), 2); + } + + #[test] + fn from_node_coords_parent_is_coarser_node() + { + let l = TreeLocator::<4>::from_node_coords(3, 37, 12, 63); + let p = TreeLocator::<4>::from_node_coords(2, 37 / 4, 12 / 4, 63 / 4); + assert_eq!(raw(l.parent().unwrap()), raw(p)); + } + + #[test] + fn roundtrip_via_local_coords() + { + let original = TreeLocator::<3>::from_node_coords(4, 50, 7, 80); + + // Walk up to the root, collecting local coords at each level. + let mut path = Vec::new(); + let mut cur = original; + while let Some(parent) = cur.parent() + { + path.push(cur.local_coords()); + cur = parent; + } + assert!(cur.is_root()); + assert_eq!(path.len() as u32, original.depth()); + + // Walk back down and rebuild. + let mut rebuilt = TreeLocator::<3>::root(); + for (x, y, z) in path.into_iter().rev() + { + rebuilt = rebuilt.child(x, y, z); + } + assert_eq!(raw(rebuilt), raw(original)); + } + + #[test] + fn children_are_complete_distinct_and_valid() + { + let parent = TreeLocator::<3>::root().child(2, 1, 0); + let kids: Vec<_> = parent.children().collect(); + + assert_eq!(kids.len(), 27); + + let mut seen = std::collections::HashSet::new(); + let mut locals = std::collections::HashSet::new(); + for k in &kids + { + assert_eq!(k.depth(), parent.depth() + 1); + assert_eq!(raw(k.parent().unwrap()), raw(parent)); + assert!(seen.insert(raw(*k)), "duplicate child"); + locals.insert(k.local_coords()); + } + // Every (x, y, z) in 0..3 appears exactly once as a local coordinate. + assert_eq!(locals.len(), 27); + } + + #[test] + fn node_size_scales_with_depth() + { + let max_depth = 3; + let root = TreeLocator::<4>::root(); + assert_eq!(root.node_size(max_depth), 64); // 4^3 + assert_eq!(root.child(0, 0, 0).node_size(max_depth), 16); // 4^2 + assert_eq!(root.child(0, 0, 0).child(1, 1, 1).node_size(max_depth), 4); + assert_eq!( + root.child(0, 0, 0) + .child(1, 1, 1) + .child(2, 2, 2) + .node_size(max_depth), + 1 + ); + } + + #[test] + fn max_depth_is_reachable_without_overflow() + { + // `max_depth` may be conservative, but it must always be safe to reach. + fn check() + { + let max = TreeLocator::::max_depth(); + let last = N as u32 - 1; + + let mut l = TreeLocator::::root(); + for _ in 0..max + { + l = l.child(last, last, last); + } + assert_eq!(l.depth(), max); + + // Largest coordinates at that depth must also be constructible. + let top = (N as u32).pow(max) - 1; + let direct = TreeLocator::::from_node_coords(max, top, top, top); + assert_eq!(raw(direct), raw(l)); + } + + check::<2>(); + check::<3>(); + check::<4>(); + check::<8>(); + } + + #[test] + #[should_panic(expected = "Out of bounds child coordinate.")] + fn child_rejects_out_of_range_coordinate() + { + TreeLocator::<4>::root().child(0, 4, 0); + } + + #[test] + #[should_panic(expected = "Node coordinates out of bounds.")] + fn from_node_coords_rejects_out_of_range_coordinate() + { + // Depth 2 in a 4-tree allows 0..16. + TreeLocator::<4>::from_node_coords(2, 0, 16, 0); + } + + #[test] + #[should_panic(expected = "TreeLocator too deep")] + fn child_rejects_overflowing_depth() + { + let mut l = TreeLocator::<2>::root(); + for _ in 0..40 + { + l = l.child(1, 1, 1); + } + } +} diff --git a/src/terrain.rs b/src/terrain.rs index 680051c..528536a 100644 --- a/src/terrain.rs +++ b/src/terrain.rs @@ -42,8 +42,12 @@ struct ToroidalInvalidationImmediates impl ToroidalStructureTable { - pub fn new(device: &wgpu::Device, extent: (usize, usize, usize), initial_position: Vec3) - -> Self + pub fn new( + device: &wgpu::Device, + extent: (usize, usize, usize), + initial_position: Vec3, + max_requests: usize, + ) -> Self { let size = extent.0 * extent.1 * extent.2; assert!(size <= (u32::MAX as usize)); @@ -77,7 +81,7 @@ impl ToroidalStructureTable ToroidalStructureTable { extent, - fixed_structure_table: FixedStructureTable::new(device, size), + fixed_structure_table: FixedStructureTable::new(device, size, max_requests), position: initial_position, current_offset, invalidation_pass, diff --git a/src/voxel_cache.rs b/src/voxel_cache.rs index 5f2cd46..4bb6b43 100644 --- a/src/voxel_cache.rs +++ b/src/voxel_cache.rs @@ -130,7 +130,12 @@ impl VoxelCache where [(); N * N * N]:, { - pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self + pub fn new( + device: &Device, + page_count: usize, + max_requests: usize, + layout: &CacheLayout, + ) -> Self { let mut cache_memory_profile = MemoryProfile::new("VoxelCache"); let mut mem_device = cache_memory_profile.begin(device); @@ -141,8 +146,11 @@ where layout, page_count, ); - let request_handler = - CacheRequestHandler::new(&mut mem_device.group("CacheRequestHandler"), page_count); + let request_handler = CacheRequestHandler::new( + &mut mem_device.group("CacheRequestHandler"), + page_count, + max_requests as u32, + ); let evictor = CacheEvictor::new(&mut mem_device.group("CacheEvictor"), page_count, 0u32); let common_ressources = CacheRessources::new(&mut mem_device.group("CacheRessources"), page_count); @@ -193,8 +201,12 @@ where { gpu_profiler::begin_scope!(encoder, "gather_requests"); - self.request_handler - .sort_requests(device, &self.common_ressources, &mut encoder); + self.request_handler.sort_requests( + device, + &self.common_ressources, + &mut encoder, + request_buffer.max_requests as u32, + ); self.write_requests_pass.encode( &mut encoder, diff --git a/src/voxel_cache/requests.rs b/src/voxel_cache/requests.rs index 00af908..522ddde 100644 --- a/src/voxel_cache/requests.rs +++ b/src/voxel_cache/requests.rs @@ -9,9 +9,10 @@ use wgpu::Device; use wgpu::include_wgsl; use wgpu::util::DeviceExt; -use crate::gpu::buffer_compactor::NonZeroBufferCompactor; use crate::gpu::create_multi_buffers_bind_group; +use crate::gpu::indirect_buffer::IndirectBuffer1D; use crate::gpu::radix_sort::{self}; +use crate::gpu::top_k::TopKSelector; use crate::gpu_profiler::ScopeEncoder; use crate::gpu_profiler::memory_profiler; use crate::gpu_profiler::{self}; @@ -34,7 +35,16 @@ pub struct CacheRequestHandler /// Number of requests request_count: wgpu::Buffer, - compactor: NonZeroBufferCompactor, + /// Number of request counts in `request_counts_pages` + element_count: u32, + + /// Selects the most requested pages + top_k: TopKSelector, + + /// Gathers the selected counts and indices into contiguous sort buffers + gather_pass: ComputePipeline, + gather_pass_bind_group_layout: BindGroupLayout, + gather_indirect_buffer: IndirectBuffer1D, // Pass to reset the requests reset_pass_bind_group: BindGroup, @@ -66,18 +76,25 @@ pub struct CacheRequestBuffer impl CacheRequestHandler { - pub fn new(device: &mut memory_profiler::Device, page_count: usize) -> Self + pub fn new(device: &mut memory_profiler::Device, page_count: usize, max_selected: u32) -> Self { + let element_count = page_count * N * N * N; + assert!( + element_count <= u32::MAX as usize, + "CacheRequestHandler: too many request pages ({element_count})" + ); + let element_count = element_count as u32; + 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]), + contents: bytemuck::cast_slice(&vec![0u32; element_count as usize]), }); 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]), + contents: bytemuck::cast_slice(&vec![0u32; element_count as usize]), }); let request_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { @@ -88,6 +105,25 @@ impl CacheRequestHandler contents: bytemuck::bytes_of(&0u32), }); + let top_k = TopKSelector::new(device, max_selected); + + let gather_pass_bind_group_layout = Self::create_gather_bind_group_layout(device); + let gather_pass_pipeline_layout = + device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("CacheRequestHandler::gather_pass_pipeline_layout"), + bind_group_layouts: &[Some(&gather_pass_bind_group_layout)], + immediate_size: 0, + }); + + let gather_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("CacheRequestHandler::gather_pass"), + layout: Some(&gather_pass_pipeline_layout), + module: &device.create_shader_module(include_wgsl!("./shaders/gather_requests.wgsl")), + entry_point: Some("gather_requests"), + compilation_options: wgpu::PipelineCompilationOptions::default(), + cache: None, + }); + let (reset_pass_bg_layout, reset_pass_bind_group) = create_multi_buffers_bg_bg_layout( device, &[&request_counts_pages], @@ -122,17 +158,46 @@ impl CacheRequestHandler request_counts_pages, sorted_requests, request_count, - compactor: NonZeroBufferCompactor::new(device, page_count * N * N * N), + element_count, + top_k, + gather_pass, + gather_pass_bind_group_layout, + gather_indirect_buffer: IndirectBuffer1D::new(device), reset_pass_bind_group, reset_pass, - reset_pass_dispatch: ((page_count * N * N * N) as u32).div_ceil(256), + reset_pass_dispatch: element_count.div_ceil(256), bind_group_layout, bind_group, } } + fn create_gather_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout + { + let entry = |binding: u32, read_only: bool| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }; + + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("CacheRequestHandler::gather_pass_bind_group_layout"), + entries: &[ + entry(0, true), // requests + entry(1, true), // selected_indices + entry(2, true), // selected_count + entry(3, false), // keys + entry(4, false), // values + ], + }) + } + /// 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 @@ -143,46 +208,91 @@ impl CacheRequestHandler device: &wgpu::Device, ressources: &CacheRessources, encoder: &mut ScopeEncoder, + k: u32, ) { gpu_profiler::begin_scope!(encoder, "RequestHandler::sort_requests"); - // First perform a fast compaction sort + // Select the most requested pages. { - gpu_profiler::begin_scope!(encoder, "compaction"); - self.compactor.compact_buffer( + gpu_profiler::begin_scope!(encoder, "top_k"); + self.top_k.select( device, &mut encoder, &self.request_counts_pages, - &self.sorted_requests, - Some(&ressources.scratch_buffer), + self.element_count, + k, ); } - self.compactor - .copy_count_to_buffer(&mut encoder, &self.request_count); + // Gather the selected counts and indices into contiguous sort buffers. + { + gpu_profiler::begin_scope!(encoder, "gather"); - // State: - // At this point the `sorted_requests` buffer contains the compacted indices of the request counts - // and the scratch buffer contains the associated values + let gather_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("CacheRequestHandler::gather_bind_group"), + layout: &self.gather_pass_bind_group_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: self.request_counts_pages.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: self.top_k.selected_indices_buffer().as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: self.top_k.selected_count_buffer().as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: ressources.scratch_buffer.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: self.sorted_requests.as_entire_binding(), + }, + ], + }); - // The indices can now be sorted using `sorted_requests` as values and - // `ressources.scratch_buffer` as keys for a sort operation + let gather_dispatch = self.gather_indirect_buffer.workgroup_count( + device, + &mut encoder, + self.top_k.selected_count_buffer(), + 256, + ); - // We use the amount of non zero request as the indirect count so that we can sort only the - // compacted, non-null requests + let mut compute_pass = encoder.begin_profiled_compute_pass("gather"); + compute_pass.set_pipeline(&self.gather_pass); + compute_pass.set_bind_group(0, &gather_bind_group, &[]); + compute_pass.dispatch_workgroups_indirect(gather_dispatch, 0); + } + + // Sort the selected requests by descending request count. The scratch + // buffer holds the keys (counts) and `sorted_requests` the values + // (indices). `selected_count` is the indirect element count. { gpu_profiler::begin_scope!(encoder, "radix"); ressources.radix_sorter.sort( device, &ressources.scratch_buffer, &self.sorted_requests, - Some(&self.request_count), + Some(self.top_k.selected_count_buffer()), None, &mut encoder, radix_sort::RadixSortDirection::Descending, ); } + + // Publish the amount of selected requests for downstream passes. + encoder.copy_buffer_to_buffer( + self.top_k.selected_count_buffer(), + 0, + &self.request_count, + 0, + size_of::() as u64, + ); } pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout diff --git a/src/voxel_cache/shaders/gather_requests.wgsl b/src/voxel_cache/shaders/gather_requests.wgsl new file mode 100644 index 0000000..13cc841 --- /dev/null +++ b/src/voxel_cache/shaders/gather_requests.wgsl @@ -0,0 +1,25 @@ +// Gathers the selected (count, index) pairs into contiguous buffers so they can +// be sorted by the radix sorter. +// +// `keys` receives the request counts and `values` receives the request indices. + +@group(0) @binding(0) var requests: array; +@group(0) @binding(1) var selected_indices: array; +@group(0) @binding(2) var selected_count: u32; +@group(0) @binding(3) var keys: array; +@group(0) @binding(4) var values: array; + +@compute +@workgroup_size(256, 1, 1) +fn gather_requests(@builtin(global_invocation_id) gid: vec3) +{ + let i = gid.x; + if (i >= selected_count) + { + return; + } + + let index = selected_indices[i]; + keys[i] = requests[index]; + values[i] = index; +} diff --git a/src/voxel_cache/shaders/invalidation.wgsl b/src/voxel_cache/shaders/invalidation.wgsl index bb6353a..c595d97 100644 --- a/src/voxel_cache/shaders/invalidation.wgsl +++ b/src/voxel_cache/shaders/invalidation.wgsl @@ -19,9 +19,10 @@ fn invalidation(@builtin(global_invocation_id) gid: vec3) for(var i = u32(0); i < CHILDREN_COUNT; i++) { - if(pointer_invalid(structure_pointer_pages[index].pointers[i])) + let pointer = structure_pointer_pages[index].pointers[i]; + if(child_pointer_available(pointer) && cache_evictor_timestamps[child_pointer_pointer(pointer)] == new_timestamp) { - pointer_invalidate(index, i); + structure_pointer_pages[index].pointers[i] = child_pointer_empty(true); } } } diff --git a/src/voxel_cache/tables.rs b/src/voxel_cache/tables.rs index 7e58fb0..b9b0145 100644 --- a/src/voxel_cache/tables.rs +++ b/src/voxel_cache/tables.rs @@ -60,7 +60,7 @@ pub struct FixedStructureTable impl FixedStructureTable { - pub fn new(device: &wgpu::Device, size: usize) -> Self + pub fn new(device: &wgpu::Device, size: usize, max_requests: usize) -> Self { let pointer = CachePointer::new(Some(None)); let pointers = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { @@ -72,8 +72,11 @@ impl FixedStructureTable let mut memory_profile = MemoryProfile::new("FixedStructureTable"); let mut mem_device = memory_profile.begin(device); - let request_handler = - CacheRequestHandler::<1>::new(&mut mem_device.group("CacheRequestHandler"), size); + let request_handler = CacheRequestHandler::<1>::new( + &mut mem_device.group("CacheRequestHandler"), + size, + max_requests as u32, + ); let common_ressources = CacheRessources::new(&mut mem_device.group("CacheRessources"), size); drop(mem_device); @@ -195,8 +198,12 @@ impl FixedStructureTable request_buffer: &CacheRequestBuffer, ) { - self.request_handler - .sort_requests(device, &self.common_ressources, encoder); + self.request_handler.sort_requests( + device, + &self.common_ressources, + encoder, + request_buffer.max_requests as u32, + ); let workgroup_count_buffer = self.indirect_buffer.workgroup_count( device,