1use bytemuck::{Pod, Zeroable};
4use spatialrust_core::{SpatialError, SpatialResult};
5use wgpu::util::DeviceExt;
6
7use crate::image::gpu_image::{create_texture, GpuImage};
8use crate::{scratch::ScratchBuffers, GpuStageProfiler, WgpuRuntime};
9
10const WORKGROUP: u32 = 256;
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum GpuGaussianBorder {
15 Replicate,
17 Reflect,
19 Reflect101,
21 Wrap,
23 Constant([u8; 4]),
25}
26
27#[derive(Clone, Copy, Debug, PartialEq)]
29pub struct GpuGaussianBlurOptions {
30 pub kernel_width: u32,
32 pub kernel_height: u32,
34 pub sigma_x: f64,
36 pub sigma_y: f64,
38 pub border: GpuGaussianBorder,
40}
41
42impl Default for GpuGaussianBlurOptions {
43 fn default() -> Self {
44 Self {
45 kernel_width: 5,
46 kernel_height: 5,
47 sigma_x: 1.2,
48 sigma_y: 1.2,
49 border: GpuGaussianBorder::Reflect101,
50 }
51 }
52}
53
54#[repr(C)]
55#[derive(Clone, Copy, Pod, Zeroable)]
56struct Params {
57 width: u32,
58 height: u32,
59 pixels: u32,
60 groups: u32,
61 kernel_width: u32,
62 kernel_height: u32,
63 border: u32,
64 bits: u32,
65 channels: u32,
66 padding: [u32; 3],
67 weights_x: [[u32; 4]; 2],
68 weights_y: [[u32; 4]; 2],
69 constant: [u32; 4],
70}
71
72struct Plan {
73 params: Params,
74 scratch_bytes: u64,
75 packed: bool,
76}
77
78fn weights(size: u32, sigma: f64, bits: u32) -> [[u32; 4]; 2] {
81 let scale = 1u32 << bits;
82 let denominator = 2.0 * sigma * sigma;
83 let center = f64::from(size / 2);
84 let mut raw = [0.0; 7];
85 for i in 0..size {
86 let offset = f64::from(i) - center;
87 raw[i as usize] = (-(offset * offset) / denominator).exp();
88 }
89 let sum = raw[..size as usize].iter().sum::<f64>();
90 let mut fixed = [0i32; 8];
91 for i in 0..size {
92 fixed[i as usize] = (raw[i as usize] * f64::from(scale) / sum).round() as i32;
93 }
94 fixed[(size / 2) as usize] += scale as i32 - fixed.iter().sum::<i32>();
95 std::array::from_fn(|i| std::array::from_fn(|j| fixed[i * 4 + j] as u32))
96}
97
98fn plan(
99 width: u32,
100 height: u32,
101 channels: u32,
102 options: GpuGaussianBlurOptions,
103 limits: &wgpu::Limits,
104) -> SpatialResult<Plan> {
105 let invalid = || {
106 SpatialError::InvalidArgument(
107 "GPU Gaussian requires supported nonempty 1..=4-channel images, 3/5/7 kernels, finite positive sigmas and bounded scratch/compute limits".to_owned(),
108 )
109 };
110 let pixels = u64::from(width) * u64::from(height);
111 let components = pixels.checked_mul(u64::from(channels)).ok_or_else(invalid)?;
112 let scratch_bytes = components.checked_mul(4).ok_or_else(invalid)?;
113 if width == 0
114 || height == 0
115 || !(1..=4).contains(&channels)
116 || ![3, 5, 7].contains(&options.kernel_width)
117 || ![3, 5, 7].contains(&options.kernel_height)
118 || !options.sigma_x.is_finite()
119 || !options.sigma_y.is_finite()
120 || options.sigma_x <= 0.0
121 || options.sigma_y <= 0.0
122 || pixels > u64::from(u32::MAX)
123 || components > u64::from(u32::MAX)
124 || width > limits.max_texture_dimension_2d
125 || height > limits.max_texture_dimension_2d
126 || u64::from(width) * 2 + 3 > i32::MAX as u64
128 || u64::from(height) * 2 + 3 > i32::MAX as u64
129 || scratch_bytes > limits.max_buffer_size.min(u64::from(limits.max_storage_buffer_binding_size))
130 || limits.max_buffer_size < std::mem::size_of::<Params>() as u64
131 || limits.max_compute_invocations_per_workgroup < WORKGROUP
132 || limits.max_compute_workgroup_size_x < WORKGROUP
133 || limits.max_compute_workgroup_size_y == 0
134 || limits.max_compute_workgroup_size_z == 0
135 || limits.max_compute_workgroups_per_dimension == 0
136 || limits.max_bind_groups == 0
137 || limits.max_bindings_per_bind_group < 3
138 || limits.max_sampled_textures_per_shader_stage == 0
139 || limits.max_storage_textures_per_shader_stage == 0
140 || limits.max_storage_buffers_per_shader_stage == 0
141 || limits.max_uniform_buffers_per_shader_stage == 0
142 || limits.max_uniform_buffer_binding_size < std::mem::size_of::<Params>() as u32
143 {
144 return Err(invalid());
145 }
146 let bits = if options.kernel_width == 7 || options.kernel_height == 7 { 15 } else { 8 };
147 let (border, constant) = match options.border {
148 GpuGaussianBorder::Replicate => (0, [0; 4]),
149 GpuGaussianBorder::Reflect => (1, [0; 4]),
150 GpuGaussianBorder::Reflect101 => (2, [0; 4]),
151 GpuGaussianBorder::Wrap => (3, [0; 4]),
152 GpuGaussianBorder::Constant(pixel) => (4, pixel.map(u32::from)),
153 };
154 let packed = bits == 8 && channels >= 2;
156 let words_per_pixel = if packed { channels.div_ceil(2) } else { channels };
157 let scratch_bytes = pixels * u64::from(words_per_pixel) * 4;
158 Ok(Plan {
159 params: Params {
160 width,
161 height,
162 pixels: pixels as u32,
163 groups: (pixels as u32)
164 .div_ceil(WORKGROUP)
165 .min(4096)
166 .min(limits.max_compute_workgroups_per_dimension),
167 kernel_width: options.kernel_width,
168 kernel_height: options.kernel_height,
169 border,
170 bits,
171 channels,
172 padding: [if packed { words_per_pixel } else { 0 }, 0, 0],
173 weights_x: weights(options.kernel_width, options.sigma_x, bits),
174 weights_y: weights(options.kernel_height, options.sigma_y, bits),
175 constant,
176 },
177 scratch_bytes,
178 packed,
179 })
180}
181
182pub(crate) struct GaussianPipelines {
183 pipelines: std::sync::OnceLock<[wgpu::ComputePipeline; 2]>,
184 packed: std::sync::OnceLock<[wgpu::ComputePipeline; 2]>,
185 q15_pairs: std::sync::OnceLock<wgpu::ComputePipeline>,
186 q15_rows: std::sync::OnceLock<wgpu::ComputePipeline>,
187}
188
189impl GaussianPipelines {
190 fn new() -> Self {
191 Self {
192 pipelines: std::sync::OnceLock::new(),
193 packed: std::sync::OnceLock::new(),
194 q15_pairs: std::sync::OnceLock::new(),
195 q15_rows: std::sync::OnceLock::new(),
196 }
197 }
198
199 fn pipelines(&self, device: &wgpu::Device, packed: bool) -> &[wgpu::ComputePipeline; 2] {
200 let cache = if packed { &self.packed } else { &self.pipelines };
201 cache.get_or_init(|| {
202 let shaders = if packed {
203 [
204 concat!(
205 include_str!("gaussian_params.wgsl"),
206 include_str!("gaussian_packed_horizontal.wgsl")
207 ),
208 concat!(
209 include_str!("gaussian_params.wgsl"),
210 include_str!("gaussian_packed_vertical.wgsl")
211 ),
212 ]
213 } else {
214 [
215 concat!(
216 include_str!("gaussian_params.wgsl"),
217 include_str!("gaussian_horizontal.wgsl")
218 ),
219 concat!(
220 include_str!("gaussian_params.wgsl"),
221 include_str!("gaussian_vertical.wgsl")
222 ),
223 ]
224 };
225 shaders.map(|source| {
226 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
227 label: Some("gpu-gaussian-shader"),
228 source: wgpu::ShaderSource::Wgsl(source.into()),
229 });
230 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
231 label: Some("gpu-gaussian-pipeline"),
232 layout: None,
233 module: &shader,
234 entry_point: Some("main"),
235 compilation_options: Default::default(),
236 cache: None,
237 })
238 })
239 })
240 }
241
242 fn vertical_pipeline<'a>(
243 &'a self,
244 device: &wgpu::Device,
245 plan: &Plan,
246 standard: &'a wgpu::ComputePipeline,
247 ) -> &'a wgpu::ComputePipeline {
248 if plan.params.bits != 15 || plan.params.channels < 2 {
249 return standard;
250 }
251 let pairs = plan.params.channels == 2;
252 let cache = if pairs { &self.q15_pairs } else { &self.q15_rows };
253 cache.get_or_init(|| {
254 let source = if pairs {
255 concat!(
256 include_str!("gaussian_params.wgsl"),
257 include_str!("gaussian_q15_pairs.wgsl")
258 )
259 } else {
260 concat!(
261 include_str!("gaussian_params.wgsl"),
262 include_str!("gaussian_q15_rows.wgsl")
263 )
264 };
265 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
266 label: Some("gpu-gaussian-q15-shared-shader"),
267 source: wgpu::ShaderSource::Wgsl(source.into()),
268 });
269 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
270 label: Some("gpu-gaussian-q15-shared-pipeline"),
271 layout: None,
272 module: &shader,
273 entry_point: Some("main"),
274 compilation_options: Default::default(),
275 cache: None,
276 })
277 })
278 }
279}
280
281pub fn gaussian_blur_gpu(
291 runtime: &WgpuRuntime,
292 source: &GpuImage,
293 options: GpuGaussianBlurOptions,
294) -> SpatialResult<GpuImage> {
295 gaussian_impl(runtime, source, options, None)
296}
297
298pub fn gaussian_blur_gpu_profiled(
300 runtime: &WgpuRuntime,
301 source: &GpuImage,
302 options: GpuGaussianBlurOptions,
303 profiler: &mut GpuStageProfiler,
304) -> SpatialResult<GpuImage> {
305 let result = gaussian_impl(runtime, source, options, Some(profiler));
306 profiler.finish_recording(&result);
307 result
308}
309
310fn gaussian_impl(
311 runtime: &WgpuRuntime,
312 source: &GpuImage,
313 options: GpuGaussianBlurOptions,
314 mut profiler: Option<&mut GpuStageProfiler>,
315) -> SpatialResult<GpuImage> {
316 source.validate_runtime(runtime)?;
317 let p = plan(
318 source.width(),
319 source.height(),
320 source.channels(),
321 options,
322 &runtime.device().limits(),
323 )?;
324 if let Some(ref profiler) = profiler {
325 profiler.validate(runtime, 2)?;
326 }
327 let cache = runtime.image_gaussian_pipelines.get_or_init(GaussianPipelines::new);
328 let mut scratch = ScratchBuffers::new(runtime);
329 let sums = scratch.acquire("gpu-gaussian-horizontal", p.scratch_bytes);
330 let output = create_texture(runtime, source.width(), source.height(), "gpu-gaussian-output");
331 let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
332 label: Some("gpu-gaussian-params"),
333 contents: bytemuck::bytes_of(&p.params),
334 usage: wgpu::BufferUsages::UNIFORM,
335 });
336 let source_view = source.view();
337 let output_view = output.create_view(&Default::default());
338 let mut encoder = runtime.device().create_command_encoder(&Default::default());
339 let pipelines = cache.pipelines(runtime.device(), p.packed);
340 let vertical = cache.vertical_pipeline(runtime.device(), &p, &pipelines[1]);
341 for (index, pipeline) in [&pipelines[0], vertical].into_iter().enumerate() {
342 let stage = if index == 0 { "gaussian_horizontal_gpu" } else { "gaussian_blur_gpu" };
343 let image = if index == 0 { &source_view } else { &output_view };
344 let group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
345 label: Some(stage),
346 layout: &pipeline.get_bind_group_layout(0),
347 entries: &[
348 wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() },
349 wgpu::BindGroupEntry {
350 binding: 1,
351 resource: wgpu::BindingResource::TextureView(image),
352 },
353 wgpu::BindGroupEntry { binding: 2, resource: sums.as_entire_binding() },
354 ],
355 });
356 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
357 label: Some(stage),
358 timestamp_writes: crate::profiling::timestamp_writes(&mut profiler, stage),
359 });
360 pass.set_pipeline(pipeline);
361 pass.set_bind_group(0, &group, &[]);
362 pass.dispatch_workgroups(p.params.groups, 1, 1);
363 }
364 scratch.submit_and_recycle(encoder);
365 let mut receipt = source.receipt().clone();
366 receipt.record_gpu_to_gpu(p.scratch_bytes, "gaussian_horizontal_gpu");
367 receipt.record_gpu_to_gpu(u64::from(p.params.pixels) * 4, "gaussian_blur_gpu");
368 GpuImage::from_parts(
369 runtime,
370 source.width(),
371 source.height(),
372 source.channels(),
373 output,
374 source.metadata(),
375 receipt,
376 )
377}
378
379#[cfg(all(test, not(target_arch = "wasm32")))]
380#[path = "gaussian_tests.rs"]
381mod tests;