shitty radix
This commit is contained in:
+1
-1
@@ -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
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,158 @@
|
||||
[[vk::binding(0, 0)]]
|
||||
RWStructuredBuffer<uint32_t> count_buffer;
|
||||
[[vk::binding(0, 1)]]
|
||||
RWStructuredBuffer<uint32_t> 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<uint32_t> total_count;
|
||||
[[vk::binding(0, 1)]]
|
||||
RWStructuredBuffer<IndirectArgs> 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);
|
||||
}
|
||||
|
||||
Binary file not shown.
@@ -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<uint32_t> histograms;
|
||||
|
||||
[vk::binding(0, 1)]
|
||||
RWStructuredBuffer<uint32_t> key_buffer;
|
||||
[vk::binding(1, 1)]
|
||||
RWStructuredBuffer<uint32_t> value_buffer;
|
||||
|
||||
// Double buffering
|
||||
[vk::binding(0, 2)]
|
||||
RWStructuredBuffer<uint32_t> dest_key_buffer;
|
||||
[vk::binding(1, 2)]
|
||||
RWStructuredBuffer<uint32_t> dest_value_buffer;
|
||||
|
||||
[vk::binding(0, 3)]
|
||||
RWStructuredBuffer<uint32_t> sort_count;
|
||||
[vk::binding(1, 3)]
|
||||
RWStructuredBuffer<IndirectArgs> 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<uint32_t>[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;
|
||||
}
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,2 @@
|
||||
// Main common gpu parallel algorithms
|
||||
pub mod radix_sort;
|
||||
@@ -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::<u32>() * 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::<wgpu::util::DispatchIndirectArgs>() * 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::<wgpu::util::DispatchIndirectArgs>() * 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::<wgpu::util::DispatchIndirectArgs>()) 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::<Vec<_>>();
|
||||
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::<wgpu::util::DispatchIndirectArgs>() * 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::<wgpu::util::DispatchIndirectArgs>() * (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::<u32>()).next_multiple_of(256);
|
||||
//let digit_stride = histogram_count * size_of::<u32>();
|
||||
|
||||
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::<u32>() * 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::<u32>() * 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::<PassParameters>() 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::<u32>() 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::<wgpu::util::DispatchIndirectArgs>() 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::<u32>() 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);
|
||||
}
|
||||
}
|
||||
+123
-25
@@ -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<Mutex<VoxelCache<4>>>,
|
||||
cache_interface: Arc<CacheProducerInterface<4>>,
|
||||
terrain_generator: Arc<SdfGenerator<4>>,
|
||||
//terrain_generator: Arc<TerrainGenerator<4>>,
|
||||
//terrain_generator: Arc<SdfGenerator<4>>,
|
||||
terrain_generator: Arc<TerrainGenerator<4>>,
|
||||
chunk_pos_map: Arc<HashMap<u32, (usize, usize, usize)>>,
|
||||
instance_buffer: Buffer,
|
||||
instance_count: usize,
|
||||
@@ -126,6 +117,10 @@ struct State
|
||||
frame_time: Arc<Mutex<f32>>,
|
||||
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::<Vec<_>>();
|
||||
let org_big_key_buffer = org_big_value_buffer
|
||||
.iter()
|
||||
.map(|_| random_range(0..2_000_000u32))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let sorted_values = org_big_key_buffer
|
||||
.iter()
|
||||
.zip(org_big_value_buffer.iter())
|
||||
.sorted_by_key(|(key, _)| *key)
|
||||
.map(|(_, val)| *val)
|
||||
.collect::<Vec<u32>>();
|
||||
|
||||
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::<Vec<u32>>();
|
||||
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::<Vec<u32>>();
|
||||
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(
|
||||
|
||||
+2
-2
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+41
-15
@@ -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<const N: usize>
|
||||
queue: Queue,
|
||||
structure_pool: Buffer,
|
||||
location_pool: Buffer,
|
||||
depth_pool: Buffer,
|
||||
attributes_pools: Vec<Buffer>,
|
||||
|
||||
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<storage, read_write> structure_pool: array<StructurePoolElement>;
|
||||
@group(0) @binding(1) var<storage, read_write> attributes_pools: binding_array<AttributeArray, {attribute_count}>;
|
||||
@group(0) @binding(2) var<storage, read_write> location_pool: array<LocationPoolElement>;
|
||||
@group(0) @binding(3) var<storage, read> sorted_requests: array<u32>;
|
||||
@group(0) @binding(4) var<storage, read> lru_list: array<u32>;
|
||||
@group(0) @binding(5) var<storage, read_write> usage_buffer: array<u32>;
|
||||
@group(0) @binding(6) var<storage, read> pools_request_count: u32;
|
||||
@group(0) @binding(3) var<storage, read_write> depth_pool: array<u32>;
|
||||
@group(0) @binding(4) var<storage, read> sorted_requests: array<u32>;
|
||||
@group(0) @binding(5) var<storage, read> lru_list: array<u32>;
|
||||
@group(0) @binding(6) var<storage, read_write> usage_buffer: array<u32>;
|
||||
@group(0) @binding(7) var<storage, read> pools_request_count: u32;
|
||||
|
||||
@group(1) @binding(0) var<storage, read_write> structure_table_pointers: array<u32>;
|
||||
@group(1) @binding(1) var<storage, read_write> structure_table_sorted_requests: array<u32>;
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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<const N: usize>
|
||||
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<const N: usize> RequestBuffer<N>
|
||||
@@ -38,27 +37,32 @@ where
|
||||
{
|
||||
pub fn new(cache_size: usize, device: Device) -> Self
|
||||
{
|
||||
let buffer_sizes = (size_of::<u32>() * 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::<RequestBufferElement<N>>() * 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::<wgpu::util::DispatchIndirectArgs>() 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::<wgpu::util::DispatchIndirectArgs>() 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::<u32>() * 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::<u32>() * 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::<u32>() 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<immediate> both_phase: u32;
|
||||
|
||||
@group(0) @binding(0) var<storage, read_write> request_buffer: array<u32>;
|
||||
@group(0) @binding(1) var<storage, read_write> sort_buffer: array<u32>;
|
||||
@group(0) @binding(2) var<storage, read_write> index_buffer: array<u32>;
|
||||
@group(0) @binding(3) var<storage, read_write> indirect_count: vec3<u32>;
|
||||
@group(0) @binding(4) var<storage, read_write> request_count: u32;
|
||||
|
||||
fn big_fusion(index: u32, phase_size: u32) -> vec2<u32>
|
||||
{{
|
||||
// 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<u32>(a, b);
|
||||
}}
|
||||
|
||||
fn small_fusion(index: u32, phase: u32, sub_phase: u32) -> vec2<u32>
|
||||
{{
|
||||
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<u32>(a, b);
|
||||
}}
|
||||
|
||||
|
||||
@compute
|
||||
@workgroup_size(64, 1, 1)
|
||||
fn main(
|
||||
@builtin(global_invocation_id) global_invocation_id: vec3<u32>
|
||||
)
|
||||
{{
|
||||
|
||||
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<u32>(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<u32>(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<u32, {children_count}>
|
||||
}}
|
||||
|
||||
@group(0) @binding(0) var<storage, read_write> request_buffer: array<u32>;
|
||||
@group(0) @binding(1) var<storage, read_write> sort_buffer: array<u32>;
|
||||
@group(0) @binding(2) var<storage, read_write> index_buffer: array<u32>;
|
||||
@group(0) @binding(3) var<storage, read_write> indirect_count: vec3<u32>;
|
||||
@group(0) @binding(4) var<storage, read_write> request_count: u32;
|
||||
@group(0) @binding(1) var<storage, read_write> index_buffer: array<u32>;
|
||||
@group(0) @binding(2) var<storage, read_write> keys_buffer: array<u32>;
|
||||
@group(0) @binding(3) var<storage, read_write> request_count: u32;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
@@ -328,12 +165,9 @@ where
|
||||
@builtin(global_invocation_id) global_invocation_id: vec3<u32>
|
||||
)
|
||||
{{
|
||||
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<storage, read_write> request_buffer: array<u32>;
|
||||
@group(0) @binding(1) var<storage, read_write> sort_buffer: array<u32>;
|
||||
@group(0) @binding(2) var<storage, read_write> index_buffer: array<u32>;
|
||||
@group(0) @binding(3) var<storage, read_write> indirect_count: vec3<u32>;
|
||||
@group(0) @binding(4) var<storage, read_write> request_count: u32;
|
||||
@group(0) @binding(1) var<storage, read_write> index_buffer: array<u32>;
|
||||
@group(0) @binding(2) var<storage, read_write> keys_buffer: array<u32>;
|
||||
@group(0) @binding(3) var<storage, read_write> request_count: u32;
|
||||
|
||||
@compute
|
||||
@workgroup_size(1, 1, 1)
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn main(
|
||||
@builtin(global_invocation_id) global_invocation_id: vec3<u32>
|
||||
)
|
||||
{{
|
||||
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<u32>(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::<wgpu::util::DispatchIndirectArgs>() 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::<wgpu::util::DispatchIndirectArgs>() 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user