formatting: Using canonical formatting on whole project

This commit is contained in:
2026-11-22 17:16:32 +01:00
parent 2910314df3
commit dd0e102348
44 changed files with 1526 additions and 3376 deletions
+8 -17
View File
@@ -10,8 +10,7 @@ use wgpu::Device;
use wgpu::ShaderStages;
use wgpu::util::DeviceExt;
pub struct NonZeroBufferCompactor
{
pub struct NonZeroBufferCompactor {
block_count: usize,
reduced_buffer: Buffer,
#[allow(unused)]
@@ -24,11 +23,9 @@ pub struct NonZeroBufferCompactor
scatter_pipeline: ComputePipeline,
}
impl NonZeroBufferCompactor
{
impl NonZeroBufferCompactor {
const THREAD_COUNT: usize = 256;
pub fn new(device: &Device, size: usize) -> Self
{
pub fn new(device: &Device, size: usize) -> Self {
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"),
@@ -189,14 +186,12 @@ impl NonZeroBufferCompactor
}
}
pub fn total_sum_buffer(&self) -> BufferSlice<'_>
{
pub fn total_sum_buffer(&self) -> BufferSlice<'_> {
self.reduced_buffer
.slice(((size_of::<u32>() * self.block_count) as u64)..)
}
pub fn copy_count_to_buffer(&self, encoder: &mut CommandEncoder, target: &Buffer)
{
pub fn copy_count_to_buffer(&self, encoder: &mut CommandEncoder, target: &Buffer) {
encoder.copy_buffer_to_buffer(
&self.reduced_buffer,
(size_of::<u32>() * self.block_count) as u64,
@@ -213,8 +208,7 @@ impl NonZeroBufferCompactor
count_buffer: &Buffer,
index_buffer: &Buffer,
compact_buffer: Option<&Buffer>,
)
{
) {
let count_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("count_buffer_bind_group"),
layout: &self.count_buffer_bg_layout,
@@ -253,12 +247,9 @@ impl NonZeroBufferCompactor
compute_pass.set_pipeline(&self.scatter_pipeline);
compute_pass.set_immediates(
0,
if compact_buffer.is_some()
{
if compact_buffer.is_some() {
bytes_of(&1)
}
else
{
} else {
bytes_of(&0)
},
);
+4 -8
View File
@@ -4,8 +4,7 @@ use wgpu::Buffer;
use wgpu::CommandEncoder;
/// Takes in a single u32, and computes the amount of workgroups to dispatch given a workgroup size
pub struct IndirectBuffer1D
{
pub struct IndirectBuffer1D {
/// Buffer used in the indirect dispatch command
indirect_buffer: wgpu::Buffer,
@@ -17,10 +16,8 @@ pub struct IndirectBuffer1D
compute_pipeline: wgpu::ComputePipeline,
}
impl IndirectBuffer1D
{
pub fn new(device: &wgpu::Device) -> Self
{
impl IndirectBuffer1D {
pub fn new(device: &wgpu::Device) -> Self {
let indirect_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("IndirectBuffer1D::indirect_buffer"),
size: size_of::<wgpu::util::DispatchIndirectArgs>() as u64,
@@ -127,8 +124,7 @@ impl IndirectBuffer1D
encoder: &mut CommandEncoder,
count_buffer: &Buffer,
workgroup_size: u32,
) -> &Buffer
{
) -> &Buffer {
// Transient bind group
let user_count_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("IndirectBuffer1D::bind_group"),
+3 -6
View File
@@ -9,8 +9,7 @@ pub fn create_multi_buffers_bind_group_layout(
device: &wgpu::Device,
count: u32,
label: Option<&str>,
) -> wgpu::BindGroupLayout
{
) -> wgpu::BindGroupLayout {
let entries = (0..count)
.map(|i| wgpu::BindGroupLayoutEntry {
binding: i,
@@ -35,8 +34,7 @@ pub fn create_multi_buffers_bind_group(
layout: &wgpu::BindGroupLayout,
buffers: &[&wgpu::Buffer],
label: Option<&str>,
) -> wgpu::BindGroup
{
) -> wgpu::BindGroup {
let entries = buffers
.iter()
.enumerate()
@@ -57,8 +55,7 @@ pub fn create_multi_buffers_bg_bg_layout(
device: &wgpu::Device,
buffers: &[&wgpu::Buffer],
label: Option<&str>,
) -> (wgpu::BindGroupLayout, wgpu::BindGroup)
{
) -> (wgpu::BindGroupLayout, wgpu::BindGroup) {
let layout = create_multi_buffers_bind_group_layout(device, buffers.len() as u32, label);
let bg = create_multi_buffers_bind_group(device, &layout, buffers, label);
(layout, bg)
+10 -21
View File
@@ -9,23 +9,20 @@ use wgpu::QuerySet;
use wgpu::include_spirv;
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum RadixSortDirection
{
pub enum RadixSortDirection {
Ascending,
Descending,
}
#[derive(Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)]
#[repr(C)]
struct PassParameters
{
struct PassParameters {
pass_index: u32,
descending: u32,
digit_stride: u32,
}
pub struct RadixSorter
{
pub struct RadixSorter {
max_size: usize,
histogram_count: usize,
@@ -56,8 +53,7 @@ pub struct RadixSorter
pub timing_buffer: Buffer,
}
impl RadixSorter
{
impl RadixSorter {
// How many total digits u32 => 32
const TOTAL_BIN_DIGIT_COUNT: usize = 32;
@@ -79,8 +75,7 @@ impl RadixSorter
// Elements managed per workgroup for histo build
const WG_HISTO_ELEMENTS: usize = Self::WG_THREAD_COUNT * Self::WE_HISTO_ELEMENTS;
pub fn new(device: &Device, max_size: usize) -> Self
{
pub fn new(device: &Device, max_size: usize) -> Self {
// How many blocks (workgroups) for histobuild
let histo_block_count = max_size.div_ceil(Self::WG_HISTO_ELEMENTS);
@@ -330,8 +325,7 @@ impl RadixSorter
direct_length: Option<usize>,
encoder: &mut CommandEncoder,
sort_direction: RadixSortDirection,
)
{
) {
let data_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("RadixSorter::data_buffer_bind_group"),
layout: &self.data_bind_group_layout,
@@ -379,12 +373,9 @@ impl RadixSorter
});
let parameters = PassParameters {
pass_index: if indirect.is_some()
{
pass_index: if indirect.is_some() {
0
}
else
{
} else {
direct_length.unwrap_or(self.max_size) as u32
},
descending: 0,
@@ -421,12 +412,10 @@ impl RadixSorter
}),
});
for i in 0..Self::PASS_COUNT
{
for i in 0..Self::PASS_COUNT {
let parameters = PassParameters {
pass_index: i as u32,
descending: match sort_direction
{
descending: match sort_direction {
RadixSortDirection::Ascending => 0,
RadixSortDirection::Descending => 1,
},
+40 -81
View File
@@ -47,8 +47,7 @@ const _: () = assert!(SUB_BINS.is_power_of_two());
/// Parameters passed to the shader through immediates.
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct TopKParams
{
struct TopKParams {
element_count: u32,
k: u32,
}
@@ -58,8 +57,7 @@ struct TopKParams
/// The selector owns its scratch and output buffers, so a single instance
/// cannot be used for two overlapping selections. Create one instance per
/// concurrent selection, or copy the results before the next call.
pub struct TopKSelector
{
pub struct TopKSelector {
max_selected: u32,
histogram: Buffer,
@@ -75,11 +73,9 @@ pub struct TopKSelector
select_pass: ComputePipeline,
}
impl TopKSelector
{
impl TopKSelector {
/// Creates a selector that can output at most `max_selected` indices.
pub fn new(device: &Device, max_selected: u32) -> Self
{
pub fn new(device: &Device, max_selected: u32) -> Self {
assert!(
device.features().contains(wgpu::Features::IMMEDIATES),
"TopKSelector requires the IMMEDIATES feature"
@@ -284,8 +280,7 @@ impl TopKSelector
requests: &Buffer,
element_count: u32,
k: u32,
)
{
) {
assert!(
k <= self.max_selected,
"TopKSelector: k ({k}) exceeds the max_selected capacity ({})",
@@ -355,51 +350,41 @@ impl TopKSelector
}
/// Number of indices emitted by the last [`Self::select`] call.
pub fn selected_count_buffer(&self) -> &Buffer
{
pub fn selected_count_buffer(&self) -> &Buffer {
&self.selected_count
}
/// Indices emitted by the last [`Self::select`] call, in arbitrary order.
pub fn selected_indices_buffer(&self) -> &Buffer
{
pub fn selected_indices_buffer(&self) -> &Buffer {
&self.selected_indices
}
/// Threshold bin of the last [`Self::select`] call, or `-1` if every
/// non-zero element was selected.
pub fn threshold_buffer(&self) -> &Buffer
{
pub fn threshold_buffer(&self) -> &Buffer {
&self.threshold
}
/// Maximum number of indices this selector can emit.
pub fn max_selected(&self) -> u32
{
pub fn max_selected(&self) -> u32 {
self.max_selected
}
}
#[cfg(test)]
mod tests
{
mod tests {
use super::*;
/// CPU mirror of the WGSL quantizer.
fn quantize_cpu(count: u32) -> u32
{
if count == 0
{
fn quantize_cpu(count: u32) -> u32 {
if count == 0 {
return 0;
}
let exponent = 31 - count.leading_zeros();
let extra = if exponent >= LOG_SUB_BINS
{
let extra = if exponent >= LOG_SUB_BINS {
(count >> (exponent - LOG_SUB_BINS)) & (SUB_BINS - 1)
}
else
{
} else {
(count << (LOG_SUB_BINS - exponent)) & (SUB_BINS - 1)
};
@@ -407,14 +392,11 @@ mod tests
}
/// CPU mirror of the three passes.
fn select_cpu(counts: &[u32], k: u32) -> (Vec<u32>, i32)
{
fn select_cpu(counts: &[u32], k: u32) -> (Vec<u32>, i32) {
let mut histogram = vec![0u32; BIN_COUNT as usize];
for &count in counts
{
if count != 0
{
for &count in counts {
if count != 0 {
histogram[quantize_cpu(count) as usize] += 1;
}
}
@@ -422,12 +404,10 @@ mod tests
let mut sum = 0u32;
let mut threshold = -1i32;
for bin in (0..BIN_COUNT as usize).rev()
{
for bin in (0..BIN_COUNT as usize).rev() {
let count = histogram[bin];
if sum + count >= k
{
if sum + count >= k {
threshold = bin as i32;
break;
}
@@ -447,18 +427,14 @@ mod tests
// Fill the remaining slots from the threshold bin. The GPU picks these
// in arbitrary order; the CPU mirror fills them in index order so the
// tests stay deterministic.
if threshold >= 0
{
if threshold >= 0 {
let mut slots = remaining;
for (index, &count) in counts.iter().enumerate()
{
if slots == 0
{
for (index, &count) in counts.iter().enumerate() {
if slots == 0 {
break;
}
if count != 0 && quantize_cpu(count) as i32 == threshold
{
if count != 0 && quantize_cpu(count) as i32 == threshold {
selected.push(index as u32);
slots -= 1;
}
@@ -468,8 +444,7 @@ mod tests
(selected, threshold)
}
fn next_random(state: &mut u64) -> u32
{
fn next_random(state: &mut u64) -> u32 {
*state ^= *state << 13;
*state ^= *state >> 7;
*state ^= *state << 17;
@@ -477,12 +452,10 @@ mod tests
}
#[test]
fn quantize_is_monotonic()
{
fn quantize_is_monotonic() {
let mut previous = 0;
for count in 1..100_000u32
{
for count in 1..100_000u32 {
let bin = quantize_cpu(count);
assert!(bin >= previous, "quantize({count}) = {bin} < {previous}");
assert!(bin < BIN_COUNT);
@@ -496,8 +469,7 @@ mod tests
values.sort_unstable();
let mut previous = 0;
for count in values
{
for count in values {
let bin = quantize_cpu(count);
assert!(bin >= previous);
assert!(bin < BIN_COUNT);
@@ -506,19 +478,16 @@ mod tests
}
#[test]
fn quantize_handles_zero_and_max()
{
fn quantize_handles_zero_and_max() {
assert_eq!(quantize_cpu(0), 0);
assert!(quantize_cpu(u32::MAX) < BIN_COUNT);
}
#[test]
fn selection_selects_exactly_min_k_and_non_zero()
{
fn selection_selects_exactly_min_k_and_non_zero() {
let mut state = 0x0ddc_0ffe_e15e_beefu64;
for _ in 0..100
{
for _ in 0..100 {
let len = 1 + (next_random(&mut state) % 1000) as usize;
let counts = (0..len)
.map(|_| next_random(&mut state) % 64)
@@ -526,8 +495,7 @@ mod tests
let non_zero = counts.iter().filter(|&&count| count != 0).count();
for k in 0..=20
{
for k in 0..=20 {
let (selected, threshold) = select_cpu(&counts, k);
assert_eq!(selected.len(), (k as usize).min(non_zero));
@@ -537,8 +505,7 @@ mod tests
sorted.dedup();
assert_eq!(sorted.len(), selected.len(), "duplicate indices");
for &index in &selected
{
for &index in &selected {
let count = counts[index as usize];
assert!(count != 0);
assert!(quantize_cpu(count) as i32 >= threshold);
@@ -548,8 +515,7 @@ mod tests
}
#[test]
fn selection_fills_threshold_bin_to_exactly_k()
{
fn selection_fills_threshold_bin_to_exactly_k() {
let counts = [1, 5, 3, 5, 2];
let (selected, _) = select_cpu(&counts, 3);
@@ -560,8 +526,7 @@ mod tests
}
#[test]
fn selection_with_fewer_candidates_than_k()
{
fn selection_with_fewer_candidates_than_k() {
let counts = [1, 0, 2, 0, 3];
let (selected, threshold) = select_cpu(&counts, 10);
@@ -570,8 +535,7 @@ mod tests
}
#[test]
fn selection_with_k_zero()
{
fn selection_with_k_zero() {
let counts = [1, 2, 3];
let (selected, _) = select_cpu(&counts, 0);
@@ -579,8 +543,7 @@ mod tests
}
#[test]
fn selection_with_all_equal_counts_selects_k()
{
fn selection_with_all_equal_counts_selects_k() {
let counts = [7, 7, 7, 7];
let (selected, threshold) = select_cpu(&counts, 2);
@@ -590,8 +553,7 @@ mod tests
}
#[test]
fn selection_with_all_zero_counts()
{
fn selection_with_all_zero_counts() {
let counts = [0, 0, 0, 0];
let (selected, threshold) = select_cpu(&counts, 2);
@@ -601,8 +563,7 @@ mod tests
#[test]
#[ignore = "requires a GPU adapter with the IMMEDIATES feature"]
fn gpu_selection_smoke_test()
{
fn gpu_selection_smoke_test() {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let adapter =
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default()))
@@ -628,8 +589,7 @@ mod tests
// Run the selection twice to verify that the histogram and fill state
// are reset between calls.
for _ in 0..2
{
for _ in 0..2 {
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("TopKSelector::test_encoder"),
});
@@ -678,8 +638,7 @@ mod tests
device: &wgpu::Device,
queue: &wgpu::Queue,
selector: &TopKSelector,
) -> (u32, Vec<u32>)
{
) -> (u32, Vec<u32>) {
let count = std::sync::Arc::new(std::sync::Mutex::new(None));
let count_clone = count.clone();
wgpu::util::DownloadBuffer::read_buffer(