Skip to main content

wgpu_primitives/sort/
sorter.rs

1use crate::context::Context;
2use crate::{Error, GpuProfile};
3
4use super::core::RadixSorter;
5use super::pipeline::SortItemKind;
6
7/// Performs an unsigned 32-bit LSD radix sort on a wgpu device.
8pub struct Sorter {
9    core: RadixSorter,
10}
11
12impl Sorter {
13    /// Creates a sorter that submits work through an existing wgpu device and queue.
14    pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
15        Self {
16            core: RadixSorter::new(device, queue, SortItemKind::Key),
17        }
18    }
19
20    /// Creates a sorter from the crate's optional convenience context.
21    pub fn from_context(ctx: &Context) -> Self {
22        Self::new(&ctx.device, &ctx.queue)
23    }
24
25    /// Uploads values, sorts them on the GPU, and downloads the sorted result.
26    pub async fn sort(&mut self, input: &[u32]) -> Result<Vec<u32>, Error> {
27        self.core.sort_slice(input).await
28    }
29
30    /// Sorts caller-owned GPU buffers and submits the work immediately.
31    pub fn sort_gpu_to_gpu(
32        &mut self,
33        input: &wgpu::Buffer,
34        output: &wgpu::Buffer,
35        num_items: u32,
36    ) -> Result<(), Error> {
37        self.core.sort_gpu_to_gpu(input, output, num_items)
38    }
39
40    /// Profiles a GPU-buffer radix sort using GPU timestamps.
41    pub async fn profile_sort_gpu_to_gpu(
42        &mut self,
43        input: &wgpu::Buffer,
44        output: &wgpu::Buffer,
45        num_items: u32,
46    ) -> Result<GpuProfile, Error> {
47        self.core
48            .profile_sort_gpu_to_gpu(input, output, num_items)
49            .await
50    }
51
52    /// Records a GPU radix sort without submitting or waiting for the work.
53    pub fn record_sort(
54        &mut self,
55        encoder: &mut wgpu::CommandEncoder,
56        input: &wgpu::Buffer,
57        output: &wgpu::Buffer,
58        num_items: u32,
59    ) -> Result<(), Error> {
60        self.core.record_sort(encoder, input, output, num_items)
61    }
62}