From 3124978e3f5aaca096bf70471b8baa972a8da66c Mon Sep 17 00:00:00 2001 From: Albin Chaboissier Date: Mon, 28 Sep 2026 23:01:31 +0200 Subject: [PATCH] shitty radix --- shaders/Makefile | 2 +- shaders/compaction.spv | Bin 4528 -> 4552 bytes shaders/gi.spv | Bin 1968 -> 1896 bytes shaders/radix_reduce.slang | 158 +++++++ shaders/radix_reduce.spv | Bin 0 -> 4848 bytes shaders/radix_sort.slang | 275 +++++++++++ shaders/radix_sort.spv | Bin 0 -> 8908 bytes shaders/voxel.spv | Bin 15124 -> 14480 bytes src/gpu.rs | 2 + src/gpu/radix_sort.rs | 729 +++++++++++++++++++++++++++++ src/main.rs | 148 +++++- src/producers.rs | 4 +- src/voxel_cache.rs | 56 ++- src/voxel_cache/indirect_buffer.rs | 4 +- src/voxel_cache/request_buffer.rs | 339 +++----------- 15 files changed, 1403 insertions(+), 314 deletions(-) create mode 100644 shaders/radix_reduce.slang create mode 100644 shaders/radix_reduce.spv create mode 100644 shaders/radix_sort.slang create mode 100644 shaders/radix_sort.spv create mode 100644 src/gpu.rs create mode 100644 src/gpu/radix_sort.rs diff --git a/shaders/Makefile b/shaders/Makefile index 4ab55d4..3f33ddd 100644 --- a/shaders/Makefile +++ b/shaders/Makefile @@ -1,4 +1,4 @@ -all: clean voxel.spv compaction.spv gi.spv +all: clean voxel.spv compaction.spv gi.spv radix_sort.spv radix_reduce.spv clean: rm -f *.spv diff --git a/shaders/compaction.spv b/shaders/compaction.spv index e31434a750df38b537a872bcf305bbebbe755534..aed71d52ff6c9fbd06fba3afbe3dc3fa28134036 100644 GIT binary patch delta 1449 zcmZ9MOHY$Q7=`D97AU2(4GO810>K0Y(JG)qxe8Jc5i#+yBPzs8tP9k*P*VxI#mgin z#$P~;2}1k{CT?9Bm;MA7UU21k%8VgQa{8V*?>A@WeZTp-*7~`1Z6c_zFcqf8Y>m0O z!b0Kd!eZ9g@gQ3hGBN27ZqDDkVeDd%wd=v1RF$Ntuvf^Nkg0U@w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tZ?I+xhdd>5sEeYbM>p zhRcGB@3`a2z?@2o8J5PL5Oz*_Qp^$QqJ%Xqe^eTb`bGKf_W(X6l;25F0{4P6KJ~~o zE?txiNS0E6LN@!e`f^9afXyiva{wdPq%^sxJ15k=L2&x{pU~fw_IN+=UCn9PuK$ba zKJkk}IX82o<|S!xW{iJXnls?fC@XJ^o;VMfTi9UKzmkG*sSkfH#g^3-=e?R@;7&Hg zWwyKza^Z6pa&sPha&r!r^O+@!TJ&DT(OOd`_kV@YUH?$FlJs|FnFrMRExRaPmavcB zR4(rKnuLB{>r3wIDJEr}31gNwB=pFPiGz1j0{%rD=DQ#v7M$9P(yU+Nvv*6fB%waq z)mxTL56r{WyDgh~yct*Tj%;vO@2+fO!GDTPJ#teg>w|yOozUZoggEN+9^lgJJ!uxb z!nrR2BOm&e;(0f#5_&~g^!!;dyrGJOefs5HJdkjYyP6O0f&V`+c$}R#vnBzD_cfj4 z!xZPu(A&B+i{99KBmtv0w5#`6cD5ex35ft8R#~4se>9nO$zKs2lM(;` diff --git a/shaders/radix_reduce.slang b/shaders/radix_reduce.slang new file mode 100644 index 0000000..dbc85e6 --- /dev/null +++ b/shaders/radix_reduce.slang @@ -0,0 +1,158 @@ +[[vk::binding(0, 0)]] +RWStructuredBuffer count_buffer; +[[vk::binding(0, 1)]] +RWStructuredBuffer reduced_buffer; + +static const uint32_t THREAD_WIDTH = 256; +static const uint32_t DATA_WIDTH = THREAD_WIDTH * 2; +static const uint32_t DIGIT_COUNT = 8; +static const uint32_t VALUE_COUNT = 1 << DIGIT_COUNT; + +groupshared uint32_t local_data[DATA_WIDTH]; + +[numthreads(256, 1, 1)] +[shader("compute")] +void reduce_pass( + uint32_t3 workgroup_id: SV_GroupID, + uint32_t3 local_thread_id: SV_GroupThreadID, + uint32_t3 global_thread_id: SV_DispatchThreadID) +{ + // Perform sum in current block + let thread_index = global_thread_id.x; + let local_thread_index = local_thread_id.x; + let total = count_buffer.getCount(); + + // Load to groupshared + local_data[local_thread_index * 2] = select((thread_index * 2) < total, count_buffer[thread_index * 2], 0); + local_data[local_thread_index * 2 + 1] = select(((thread_index * 2) + 1) < total, count_buffer[thread_index * 2 + 1], 0); + + GroupMemoryBarrierWithGroupSync(); + + // Belloch sum + var width : uint32_t = 2; + while (width <= DATA_WIDTH) + { + let dest_index = width * (local_thread_index + 1) - 1; + let get_index = dest_index - (width / 2); + // println!("{}, {}", get_index, dest_index); + if (dest_index < DATA_WIDTH) + { + local_data[dest_index] += local_data[get_index]; + } + width *= 2; + GroupMemoryBarrierWithGroupSync(); + } + + // Write to reduced buffer + reduced_buffer[workgroup_id.x] = local_data[DATA_WIDTH - 1]; + // reduced_buffer[workgroup_id.x] = local_data[DATA_WIDTH - 1]; + GroupMemoryBarrierWithGroupSync(); + + local_data[DATA_WIDTH - 1] = 0; + GroupMemoryBarrierWithGroupSync(); + while (width >= 2) + { + let dest_index = width * (local_thread_index + 1) - 1; + let get_index = dest_index - (width / 2); + // println!("{}, {}", get_index, dest_index); + if (dest_index < DATA_WIDTH) + { + let self_data = local_data[dest_index]; + local_data[dest_index] += local_data[get_index]; + local_data[get_index] = self_data; + } + width /= 2; + GroupMemoryBarrierWithGroupSync(); + } + + // Block now contains running local sum + // Dump back to sum buffer + if (2 * thread_index < total) + { + count_buffer[2 * thread_index] = local_data[2 * local_thread_index]; + } + if ((2 * thread_index + 1) < total) + { + count_buffer[2 * thread_index + 1] = local_data[2 * local_thread_index + 1]; + } +} + +[numthreads(256, 1, 1)] +[shader("compute")] +void apply_pass( + uint32_t3 workgroup_id: SV_GroupID, + uint32_t3 local_thread_id: SV_GroupThreadID, + uint32_t3 global_thread_id: SV_DispatchThreadID) +{ + let total = count_buffer.getCount(); + let thread_index = global_thread_id.x; + let local_thread_index = local_thread_id.x; + + // Gather + let reduced_value = reduced_buffer[workgroup_id.x]; + + // Apply sum back + if (thread_index * 2 < total) + { + count_buffer[thread_index * 2] += reduced_value; + } + + if ((thread_index * 2 + 1) < total) + { + count_buffer[thread_index * 2 + 1] += reduced_value; + } +} + +[numthreads(1, 1, 1)] +[shader("compute")] +void direct_pass( + uint32_t3 workgroup_id: SV_GroupID, + uint32_t3 local_thread_id: SV_GroupThreadID, + uint32_t3 global_thread_id: SV_DispatchThreadID) +{ + let size = reduced_buffer.getCount(); + + // Perform exclusive sum + var running_sum : uint32_t = 0; + for (uint32_t i = 0; i < size; i++) + { + let value = reduced_buffer[i]; + reduced_buffer[i] = running_sum; + running_sum += value; + } +} + +struct IndirectArgs +{ + uint32_t x; + uint32_t y; + uint32_t z; +} + +[[vk::binding(0, 0)]] +RWStructuredBuffer total_count; +[[vk::binding(0, 1)]] +RWStructuredBuffer group_counts; + +[numthreads(1, 1, 1)] +[shader("compute")] +void compute_invocation_count( + uint32_t3 workgroup_id: SV_GroupID, + uint32_t3 local_thread_id: SV_GroupThreadID, + uint32_t3 global_thread_id: SV_DispatchThreadID) +{ + var prev_count = total_count[0]; + for (var i = 0; i < group_counts.getCount(); i++) + { + prev_count = div_ceil(prev_count, THREAD_WIDTH); + group_counts[i].x = prev_count; + group_counts[i].y = 1; + group_counts[i].z = 1; + } +} + +uint32_t div_ceil(uint32_t n, uint32_t q) +{ + return (n / q) + select(n % q == 0, 0, 1); +} + diff --git a/shaders/radix_reduce.spv b/shaders/radix_reduce.spv new file mode 100644 index 0000000000000000000000000000000000000000..d9d8040a6c198ee1e680c31ff84ec96d9d371831 GIT binary patch literal 4848 zcmai$33roK5Qab7rmR{J5Rk4W-&9HBHz=MMM<$eP3`F zR78J~f5P<~k3P?rZ)#4&j$Y5uwe~z zKS}lu^i_AKG3{xO>%H$A-R)lMX`G2%bKm7UjH{JO1Ev1_NNorv_piRodBy1=v(H7#`R3L!3Fm6P>#0`kT2NQ%etq+r?D-A$ z6!1U!+Q?Er?|ii9drsqiZTH(V{npm#*N*(wH?FZ3?Z#TCVMo3xWI8X6Z%wA7#nZ?!1Ko+Zren`U%e5k%*!IQR<&AeP zorv5VqMVQMbFepV$-F-9eb@_&VTCM*xQp~RJ!*j zw0qS*W_`UG?0!ElzjE7kXxAU?*QaeB_o?HZtOw_icmo^2a;})qE#Nl9`RI?nZUoy` zKa`mhabAIulr_KfqK=*`_=`LOQ+yEpE5 zFIdhvd!$d!p2WH8xW8{C?$z95_xOISRo(dJ>~Fle`?4H8==+fe5Z~N`8Ahdh^JsIa zPi1dz2iX0-S^L$CcG<5TXl?VjPi@Rjw96Pj%LPQv7~`WCec_@;W5Oez-t8Hw|LhZaNXqP=% zgC0TT%qNa~Rq$%We10!#n=fM3fAWj93W?vZv2d>Gi1}*hp6oNb2i$_VJYyz$FER#+ z@2Y(nhZ>F956&SGa{w&oitn>W!EML_M1S1jAXr~~z8(X6#vCNx%;R8r>$5*kpk4My z-yuZK`-tPrC&AvwGuKvB`=w9YJnmC_ zFR^^|?k%wOJ704}@7@OMbCzoF5PkFx+QtND?e2G;_Q5-PmOA><_!$}x?~0zj1CE;B z1y4Y%Nr{@?1M4&2`)Kp4qn96mjWO4U$VZ62S?G@ubLl&d=(EqCWEhp^{S<9pb>2XT;!Cv4S?JUDEOV=47V`0X{}tFfEJ2QC-zQ%;a3`~~ zPQb}`A^tzkdQPUee#gaN>zsl9CiBId?2G5f+wW=UZxQcjf4qag1yj)9A^PNf2ioor p|0%G3&(p8%{KNk}SpQN)zqWpBvF785=eggRIurY&jv4!A{sukn$kzY> literal 0 HcmV?d00001 diff --git a/shaders/radix_sort.slang b/shaders/radix_sort.slang new file mode 100644 index 0000000..57f17c7 --- /dev/null +++ b/shaders/radix_sort.slang @@ -0,0 +1,275 @@ +const static uint32_t digit_count = 4; +const static uint32_t value_count = 1 << digit_count; + +struct Histogram +{ + uint32_t[value_count] histogram; +} + +struct IndirectArgs +{ + uint32_t x; + uint32_t y; + uint32_t z; +} + +struct PassParams +{ + uint32_t pass_index; + uint32_t descending; + uint32_t digit_stride; +} + +[vk::binding(0, 0)] +RWStructuredBuffer histograms; + +[vk::binding(0, 1)] +RWStructuredBuffer key_buffer; +[vk::binding(1, 1)] +RWStructuredBuffer value_buffer; + +// Double buffering +[vk::binding(0, 2)] +RWStructuredBuffer dest_key_buffer; +[vk::binding(1, 2)] +RWStructuredBuffer dest_value_buffer; + +[vk::binding(0, 3)] +RWStructuredBuffer sort_count; +[vk::binding(1, 3)] +RWStructuredBuffer block_count; + +[vk::push_constant] +uniform PassParams params; + +uint32_t get_digit(uint32_t value, uint32_t digit_id, uint32_t descending) +{ + let mask = ~(0xFFFFFFFF << digit_count); + let digit = (value >> (digit_id * digit_count)) & mask; + return select(descending != 0, digit ^ mask, digit); +} + +static const uint32_t split_size = 16; +static const uint32_t thread_count = 256; +static const uint32_t local_histo_count = thread_count / split_size; + +struct LocalHistogram +{ + Atomic[value_count] histogram; +} + +groupshared LocalHistogram[local_histo_count] local_histograms; + +uint32_t histogram_index(uint32_t digit, uint32_t histo_index) +{ + return digit * params.digit_stride + histo_index; +} + +[shader("compute")] +[numthreads(256, 1, 1)] +void histogram_pass( + uint32_t3 location: SV_DispatchThreadID, + uint32_t3 local_location: SV_GroupThreadID, + uint32_t3 group_location: SV_GroupID, ) +{ + + let element_count = sort_count[0]; + // Reset histogram + let split_index = local_location.x / split_size; + for (uint32_t i = 0; i < value_count; i++) + { + local_histograms[split_index].histogram[i].store(0); + } + if (location.x >= element_count) + { + + return; + } + + GroupMemoryBarrierWithGroupSync(); // Sync histo reset + + var value = key_buffer[location.x]; + value = get_digit(value, params.pass_index, params.descending); + local_histograms[split_index].histogram[value].add(1); + + GroupMemoryBarrierWithGroupSync(); // Sync histo build + + // Aggregate all histograms and send to local memory + // Binary tree sum + /* + var amount = 2; + for (uint32_t d = local_histo_count / 2; d > 0; d >>= 1) + { + if (local_location.x < d) + { + let a = location.x * amount; + let b = a + amount - 1; + + for (var v = 0; v < value_count; v++) + { + local_histograms[a * value_count + v].add(local_histograms[b * value_count + v].load()); + } + } + GroupMemoryBarrierWithGroupSync(); + amount >>= 1; + } + */ + // thread 0 sends to local memory + if (local_location.x == 0) + { + + for (uint32_t v = 0; v < value_count; v++) + { + var sum = 0; + for (uint32_t i = 0; i < local_histo_count; i++) + { + + sum += local_histograms[i].histogram[v].load(); + } + histograms[histogram_index(v, group_location.x)] = sum; + } + } +} + +uint32_t div_ceil(uint32_t n, uint32_t q) +{ + return (n / q) + select(n % q == 0, 0, 1); +} + +groupshared uint32_t[16][16] block_sums; + +void scan_digit(uint32_t lid_digit, uint32_t lid_histo) +{ + let thread_block_size = div_ceil(block_count[0].x, 16); + var running_sum = 0; + for (uint32_t i = lid_histo * thread_block_size; i < min(thread_block_size * (lid_histo + 1), block_count[0].x); i++) + { + let current = histograms[histogram_index(lid_digit, i)]; + histograms[histogram_index(lid_digit, i)] = running_sum; + running_sum += current; + } + + if (lid_histo == 15) + { + histograms[histogram_index(lid_digit, block_count[0].x)] = running_sum; + } + block_sums[lid_digit][lid_histo] = running_sum; +} + +void apply_digit(uint32_t lid_digit, uint32_t lid_histo) +{ + let thread_block_size = div_ceil(block_count[0].x + 1, 16); + var running_sum = 0; + for (uint32_t i = lid_histo * thread_block_size; i < min(thread_block_size * (lid_histo + 1), block_count[0].x + 1); i++) + { + histograms[histogram_index(lid_digit, i)] += block_sums[lid_digit][lid_histo]; + } +} + +[shader("compute")] +[numthreads(16, 16, 1)] +void running_sum_pass( + uint32_t3 location: SV_DispatchThreadID, + uint32_t3 local_location: SV_GroupThreadID, + uint32_t3 group_location: SV_GroupID, ) +{ + scan_digit(local_location.x, local_location.y); + + AllMemoryBarrierWithGroupSync(); + if (local_location.y == 0) + { + var running_sum = 0; + for (uint32_t i = 0; i < 16; i++) + { + let current = block_sums[local_location.x][i]; + block_sums[local_location.x][i] = running_sum; + running_sum += current; + } + } + AllMemoryBarrierWithGroupSync(); + + apply_digit(local_location.x, local_location.y); + + AllMemoryBarrierWithGroupSync(); + + if (local_location.x == 0 && local_location.y == 0) + { + var running_sum = 0; + for (uint32_t i = 0; i < value_count; i++) + { + let current = histograms[histogram_index(i, block_count[0].x)]; + histograms[histogram_index(i, block_count[0].x)] = running_sum; + running_sum += current; + } + } +} + +groupshared uint32_t[256] keys; +groupshared uint32_t[256] values; +groupshared uint32_t[256] digit; + +[shader("compute")] +[numthreads(256, 1, 1)] +void scatter_pass( + uint32_t3 location: SV_DispatchThreadID, + uint32_t3 local_location: SV_GroupThreadID, + uint32_t3 group_location: SV_GroupID, ) +{ + + let element_count = sort_count[0]; + // Load kv + if (location.x >= element_count) + { + return; + } + + // Gather + keys[local_location.x] = key_buffer[location.x]; + values[local_location.x] = value_buffer[location.x]; + + // Compute digit + digit[local_location.x] = get_digit(keys[local_location.x], params.pass_index, params.descending); + + GroupMemoryBarrierWithGroupSync(); + + // Compute local offset + var local_offset = 0; + var local_digit = digit[local_location.x]; + for (uint32_t i = 0; i < local_location.x; i++) + { + + if (digit[i] == local_digit) + { + + local_offset += 1; + } + } + + // Scatter + // Compute global offset + let digit_offset = local_digit * (block_count[0].x + 1); + let global_loc = histograms[histogram_index(local_digit, block_count[0].x)] + histograms[histogram_index(local_digit, group_location.x)] + local_offset; + + dest_key_buffer[global_loc] = keys[local_location.x]; + dest_value_buffer[global_loc] = values[local_location.x]; +} + +[shader("compute")] +[numthreads(1, 1, 1)] +void indirect_count_pass( + uint32_t3 location: SV_DispatchThreadID, + uint32_t3 local_location: SV_GroupThreadID, + uint32_t3 group_location: SV_GroupID, ) +{ + + let indirect = params.pass_index; + if (indirect == 0) + { + sort_count[0] = key_buffer.getCount(); + } + let div_ceil = (sort_count[0] / 256) + select(sort_count[0] % 256 == 0, 0, 1); + block_count[0].x = div_ceil; + block_count[0].y = 1; + block_count[0].z = 1; +} + diff --git a/shaders/radix_sort.spv b/shaders/radix_sort.spv new file mode 100644 index 0000000000000000000000000000000000000000..2705fd5b37cebacd601d27796e61e2f12ec8a55b GIT binary patch literal 8908 zcmZ{p2YjDp5y$^&+Jw%uv}LzVDRfXMt1Zw0q>KhAP+EpNq)8egZHgHPh>D6R?!6V< z0*bh|A}YA|o>g$+9&Ay*-}nFi!pqHJ1C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/src/gpu.rs @@ -0,0 +1,2 @@ +// Main common gpu parallel algorithms +pub mod radix_sort; diff --git a/src/gpu/radix_sort.rs b/src/gpu/radix_sort.rs new file mode 100644 index 0000000..e838343 --- /dev/null +++ b/src/gpu/radix_sort.rs @@ -0,0 +1,729 @@ +use std::num::NonZero; + +use itertools::Itertools; +use wgpu::BindGroup; +use wgpu::BindGroupLayout; +use wgpu::Buffer; +use wgpu::BufferUsages; +use wgpu::CommandEncoder; +use wgpu::ComputePass; +use wgpu::ComputePipeline; +use wgpu::Device; +use wgpu::ShaderStages; +use wgpu::include_spirv; +use wgpu::util::DeviceExt; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum RadixSortDirection +{ + Ascending, + Descending, +} + +#[derive(Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)] +#[repr(C)] +struct PassParameters +{ + pass_index: u32, + descending: u32, + digit_stride: u32, +} + +struct HistogramScanner +{ + // Used to perform the base case : dumb pass + direct_sum_pass: ComputePipeline, + slot_bind_group_layout: BindGroupLayout, + + // Recursive running + reduce_pass: ComputePipeline, + apply_pass: ComputePipeline, + compute_invocation_count: ComputePipeline, + + group_counts_storage: Buffer, + group_counts: Buffer, + group_counts_storage_bind_group: BindGroup, + buffers: Vec<(usize, Buffer, BindGroup)>, +} + +impl HistogramScanner +{ + const THREAD_COUNT: usize = 256; + const BLOCK_COUNT: usize = Self::THREAD_COUNT / 2; + const DIGIT_COUNT: usize = 4; + const VALUE_COUNT: usize = 1 << Self::DIGIT_COUNT; + + pub fn new(device: &Device, histogram_count: usize) -> Self + { + let mut buffers = vec![]; + + let mut pass_histogram_count = histogram_count; + + let indirect_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("HistogramScanner::indirect_count"), + usage: BufferUsages::INDIRECT | BufferUsages::COPY_DST, + contents: bytemuck::bytes_of(&wgpu::util::DispatchIndirectArgs { x: 1, y: 1, z: 1 }), + }); + + let slot_bind_group_layout = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("HistogramScanner::slot_bind_group_layout"), + entries: &[ + // Data buffer + 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, + }, + ], + }); + + println!("Creating histo buffer with {}", histogram_count); + while pass_histogram_count >= Self::BLOCK_COUNT + { + let block_count = pass_histogram_count.div_ceil(Self::BLOCK_COUNT); + println!("Creating block with {}", block_count); + let data_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("HistogramScanner::buffers (sum)"), + size: (block_count * size_of::() * Self::VALUE_COUNT) as u64, + usage: BufferUsages::STORAGE, + mapped_at_creation: false, + }); + let step_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("HistogramScanner::bind_group"), + layout: &slot_bind_group_layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: data_buffer.as_entire_binding(), + }], + }); + buffers.push((pass_histogram_count, data_buffer, step_bind_group)); + + // Each reduced block becomes a histogram for the next pass + pass_histogram_count = block_count; + } + + println!("Using {} histogram reduce passes !", buffers.len()); + + let pipelines_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("HistogramScanner::pipelines_layout"), + bind_group_layouts: &[ + // Count slot + Some(&slot_bind_group_layout), + // Reduced slot + Some(&slot_bind_group_layout), + ], + immediate_size: 0, // for the pass number + }); + + let radix_reduce_shader_module = + device.create_shader_module(include_spirv!("../../shaders/radix_reduce.spv")); + + let compilation_options = wgpu::PipelineCompilationOptions { + zero_initialize_workgroup_memory: false, + ..Default::default() + }; + + let reduce_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("HistogramScanner::reduce_pass"), + layout: Some(&pipelines_layout), + module: &radix_reduce_shader_module, + entry_point: Some("reduce_pass"), + compilation_options: compilation_options.clone(), + cache: None, + }); + + let apply_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("HistogramScanner::apply_pass"), + layout: Some(&pipelines_layout), + module: &radix_reduce_shader_module, + entry_point: Some("apply_pass"), + compilation_options: compilation_options.clone(), + cache: None, + }); + + let direct_sum_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("HistogramScanner::direct_sum_pass"), + layout: Some(&pipelines_layout), + module: &radix_reduce_shader_module, + entry_point: Some("direct_pass"), + compilation_options: compilation_options.clone(), + cache: None, + }); + + let compute_invocation_count = + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("HistogramScanner::compute_invocation_count"), + layout: Some(&pipelines_layout), + module: &radix_reduce_shader_module, + entry_point: Some("compute_invocation_count"), + compilation_options: compilation_options.clone(), + cache: None, + }); + + let group_counts = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("HistogramScanner::group_counts"), + size: (size_of::() * buffers.len().max(1)) as u64, + usage: BufferUsages::INDIRECT | BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + + let group_counts_storage = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("HistogramScanner::group_counts_storage"), + size: (size_of::() * buffers.len().max(1)) as u64, + usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, + mapped_at_creation: false, + }); + + let group_counts_storage_bind_group = + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("HistogramScanner::group_counts_storage_bind_group"), + layout: &slot_bind_group_layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: group_counts_storage.as_entire_binding(), + }], + }); + + Self { + group_counts_storage, + group_counts, + group_counts_storage_bind_group, + reduce_pass, + slot_bind_group_layout, + direct_sum_pass, + apply_pass, + buffers, + compute_invocation_count, + } + } + + pub fn precompute_counts( + &self, + device: &Device, + count_buffer: &Buffer, + encoder: &mut CommandEncoder, + ) + { + // ~~ Compute invocation counts + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("HistogramScanner::compute_group_count"), + timestamp_writes: None, + }); + let count_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("HistogramScanner::bind_group"), + layout: &self.slot_bind_group_layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: count_buffer.as_entire_binding(), + }], + }); + + pass.set_bind_group(0, &count_bind_group, &[]); + pass.set_bind_group(1, &self.group_counts_storage_bind_group, &[]); + pass.set_pipeline(&self.compute_invocation_count); + pass.dispatch_workgroups(1, 1, 1); + drop(pass); + + encoder.copy_buffer_to_buffer( + &self.group_counts_storage, + 0, + &self.group_counts, + 0, + (self.buffers.len() * size_of::()) as u64, + ); + } + + pub fn sum( + &self, + device: &Device, + pass: &mut ComputePass, + data_buffer: &Buffer, + offset: u64, + size: u64, + ) + { + // ~~ Compute invocation counts + let out_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("HistogramScanner::bind_group"), + layout: &self.slot_bind_group_layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + //resource: data_buffer.as_entire_binding(), + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: data_buffer, + offset, + size: Some(NonZero::new(size).unwrap()), + }), + }], + }); + + let out_pass = (0usize, data_buffer.clone(), out_bind_group.clone()); + + let passes = std::iter::once(&out_pass) + .chain(self.buffers.iter()) + .collect::>(); + let pass_count = self.buffers.len(); + + for (i, (count, reduced)) in passes.iter().tuple_windows().enumerate() + { + // Reduce to destination + //pass.set_bind_group(0, &count.2, &[if i == 0 { offset as u32 } else { 0 }]); + pass.set_bind_group(0, &count.2, &[]); + pass.set_bind_group(1, &reduced.2, &[]); + pass.set_pipeline(&self.reduce_pass); + pass.dispatch_workgroups_indirect( + &self.group_counts, + (size_of::() * i) as u64, + ); + } + + if passes.len() == 1 + { + pass.set_bind_group(0, &out_bind_group, &[]); + pass.set_bind_group(1, &out_bind_group, &[]); + } + + // Last bindgroups are still bound + pass.set_pipeline(&self.direct_sum_pass); + pass.dispatch_workgroups(1, 1, 1); + + // Perform apply back up + for (i, (reduced, count)) in passes.iter().rev().tuple_windows().enumerate() + { + // pass.set_bind_group( + // 0, + // &count.2, + // &[ + // if i == pass_count - 1 + // { + // offset as u32 + // } + // else + // { + // 0 + // }, + // ], + // ); + pass.set_bind_group(0, &count.2, &[]); + pass.set_bind_group(1, &reduced.2, &[]); + pass.set_pipeline(&self.apply_pass); + pass.dispatch_workgroups_indirect( + &self.group_counts, + (size_of::() * (pass_count - 1 - i)) as u64, + ); + } + } +} + +pub struct RadixSorter +{ + max_size: usize, + block_count: usize, + histograms: Buffer, + histograms_bind_group: BindGroup, + digit_stride: u32, + + // For indirect dispatch + sort_count_buffer: Buffer, + group_count_buffer: Buffer, + counts_bind_group: BindGroup, + indirect_buffer: Buffer, + + data_bind_group_layout: BindGroupLayout, + + double_buffer_keys: Buffer, + double_buffer_values: Buffer, + double_buffer_bind_group: BindGroup, + + histogram_reduce: HistogramScanner, + histogram_pass: ComputePipeline, + running_sum_pass: ComputePipeline, + scatter_pass: ComputePipeline, + indirect_count_pass: ComputePipeline, +} + +impl RadixSorter +{ + const TOTAL_DIGIT_COUNT: usize = 32; + const THREAD_COUNT: usize = 256; + const DIGIT_COUNT: usize = 4; + const VALUE_COUNT: usize = 1 << Self::DIGIT_COUNT; + const PASS_COUNT: usize = Self::TOTAL_DIGIT_COUNT / Self::DIGIT_COUNT; + + pub fn new(device: &Device, max_size: usize) -> Self + { + let block_count = max_size.div_ceil(Self::THREAD_COUNT); + let histogram_count = block_count + 1; + let digit_stride = (histogram_count * size_of::()).next_multiple_of(256); + //let digit_stride = histogram_count * size_of::(); + + let histograms = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("histograms_buffer"), + size: (digit_stride * Self::VALUE_COUNT) as u64, + usage: BufferUsages::STORAGE, + mapped_at_creation: false, + }); + + let sort_count_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("sort_count_buffer"), + contents: bytemuck::bytes_of(&0), + usage: BufferUsages::STORAGE, + }); + + let group_count_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("group_count_buffer"), + contents: bytemuck::bytes_of(&wgpu::util::DispatchIndirectArgs { x: 1, y: 1, z: 1 }), + usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, + }); + + let indirect_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("indirect_buffer"), + contents: bytemuck::bytes_of(&wgpu::util::DispatchIndirectArgs { x: 0, y: 1, z: 1 }), + usage: BufferUsages::INDIRECT | BufferUsages::COPY_DST, + }); + + let histograms_bind_group_layout = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("RadixSorter::histograms_bind_group_layout"), + entries: &[ + // Histrograms + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: false }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ], + }); + + let histograms_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("RadixSorter::histograms_bind_group"), + layout: &histograms_bind_group_layout, + entries: &[ + // Histrograms + wgpu::BindGroupEntry { + binding: 0, + resource: histograms.as_entire_binding(), + }, + ], + }); + + let double_buffer_keys = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("RadixSorter::double_buffer_keys"), + size: (size_of::() * max_size) as u64, + usage: BufferUsages::STORAGE, + mapped_at_creation: false, + }); + + let double_buffer_values = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("RadixSorter::double_buffer_values"), + size: (size_of::() * max_size) as u64, + usage: BufferUsages::STORAGE, + mapped_at_creation: false, + }); + + let data_bind_group_layout = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("RadixSorter::data_bind_group_layout"), + entries: &[ + // Keys + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: false }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + // Values + 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: None, + }, + ], + }); + + let double_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("RadixSorter::double_buffer_bind_group"), + layout: &data_bind_group_layout, + entries: &[ + // Keys + wgpu::BindGroupEntry { + binding: 0, + resource: double_buffer_keys.as_entire_binding(), + }, + // Values + wgpu::BindGroupEntry { + binding: 1, + resource: double_buffer_values.as_entire_binding(), + }, + ], + }); + + let counts_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("RadixSorter::counts_bind_group"), + layout: &data_bind_group_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: sort_count_buffer.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: group_count_buffer.as_entire_binding(), + }, + ], + }); + + let pipelines_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("RadixSorter::pipelines_layout"), + bind_group_layouts: &[ + Some(&histograms_bind_group_layout), + // Double buffering : + // Source buffer + Some(&data_bind_group_layout), + // Dest buffer + Some(&data_bind_group_layout), + // (Two buffers same layout as histograms) + // Sort count buffer, indirect buffer + Some(&data_bind_group_layout), + ], + immediate_size: size_of::() as u32, // for the pass number + }); + + let radix_sort_shader_module = + device.create_shader_module(include_spirv!("../../shaders/radix_sort.spv")); + + let compilation_options = wgpu::PipelineCompilationOptions { + zero_initialize_workgroup_memory: false, + ..Default::default() + }; + + let histogram_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("RadixSorter::histogram_pass"), + layout: Some(&pipelines_layout), + module: &radix_sort_shader_module, + entry_point: Some("histogram_pass"), + compilation_options: compilation_options.clone(), + cache: None, + }); + + let running_sum_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("RadixSorter::running_sum_pass"), + layout: Some(&pipelines_layout), + module: &radix_sort_shader_module, + entry_point: Some("running_sum_pass"), + compilation_options: compilation_options.clone(), + cache: None, + }); + + let scatter_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("RadixSorter::scatter_pass"), + layout: Some(&pipelines_layout), + module: &radix_sort_shader_module, + entry_point: Some("scatter_pass"), + compilation_options: compilation_options.clone(), + cache: None, + }); + + let indirect_count_pass = + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("RadixSorter::indirect_count_pass"), + layout: Some(&pipelines_layout), + module: &radix_sort_shader_module, + entry_point: Some("indirect_count_pass"), + compilation_options: compilation_options.clone(), + cache: None, + }); + + RadixSorter { + max_size, + block_count, + histograms, + histograms_bind_group, + digit_stride: digit_stride as u32, + + sort_count_buffer, + group_count_buffer, + counts_bind_group, + indirect_buffer, + + data_bind_group_layout, + + double_buffer_keys, + double_buffer_values, + double_buffer_bind_group, + + histogram_reduce: HistogramScanner::new(device, histogram_count), + histogram_pass, + running_sum_pass, + scatter_pass, + indirect_count_pass, + } + } + + pub fn sort( + &self, + device: &Device, + keys: &Buffer, + values: &Buffer, + indirect_count: Option<&Buffer>, + encoder: &mut CommandEncoder, + sort_direction: RadixSortDirection, + ) + { + let data_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("RadixSorter::double_buffer_bind_group"), + layout: &self.data_bind_group_layout, + entries: &[ + // Keys + wgpu::BindGroupEntry { + binding: 0, + resource: keys.as_entire_binding(), + }, + // Values + wgpu::BindGroupEntry { + binding: 1, + resource: values.as_entire_binding(), + }, + ], + }); + + let counts_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("RadixSorter::sort_count_bind_group"), + layout: &self.data_bind_group_layout, + entries: &[ + // Sort count + wgpu::BindGroupEntry { + binding: 0, + resource: indirect_count + .unwrap_or(&self.sort_count_buffer) + .as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: self.group_count_buffer.as_entire_binding(), + }, + ], + }); + + let bg = [&data_buffer_bind_group, &self.double_buffer_bind_group]; + + // Compute how many workgroups to dispatch + let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("RadixSorter::indirect_compute_pass"), + timestamp_writes: None, + }); + //compute_pass.set_bind_group(0, &hi, &[]); + compute_pass.set_pipeline(&self.indirect_count_pass); + compute_pass.set_bind_group(0, &self.histograms_bind_group, &[]); + compute_pass.set_bind_group(1, &data_buffer_bind_group, &[]); + compute_pass.set_bind_group(2, &self.double_buffer_bind_group, &[]); + compute_pass.set_bind_group(3, &counts_buffer_bind_group, &[]); + compute_pass.set_immediates( + 0, + bytemuck::bytes_of(&PassParameters { + pass_index: if indirect_count.is_some() { 1u32 } else { 0 }, + descending: 0, + digit_stride: self.digit_stride / (size_of::() as u32), + }), + ); + compute_pass.dispatch_workgroups(1, 1, 1); + drop(compute_pass); + + // self.histogram_reduce.precompute_counts( + // device, + // indirect_count.unwrap_or(&self.sort_count_buffer), + // encoder, + // ); + + // Copy computed count over to indirect buffer + encoder.copy_buffer_to_buffer( + &self.group_count_buffer, + 0, + &self.indirect_buffer, + 0, + size_of::() as u64, + ); + + let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("RadixSorter::compute_pass"), + timestamp_writes: None, + }); + compute_pass.set_bind_group(0, &self.histograms_bind_group, &[]); + compute_pass.set_bind_group(3, &counts_buffer_bind_group, &[]); + + for i in 0..Self::PASS_COUNT + { + let parameters = PassParameters { + pass_index: i as u32, + descending: match sort_direction + { + RadixSortDirection::Ascending => 0, + RadixSortDirection::Descending => 1, + }, + digit_stride: self.digit_stride / (size_of::() as u32), + }; + let bytes = bytemuck::bytes_of(¶meters); + + compute_pass.set_bind_group(0, &self.histograms_bind_group, &[]); + compute_pass.set_bind_group(1, bg[i % 2], &[]); + compute_pass.set_bind_group(2, bg[1 - (i % 2)], &[]); + compute_pass.set_bind_group(3, &counts_buffer_bind_group, &[]); + + // ~~ Histogram pass + compute_pass.set_pipeline(&self.histogram_pass); + compute_pass.set_immediates(0, bytes); + compute_pass.dispatch_workgroups_indirect(&self.indirect_buffer, 0); + + /* + for digit in 0..Self::VALUE_COUNT + { + self.histogram_reduce.sum( + device, + &mut compute_pass, + &self.histograms, + (digit * self.digit_stride as usize) as u64, + self.digit_stride as u64, + ); + } + */ + + compute_pass.set_bind_group(0, &self.histograms_bind_group, &[]); + compute_pass.set_bind_group(1, bg[i % 2], &[]); + compute_pass.set_bind_group(2, bg[1 - (i % 2)], &[]); + compute_pass.set_bind_group(3, &counts_buffer_bind_group, &[]); + + // ~~ Running sum pass + compute_pass.set_pipeline(&self.running_sum_pass); + compute_pass.set_immediates(0, bytes); + compute_pass.dispatch_workgroups(1, 1, 1); + + // ~~ Scatter pass + compute_pass.set_pipeline(&self.scatter_pass); + compute_pass.set_immediates(0, bytes); + compute_pass.dispatch_workgroups_indirect(&self.indirect_buffer, 0); + } + + // Even number of passes => data is in the user buffer + drop(compute_pass); + } +} diff --git a/src/main.rs b/src/main.rs index d76fc33..7a851ab 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,8 +2,6 @@ #![feature(float_algebraic)] use std::collections::HashMap; -use std::collections::HashSet; -use std::ops::Div; use std::sync::Arc; use std::sync::mpsc::sync_channel; @@ -18,6 +16,7 @@ use glam::Mat4; use glam::Vec3; use glam::Vec4; use itertools::Itertools; +use rand::random_range; use rayon::iter::IndexedParallelIterator; use rayon::iter::IntoParallelRefIterator; use rayon::iter::ParallelIterator; @@ -31,16 +30,10 @@ use wgpu::Features; use wgpu::InstanceDescriptor; use wgpu::InstanceFlags; use wgpu::MemoryBudgetThresholds; -use wgpu::Operations; -use wgpu::Origin3d; -use wgpu::RenderPipeline; use wgpu::ShaderStages; use wgpu::Texture; use wgpu::TextureUsages; use wgpu::TextureView; -use wgpu::include_spirv; -use wgpu::include_wgsl; -use wgpu::util::BufferInitDescriptor; use wgpu::util::DeviceExt; use wgpu::util::DownloadBuffer; use winit::application::ApplicationHandler; @@ -58,6 +51,8 @@ use winit::window::WindowId; use crate::camera::Camera; use crate::egui_renderer::EguiRenderer; +use crate::gpu::radix_sort; +use crate::gpu::radix_sort::RadixSorter; use crate::producers::ChunkedProducer; use crate::producers::SdfGenerator; use crate::producers::SineGenerator; @@ -65,19 +60,15 @@ use crate::producers::TerrainGenerator; use crate::sparse_tree::NTreeNodeLocator; use crate::voxel_cache::VoxelAttribute; use crate::voxel_cache::VoxelCache; -use crate::voxel_cache::data::CacheNodeRequest; -use crate::voxel_cache::data::CacheResponse; use crate::voxel_cache::data::ColorBytes; -use crate::voxel_cache::data::ColorPoolElement; -use crate::voxel_cache::data::DestinationElement; use crate::voxel_cache::data::LocationPoolElement; use crate::voxel_cache::data::StructurePoolElement; -use crate::voxel_cache::indirect_buffer::NonZeroBufferCompactor; use crate::voxel_cache::producer_interface::CacheProducerInterface; use crate::voxel_cache::producer_interface::CacheRequest; mod camera; mod egui_renderer; +mod gpu; mod producers; mod sparse_tree; mod voxel_cache; @@ -116,8 +107,8 @@ struct State gi_bg_layout: BindGroupLayout, voxel_cache: Arc>>, cache_interface: Arc>, - terrain_generator: Arc>, - //terrain_generator: Arc>, + //terrain_generator: Arc>, + terrain_generator: Arc>, chunk_pos_map: Arc>, instance_buffer: Buffer, instance_count: usize, @@ -126,6 +117,10 @@ struct State frame_time: Arc>, insertion_debounce: bool, + terrain_width: usize, + terrain_height: usize, + terrain_alt: usize, + camera: Camera, } @@ -201,6 +196,92 @@ impl State let mut encoder = device.create_command_encoder(&Default::default()); + /* + let elt_count = 1_000_000u32; + //let elt_count = 1 << 20; + let count_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("count_buffer"), + contents: bytemuck::bytes_of(&elt_count), + usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, + }); + //let elt_count = 1 << 20; + //let elt_count = 512; + let org_big_value_buffer = (0..(elt_count as u32)).collect::>(); + let org_big_key_buffer = org_big_value_buffer + .iter() + .map(|_| random_range(0..2_000_000u32)) + .collect::>(); + + let sorted_values = org_big_key_buffer + .iter() + .zip(org_big_value_buffer.iter()) + .sorted_by_key(|(key, _)| *key) + .map(|(_, val)| *val) + .collect::>(); + + let big_key_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("big_key_buffer"), + contents: bytemuck::cast_slice(&org_big_key_buffer), + usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, + }); + + let big_value_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("big_value_buffer"), + contents: bytemuck::cast_slice(&org_big_value_buffer), + usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, + }); + + let sorter = RadixSorter::new(&device, 1 << 20); + //let sorter = RadixSorter::new(&device, 1_000_000); + //let sorter = RadixSorter::new(&device, 512); + sorter.sort( + &device, + &big_key_buffer, + &big_value_buffer, + //Some(&count_buffer), + None, + &mut encoder, + radix_sort::RadixSortDirection::Ascending, + ); + + queue.submit([encoder.finish()]); + + wgpu::util::DownloadBuffer::read_buffer( + &device, + &queue, + &big_key_buffer.slice(..), + |clbk| { + let data_bytes = clbk.unwrap().to_vec(); + let data = data_bytes + .chunks(4) + .map(|x| u32::from_ne_bytes([x[0], x[1], x[2], x[3]])) + .collect::>(); + println!("{:?}", &data[0..512]); + }, + ); + + wgpu::util::DownloadBuffer::read_buffer( + &device, + &queue, + &big_value_buffer.slice(..), + move |clbk| { + let data_bytes = clbk.unwrap().to_vec(); + let data = data_bytes + .chunks(4) + .map(|x| u32::from_ne_bytes([x[0], x[1], x[2], x[3]])) + .collect::>(); + for (gpu_key, key) in data.iter().zip(sorted_values.iter()) + { + assert_eq!(gpu_key, key, "FUCK YOU"); + } + println!("Finished check !"); + }, + ); + + device.poll(wgpu::wgt::PollType::Poll); + panic!(); + */ + let size = window.inner_size(); let surface = instance.create_surface(window.clone()).unwrap(); @@ -217,8 +298,8 @@ impl State VoxelCache::<4>::new(100_000, device.clone(), queue.clone(), attributes.clone()); let cache_interface = CacheProducerInterface::new(1024, &device, attributes.clone()); - //let terrain_generator = TerrainGenerator::<4>::new(5, "vxls_height.tif", 0.2, "img.jpg"); - let terrain_generator = SdfGenerator::<4>::new(5); + let terrain_generator = TerrainGenerator::<4>::new(5, "vxls_height.tif", 0.2, "img.jpg"); + //let terrain_generator = SdfGenerator::<4>::new(5); // let terrain_generator = TerrainGenerator::<4>::new( // 5, // "./pointe_percee/height.tif", @@ -233,10 +314,18 @@ impl State // ); // + let terrain_width = terrain_generator.chunk_width; + let terrain_height = terrain_generator.chunk_height; + let terrain_alt = terrain_generator.chunk_alt; + println!( + "Chunk count : {}", + terrain_width * terrain_height * terrain_width + ); + let mut chunk_pos_map = HashMap::new(); - let chunk_instances = (0..20) - .cartesian_product(0..20) - .cartesian_product(0..20) + let chunk_instances = (0..terrain_width) + .cartesian_product(0..terrain_height) + .cartesian_product(0..terrain_alt) .map(|((x, z), y)| { let chunk_id = voxel_cache.structure_table.allocate_structure(true); //dbg!(chunk_id); @@ -450,7 +539,10 @@ impl State layout: Some(&pipeline_layout), module: &shader_module, entry_point: Some("ray_march_compute"), - compilation_options: wgpu::PipelineCompilationOptions::default(), + compilation_options: wgpu::PipelineCompilationOptions { + zero_initialize_workgroup_memory: false, + ..Default::default() + }, cache: None, }); @@ -469,7 +561,10 @@ impl State layout: Some(&gi_pipeline_layout), module: &gi_shader_module, entry_point: Some("gi"), - compilation_options: wgpu::PipelineCompilationOptions::default(), + compilation_options: wgpu::PipelineCompilationOptions { + zero_initialize_workgroup_memory: false, + ..Default::default() + }, cache: None, }); @@ -521,6 +616,9 @@ impl State chunk_pos_map: chunk_pos_map.into(), rm_time: Arc::new(Mutex::new(0.)), frame_time: Arc::new(Mutex::new(0.)), + terrain_width, + terrain_height, + terrain_alt, }; // Configure surface for the first time @@ -834,9 +932,9 @@ impl State // chunk_width: self.terrain_generator.chunk_width as u32, // chunk_height: self.terrain_generator.chunk_height as u32, // chunk_alt: self.terrain_generator.chunk_alt as u32, - chunk_width: 20, - chunk_height: 20, - chunk_alt: 20, + chunk_width: self.terrain_width as u32, + chunk_height: self.terrain_height as u32, + chunk_alt: self.terrain_alt as u32, }]; renderpass.set_immediates(0, unsafe { as_raw_bytes(&imm) }); renderpass.dispatch_workgroups( diff --git a/src/producers.rs b/src/producers.rs index 03e866a..7d62e68 100644 --- a/src/producers.rs +++ b/src/producers.rs @@ -565,8 +565,8 @@ where children[index] = StructurePointer::new(subdivided, subdivided || alpha != 0.); children_normals[index] = (0., 0., 0.); - //children_color[index] = Color(color_avg.0, color_avg.1, color_avg.2, alpha); - children_color[index] = Color(1., 1., 1., alpha); + children_color[index] = Color(color_avg.0, color_avg.1, color_avg.2, alpha); + //children_color[index] = Color(1., 1., 1., alpha); } } diff --git a/src/voxel_cache.rs b/src/voxel_cache.rs index 0a97a66..6fa6f39 100644 --- a/src/voxel_cache.rs +++ b/src/voxel_cache.rs @@ -1,7 +1,7 @@ use std::num::NonZero; use bytemuck::Zeroable; -use wgpu::{BindGroup, BindGroupLayout, Buffer, BufferUsages, CommandEncoder, ComputePipeline, Device, Queue, ShaderStages}; +use wgpu::{BindGroup, BindGroupLayout, Buffer, BufferUsages, CommandEncoder, ComputePipeline, Device, Queue, ShaderStages, util::DeviceExt}; use crate::voxel_cache::{data::{CacheNodeRequest, CacheResponse, ColorPoolElement, LocationPoolElement, StructurePoolElement}, producer_interface::CacheProducerInterface, request_buffer::RequestBuffer, structure_table::StructureTable, usage_buffer::UsageBuffer}; @@ -21,6 +21,7 @@ pub struct VoxelCache queue: Queue, structure_pool: Buffer, location_pool: Buffer, + depth_pool: Buffer, attributes_pools: Vec, pub structure_table: StructureTable, @@ -84,6 +85,12 @@ where mapped_at_creation: false, }); + let depth_pool = device.create_buffer_init(&wgpu::util::BufferInitDescriptor{ + label: Some("Depth pool"), + contents: bytemuck::cast_slice(&vec![0xFFFFFFFFu32; cache_size]), + usage: BufferUsages::STORAGE, + }); + // Create attribttues let attributes_pools = attributes.iter().enumerate() @@ -227,18 +234,18 @@ where }, count: None, }, - // Sorted requests + // Depth pool wgpu::BindGroupLayoutEntry { binding: 3, visibility: ShaderStages::COMPUTE, ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: true }, + ty: wgpu::BufferBindingType::Storage { read_only: false }, has_dynamic_offset: false, min_binding_size: None, }, count: None, }, - // LRU List + // Sorted requests wgpu::BindGroupLayoutEntry { binding: 4, visibility: ShaderStages::COMPUTE, @@ -249,10 +256,21 @@ where }, count: None, }, - // Usage buffer + // LRU List wgpu::BindGroupLayoutEntry { binding: 5, visibility: ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: true }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + // Usage buffer + wgpu::BindGroupLayoutEntry { + binding: 6, + visibility: ShaderStages::COMPUTE, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: false }, has_dynamic_offset: false, @@ -262,7 +280,7 @@ where }, // pools request count wgpu::BindGroupLayoutEntry { - binding: 6, + binding: 7, visibility: ShaderStages::COMPUTE, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: true }, @@ -296,24 +314,29 @@ where binding: 2, resource: location_pool.as_entire_binding(), }, - // Sorted requests + // Depth pool wgpu::BindGroupEntry { binding: 3, + resource: depth_pool.as_entire_binding(), + }, + // Sorted requests + wgpu::BindGroupEntry { + binding: 4, resource: request_buffer.index_buffer().as_entire_binding(), }, // LRU list wgpu::BindGroupEntry { - binding: 4, + binding: 5, resource: usage_buffer.sort_buffer().as_entire_binding(), }, // Usage buffer wgpu::BindGroupEntry { - binding: 5, + binding: 6, resource: usage_buffer.usage_buffer().as_entire_binding(), }, // Pools request count wgpu::BindGroupEntry { - binding: 6, + binding: 7, resource: request_buffer.request_count_buffer().as_entire_binding(), }, ], @@ -397,10 +420,11 @@ where @group(0) @binding(0) var structure_pool: array; @group(0) @binding(1) var attributes_pools: binding_array; @group(0) @binding(2) var location_pool: array; - @group(0) @binding(3) var sorted_requests: array; - @group(0) @binding(4) var lru_list: array; - @group(0) @binding(5) var usage_buffer: array; - @group(0) @binding(6) var pools_request_count: u32; + @group(0) @binding(3) var depth_pool: array; + @group(0) @binding(4) var sorted_requests: array; + @group(0) @binding(5) var lru_list: array; + @group(0) @binding(6) var usage_buffer: array; + @group(0) @binding(7) var pools_request_count: u32; @group(1) @binding(0) var structure_table_pointers: array; @group(1) @binding(1) var structure_table_sorted_requests: array; @@ -661,9 +685,11 @@ where 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; }} }} @@ -765,6 +791,7 @@ where device, structure_pool, attributes_pools, + depth_pool, location_pool, request_buffer, usage_buffer, @@ -868,7 +895,6 @@ where // Sort requests, reset request buffers to count requests self.usage_buffer.sort_usage(encoder); self.request_buffer.sort_requests(encoder); - self.structure_table .request_buffer_mut() .sort_requests(encoder); diff --git a/src/voxel_cache/indirect_buffer.rs b/src/voxel_cache/indirect_buffer.rs index 150eb64..06a8d91 100644 --- a/src/voxel_cache/indirect_buffer.rs +++ b/src/voxel_cache/indirect_buffer.rs @@ -31,14 +31,14 @@ impl NonZeroBufferCompactor let block_count = size.div_ceil(Self::THREAD_COUNT * 2); let reduced_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("indirect_buffer_reduced"), - contents: bytemuck::cast_slice(vec![0; block_count + 1].as_slice()), + contents: bytemuck::cast_slice(vec![0u32; block_count + 1].as_slice()), usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, }); let sum_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("indirect_buffer_sum"), contents: bytemuck::cast_slice( - vec![0; block_count * Self::THREAD_COUNT * 2].as_slice(), + vec![0u32; block_count * Self::THREAD_COUNT * 2].as_slice(), ), usage: BufferUsages::STORAGE, }); diff --git a/src/voxel_cache/request_buffer.rs b/src/voxel_cache/request_buffer.rs index e223a69..ac2dedd 100644 --- a/src/voxel_cache/request_buffer.rs +++ b/src/voxel_cache/request_buffer.rs @@ -8,6 +8,8 @@ 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; @@ -17,19 +19,16 @@ pub struct RequestBuffer pub cache_size: usize, pub request_buffer: Buffer, - - pub sort_buffer: Buffer, + pub keys_buffer: Buffer, pub index_buffer: Buffer, - pub indirect_count_storage: Buffer, - pub indirect_count: Buffer, pub request_count: Buffer, + pub sorter: RadixSorter, pub buffer_compactor: NonZeroBufferCompactor, pub bindgroup: BindGroup, - pub compute_indirect_pipeline: ComputePipeline, - pub reset_pipeline: ComputePipeline, - pub sort_pipeline: ComputePipeline, + pub reset_pass: ComputePipeline, + pub copy_pass: ComputePipeline, } impl RequestBuffer @@ -38,27 +37,32 @@ where { 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: (size_of::>() * cache_size) as u64, + size: buffer_sizes, usage: BufferUsages::STORAGE | BufferUsages::COPY_DST, mapped_at_creation: false, }); - let indirect_count = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("indirect_count_buffer"), - usage: BufferUsages::INDIRECT | BufferUsages::COPY_DST, - size: size_of::() as u64, - mapped_at_creation: false, - }); - - let indirect_count_storage = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("indirect_count_storage_buffer"), + // 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, - size: size_of::() as u64, 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, @@ -66,25 +70,8 @@ where mapped_at_creation: false, }); - // One element number per child entry - // One number to identify node, one to identify sub child - let index_buffer_count = cache_size * N * N * N; - let index_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some(format!("request_index_buffer_{N}").as_str()), - size: (size_of::() * index_buffer_count) as u64, - usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, - mapped_at_creation: false, - }); - - let sort_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some(format!("request_sort_buffer_{N}").as_str()), - size: (size_of::() * index_buffer_count) as u64, - usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, - mapped_at_creation: false, - }); - let bindgroup_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("request_sort_pipeline_bing_group_layout"), + label: Some("RequestCount::bindgroup_layout"), entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, @@ -126,21 +113,11 @@ where }, count: None, }, - wgpu::BindGroupLayoutEntry { - binding: 4, - visibility: ShaderStages::COMPUTE, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: false }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, ], }); let bindgroup = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("request_sort_pipeline_bindgroup"), + label: Some("RequestCount::bindgroup"), layout: &bindgroup_layout, entries: &[ BindGroupEntry { @@ -149,18 +126,14 @@ where }, BindGroupEntry { binding: 1, - resource: sort_buffer.as_entire_binding(), - }, - BindGroupEntry { - binding: 2, resource: index_buffer.as_entire_binding(), }, BindGroupEntry { - binding: 3, - resource: indirect_count_storage.as_entire_binding(), + binding: 2, + resource: keys_buffer.as_entire_binding(), }, BindGroupEntry { - binding: 4, + binding: 3, resource: request_count.as_entire_binding(), }, ], @@ -172,155 +145,19 @@ where immediate_size: size_of::() as u32, }); - let children_count = N * N * N; - let sort_pipeline = + let reset_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("Sort node request"), + label: Some("RequestBuffer::reset_pass"), layout: Some(pipeline_layouts), module: &device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("clear_chunk_requests shader module"), + label: Some("RequestBuffer::reset_pass_module"), source: wgpu::ShaderSource::Wgsl( + #[allow(clippy::useless_format)] format!(" - var both_phase: u32; - @group(0) @binding(0) var request_buffer: array; - @group(0) @binding(1) var sort_buffer: array; - @group(0) @binding(2) var index_buffer: array; - @group(0) @binding(3) var indirect_count: vec3; - @group(0) @binding(4) var request_count: u32; - - fn big_fusion(index: u32, phase_size: u32) -> vec2 - {{ - // Find out in which block index this invocation pertains - let block_index = index / (phase_size / 2); - let element_index = index % (phase_size / 2); - - let offset = block_index * phase_size; - let a = offset + element_index; - let b = offset + phase_size - 1 - element_index; - return vec2(a, b); - }} - - fn small_fusion(index: u32, phase: u32, sub_phase: u32) -> vec2 - {{ - let phase_size = u32(1 << (phase - sub_phase + 1)); - - let block_index = index / (phase_size / 2); - let element_index = index % (phase_size / 2); - - let offset = block_index * phase_size; - let a = offset + element_index; - let b = a + (phase_size / 2); - return vec2(a, b); - }} - - - @compute - @workgroup_size(64, 1, 1) - fn main( - @builtin(global_invocation_id) global_invocation_id: vec3 - ) - {{ - - let index = global_invocation_id.x; - //let total = arrayLength(&sort_indirection); - - let sub_phase = (both_phase >> 16) & 0xFFFF; - let phase = both_phase & 0xFFFF; - let phase_total_width = u32(1 << (phase + 1)); - - - // Check if phase is last - if(phase == sub_phase) - {{ - let next_phase_width = phase_total_width * 2; - if(next_phase_width >= (request_count * 2) && phase_total_width >= (request_count * 2)) - {{ - indirect_count = vec3(0); - }} - }} - - if(phase == 0) - {{ - - // Phase 0. Index buffer contains indicies of compacted buffer. - // We can perform compaction on the data - let a = index * 2; - let b = a + 1; - - if(a < request_count) - {{ - let compact_index_a = index_buffer[a]; - sort_buffer[a] = request_buffer[compact_index_a]; - }} - if(b < request_count) - {{ - let compact_index_b = index_buffer[b]; - sort_buffer[b] = request_buffer[compact_index_b]; - }} - }} - - var swap_indices = vec2(0, 0); - - if(sub_phase == 0) - {{ - // Bitonic fusion - swap_indices = big_fusion(index, phase_total_width); - }}else - {{ - swap_indices = small_fusion(index, phase, sub_phase); - }} - - // Do swap - - //if(swap_indices.y >= request_count_round_up) - if(swap_indices.y >= request_count) - {{ - // Suppose that swap_indices.y is -inf, dont swap - return; - }} - - let av = sort_buffer[swap_indices.x]; - let bv = sort_buffer[swap_indices.y]; - - if(bv > av) - {{ - let sort_temp = sort_buffer[swap_indices.x]; - sort_buffer[swap_indices.x] = sort_buffer[swap_indices.y]; - sort_buffer[swap_indices.y] = sort_temp; - - let index_temp = index_buffer[swap_indices.x]; - index_buffer[swap_indices.x] = index_buffer[swap_indices.y]; - index_buffer[swap_indices.y] = index_temp; - }} - }} - ") - .into(), - ), - }), - entry_point: Some("main"), - compilation_options: Default::default(), - cache: None, - }); - - let reset_pipeline = - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("reset_node_requests"), - layout: Some(pipeline_layouts), - module: &device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("clear_chunk_requests shader module"), - source: wgpu::ShaderSource::Wgsl( - format!(" - struct RequestElement - {{ - children: array - }} - - @group(0) @binding(0) var request_buffer: array; - @group(0) @binding(1) var sort_buffer: array; - @group(0) @binding(2) var index_buffer: array; - @group(0) @binding(3) var indirect_count: vec3; - @group(0) @binding(4) var request_count: u32; + @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) @@ -328,12 +165,9 @@ where @builtin(global_invocation_id) global_invocation_id: vec3 ) {{ - let index = global_invocation_id.x; - let total = arrayLength(&request_buffer); - if(index >= total) - {{ return; }} - - request_buffer[index] = 0; + let total = arrayLength(&request_buffer); + if(global_invocation_id.x >= total) {{return;}} + request_buffer[global_invocation_id.x] = 0; }} ") .into(), @@ -344,33 +178,30 @@ where cache: None, }); - let compute_indirect_pipeline = + // 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("compute_indirect_pipeline"), + label: Some("RequestBuffer::copy_pass"), layout: Some(pipeline_layouts), module: &device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("clear_chunk_requests shader module"), + 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 sort_buffer: array; - @group(0) @binding(2) var index_buffer: array; - @group(0) @binding(3) var indirect_count: vec3; - @group(0) @binding(4) var request_count: u32; + @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(1, 1, 1) + @workgroup_size(256, 1, 1) fn main( @builtin(global_invocation_id) global_invocation_id: vec3 ) {{ - let invocation_count = (request_count / 2) - + select(u32(0), u32(1), request_count % 2 != 0); - - let workgroup_count = (invocation_count / 64) - + select(u32(0), u32(1), invocation_count % 64 != 0); - - indirect_count = vec3(workgroup_count, 1, 1); + if(global_invocation_id.x >= request_count) {{return;}} + keys_buffer[global_invocation_id.x] = request_buffer[index_buffer[global_invocation_id.x]]; }} ") .into(), @@ -382,18 +213,16 @@ where }); Self { - buffer_compactor: NonZeroBufferCompactor::new(&device, index_buffer_count), cache_size, request_buffer, index_buffer, - sort_buffer, - indirect_count, + keys_buffer, request_count, - indirect_count_storage, - compute_indirect_pipeline, - sort_pipeline, - reset_pipeline, + 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, } } @@ -421,7 +250,7 @@ where }); compute_pass.set_bind_group(0, Some(&self.bindgroup), &[]); - compute_pass.set_pipeline(&self.reset_pipeline); + 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); @@ -441,53 +270,25 @@ where self.buffer_compactor .copy_count_to_buffer(encoder, &self.request_count); - let mut compute_indirect_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { - label: Some("compute_indirect_pass"), + let mut copy_keys_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("RequestBuffer::copy_keys_pass"), timestamp_writes: None, }); - compute_indirect_pass.set_bind_group(0, Some(&self.bindgroup), &[]); + 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); - compute_indirect_pass.set_pipeline(&self.compute_indirect_pipeline); - compute_indirect_pass.dispatch_workgroups(1, 1, 1); - drop(compute_indirect_pass); - - // Now the indirect count storate buffer contains the workgroup count for the sort - // Copy that to the indirect buffer - encoder.copy_buffer_to_buffer( - &self.indirect_count_storage, - 0, - &self.indirect_count, - 0, - Some(size_of::() as u64), + self.sorter.sort( + &self.device, + &self.keys_buffer, + &self.index_buffer, + Some(&self.request_count), + encoder, + radix_sort::RadixSortDirection::Descending, ); - - // Sort - let sort_element_count = self.cache_size * N * N * N; - let phases_upper_bound = sort_element_count.next_power_of_two().ilog2(); - - // Phase 0 dispatch all - for i in 0..=phases_upper_bound - { - encoder.copy_buffer_to_buffer( - &self.indirect_count_storage, - 0, - &self.indirect_count, - 0, - Some(size_of::() as u64), - ); - let mut sort_compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { - label: Some(format!("request_buffer_sort_compute_pass_{}", 0).as_str()), - timestamp_writes: None, - }); - sort_compute_pass.set_bind_group(0, Some(&self.bindgroup), &[]); - sort_compute_pass.set_pipeline(&self.sort_pipeline); - for j in 0..=i - { - sort_compute_pass.set_immediates(0, bytemuck::bytes_of(&(i | (j << 16)))); - sort_compute_pass.dispatch_workgroups_indirect(&self.indirect_count, 0); - } - drop(sort_compute_pass); - } } }