1use bytemuck::{Pod, Zeroable};
4use spatialrust_core::{SpatialError, SpatialResult};
5use wgpu::util::DeviceExt;
6
7use super::gpu_image::{create_texture, GpuImage};
8use crate::{scratch::ScratchBuffers, GpuStageProfiler, WgpuRuntime};
9
10const WORKGROUP: u32 = 256;
11const SHADER: &str = include_str!("canny.wgsl");
12const ENTRIES: [&str; 7] = [
13 "gradient_direct",
14 "gradient_horizontal",
15 "gradient_vertical",
16 "classify",
17 "connect",
18 "mark_roots",
19 "pack_edges",
20];
21const STAGES: [&str; 7] = [
22 "canny_gradients_gpu",
23 "canny_horizontal_gpu",
24 "canny_gradients_gpu",
25 "canny_classify_gpu",
26 "canny_connect_gpu",
27 "canny_roots_gpu",
28 "canny_gpu",
29];
30
31#[derive(Clone, Copy, Debug, PartialEq)]
33pub struct GpuCannyOptions {
34 pub low_threshold: f64,
36 pub high_threshold: f64,
38 pub aperture_size: u32,
40 pub l2_gradient: bool,
42}
43
44impl Default for GpuCannyOptions {
45 fn default() -> Self {
46 Self { low_threshold: 100.0, high_threshold: 200.0, aperture_size: 3, l2_gradient: false }
47 }
48}
49
50#[repr(C)]
51#[derive(Clone, Copy, Pod, Zeroable)]
52struct Params {
53 width: u32,
54 height: u32,
55 pixels: u32,
56 groups: u32,
57 aperture: u32,
58 l2: u32,
59 low: u32,
60 high: u32,
61 smooth: [[i32; 4]; 2],
62 derivative: [[i32; 4]; 2],
63}
64
65struct Plan {
66 params: Params,
67 gradient_bytes: u64,
68 pixel_bytes: u64,
69 horizontal_bytes: u64,
70}
71
72fn thresholds(options: GpuCannyOptions) -> (u32, u32) {
73 let (mut low, mut high) = (options.low_threshold, options.high_threshold);
74 if options.aperture_size == 7 {
75 low /= 16.0;
76 high /= 16.0;
77 }
78 if low > high {
79 std::mem::swap(&mut low, &mut high);
80 }
81 let convert = |value: f64| {
82 let value = if options.l2_gradient {
83 let value = value.min(32767.0);
84 value.mul_add(value, 0.0)
85 } else {
86 value
87 };
88 value.floor().min(f64::from(u32::MAX)) as u32
91 };
92 (convert(low), convert(high))
93}
94
95fn plan(
96 width: u32,
97 height: u32,
98 channels: u32,
99 options: GpuCannyOptions,
100 limits: &wgpu::Limits,
101) -> SpatialResult<Plan> {
102 let invalid = || {
103 SpatialError::InvalidArgument("GPU Canny requires a supported nonempty grayscale image, 3/5/7 aperture, finite nonnegative thresholds and bounded buffer/binding/compute limits".to_owned())
104 };
105 let pixels = u64::from(width) * u64::from(height);
106 let gradient_bytes = pixels.checked_mul(8).ok_or_else(invalid)?;
108 let pixel_bytes = pixels.checked_mul(4).ok_or_else(invalid)?;
109 let horizontal_bytes = if options.aperture_size == 3 { 0 } else { pixel_bytes };
112 let bound = limits.max_buffer_size.min(u64::from(limits.max_storage_buffer_binding_size));
113 if width == 0
114 || height == 0
115 || channels != 1
116 || ![3, 5, 7].contains(&options.aperture_size)
117 || !options.low_threshold.is_finite()
118 || !options.high_threshold.is_finite()
119 || options.low_threshold < 0.0
120 || options.high_threshold < 0.0
121 || pixels > u64::from(u32::MAX)
122 || width > limits.max_texture_dimension_2d
123 || height > limits.max_texture_dimension_2d
124 || u64::from(width) + 3 > i32::MAX as u64
125 || u64::from(height) + 3 > i32::MAX as u64
126 || gradient_bytes > bound
127 || horizontal_bytes > bound
128 || pixel_bytes > bound
129 || limits.max_buffer_size < std::mem::size_of::<Params>() as u64
130 || limits.max_uniform_buffer_binding_size < std::mem::size_of::<Params>() as u32
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 < 8
138 || limits.max_storage_buffers_per_shader_stage < 3
139 || limits.max_uniform_buffers_per_shader_stage == 0
140 || limits.max_sampled_textures_per_shader_stage == 0
141 || limits.max_storage_textures_per_shader_stage == 0
142 {
143 return Err(invalid());
144 }
145 let (smooth, derivative) = match options.aperture_size {
146 3 => ([1, 2, 1, 0, 0, 0, 0, 0], [-1, 0, 1, 0, 0, 0, 0, 0]),
147 5 => ([1, 4, 6, 4, 1, 0, 0, 0], [-1, -2, 0, 2, 1, 0, 0, 0]),
148 _ => ([1, 6, 15, 20, 15, 6, 1, 0], [-1, -4, -5, 0, 5, 4, 1, 0]),
149 };
150 let vectors = |v: [i32; 8]| std::array::from_fn(|i| std::array::from_fn(|j| v[4 * i + j]));
151 let (low, high) = thresholds(options);
152 Ok(Plan {
153 params: Params {
154 width,
155 height,
156 pixels: pixels as u32,
157 groups: (pixels as u32)
158 .div_ceil(WORKGROUP)
159 .min(4096)
160 .min(limits.max_compute_workgroups_per_dimension),
161 aperture: options.aperture_size,
162 l2: u32::from(options.l2_gradient),
163 low,
164 high,
165 smooth: vectors(smooth),
166 derivative: vectors(derivative),
167 },
168 gradient_bytes,
169 pixel_bytes,
170 horizontal_bytes,
171 })
172}
173
174pub(crate) struct CannyPipelines {
175 layout: wgpu::BindGroupLayout,
176 pipelines: [wgpu::ComputePipeline; 7],
177}
178
179impl CannyPipelines {
180 fn new(device: &wgpu::Device) -> Self {
181 let layout = binding_layout(device, false, false);
182 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
183 label: Some("canny-pipeline-layout"),
184 bind_group_layouts: &[&layout],
185 push_constant_ranges: &[],
186 });
187 let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
188 label: Some("canny-shader"),
189 source: wgpu::ShaderSource::Wgsl(SHADER.into()),
190 });
191 let pipelines = ENTRIES.map(|entry| {
192 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
193 label: Some(entry),
194 layout: Some(&pipeline_layout),
195 module: &module,
196 entry_point: Some(entry),
197 compilation_options: Default::default(),
198 cache: None,
199 })
200 });
201 Self { layout, pipelines }
202 }
203}
204
205fn binding_layout(
207 device: &wgpu::Device,
208 separate_horizontal: bool,
209 separate_strong: bool,
210) -> wgpu::BindGroupLayout {
211 let entries: Vec<_> = (0..8)
212 .filter(|&binding| {
213 (separate_horizontal || binding != 3) && (separate_strong || binding != 6)
214 })
215 .map(|binding| {
216 let ty = match binding {
217 0 => wgpu::BindingType::Buffer {
218 ty: wgpu::BufferBindingType::Uniform,
219 has_dynamic_offset: false,
220 min_binding_size: None,
221 },
222 1 => wgpu::BindingType::Texture {
223 sample_type: wgpu::TextureSampleType::Uint,
224 view_dimension: wgpu::TextureViewDimension::D2,
225 multisampled: false,
226 },
227 7 => wgpu::BindingType::StorageTexture {
228 access: wgpu::StorageTextureAccess::WriteOnly,
229 format: wgpu::TextureFormat::Rgba8Uint,
230 view_dimension: wgpu::TextureViewDimension::D2,
231 },
232 _ => wgpu::BindingType::Buffer {
233 ty: wgpu::BufferBindingType::Storage { read_only: false },
234 has_dynamic_offset: false,
235 min_binding_size: None,
236 },
237 };
238 wgpu::BindGroupLayoutEntry {
239 binding,
240 visibility: wgpu::ShaderStages::COMPUTE,
241 ty,
242 count: None,
243 }
244 })
245 .collect();
246 device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
247 label: Some("canny-layout"),
248 entries: &entries,
249 })
250}
251
252struct Work {
253 gradients: wgpu::Buffer,
254 states: wgpu::Buffer,
255 parent: wgpu::Buffer,
256}
257
258impl Work {
259 fn acquire(scratch: &mut ScratchBuffers<'_>, p: &Plan) -> Self {
260 Self {
261 gradients: scratch.acquire("canny-gradients", p.gradient_bytes),
262 states: scratch.acquire("canny-states", p.pixel_bytes),
263 parent: scratch.acquire("canny-parents", p.pixel_bytes),
264 }
265 }
266
267 fn bind(
268 &self,
269 runtime: &WgpuRuntime,
270 cache: &CannyPipelines,
271 uniform: &wgpu::Buffer,
272 source: &wgpu::TextureView,
273 output: &wgpu::TextureView,
274 ) -> wgpu::BindGroup {
275 let buffers = [(2, &self.gradients), (4, &self.states), (5, &self.parent)];
276 let mut entries = vec![
277 wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() },
278 wgpu::BindGroupEntry {
279 binding: 1,
280 resource: wgpu::BindingResource::TextureView(source),
281 },
282 ];
283 entries.extend(buffers.iter().map(|&(binding, b)| wgpu::BindGroupEntry {
284 binding,
285 resource: b.as_entire_binding(),
286 }));
287 entries.push(wgpu::BindGroupEntry {
288 binding: 7,
289 resource: wgpu::BindingResource::TextureView(output),
290 });
291 runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
292 label: Some("canny-bindings"),
293 layout: &cache.layout,
294 entries: &entries,
295 })
296 }
297}
298
299fn pass_indices(aperture: u32) -> &'static [usize] {
300 if aperture == 3 {
301 &[0, 3, 4, 5, 6]
302 } else {
303 &[1, 2, 3, 4, 5, 6]
304 }
305}
306
307fn encode(
308 cache: &CannyPipelines,
309 group: &wgpu::BindGroup,
310 groups: u32,
311 indices: &[usize],
312 encoder: &mut wgpu::CommandEncoder,
313 mut profiler: Option<&mut GpuStageProfiler>,
314) {
315 for &index in indices {
316 let stage = STAGES[index];
317 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
318 label: Some(stage),
319 timestamp_writes: crate::profiling::timestamp_writes(&mut profiler, stage),
320 });
321 pass.set_pipeline(&cache.pipelines[index]);
322 pass.set_bind_group(0, group, &[]);
323 pass.dispatch_workgroups(groups, 1, 1);
324 }
325}
326
327pub fn canny_gpu(
338 runtime: &WgpuRuntime,
339 source: &GpuImage,
340 options: GpuCannyOptions,
341) -> SpatialResult<GpuImage> {
342 canny_impl(runtime, source, options, None)
343}
344
345pub fn canny_gpu_profiled(
347 runtime: &WgpuRuntime,
348 source: &GpuImage,
349 options: GpuCannyOptions,
350 profiler: &mut GpuStageProfiler,
351) -> SpatialResult<GpuImage> {
352 let result = canny_impl(runtime, source, options, Some(profiler));
353 profiler.finish_recording(&result);
354 result
355}
356
357fn canny_impl(
358 runtime: &WgpuRuntime,
359 source: &GpuImage,
360 options: GpuCannyOptions,
361 profiler: Option<&mut GpuStageProfiler>,
362) -> SpatialResult<GpuImage> {
363 source.validate_runtime(runtime)?;
364 let p = plan(
365 source.width(),
366 source.height(),
367 source.channels(),
368 options,
369 &runtime.device().limits(),
370 )?;
371 let indices = pass_indices(options.aperture_size);
372 if let Some(ref profiler) = profiler {
373 profiler.validate(runtime, indices.len() as u32)?;
374 }
375 let cache = runtime.image_canny_pipelines.get_or_init(|| CannyPipelines::new(runtime.device()));
376 let mut scratch = ScratchBuffers::new(runtime);
377 let work = Work::acquire(&mut scratch, &p);
378 let output = create_texture(runtime, source.width(), source.height(), "canny-output");
379 let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
380 label: Some("canny-params"),
381 contents: bytemuck::bytes_of(&p.params),
382 usage: wgpu::BufferUsages::UNIFORM,
383 });
384 let group = work.bind(
385 runtime,
386 cache,
387 &uniform,
388 &source.view(),
389 &output.create_view(&Default::default()),
390 );
391 let mut encoder = runtime.device().create_command_encoder(&Default::default());
392 encode(cache, &group, p.params.groups, indices, &mut encoder, profiler);
393 scratch.submit_and_recycle(encoder);
394 let mut receipt = source.receipt().clone();
395 for &index in indices {
397 let bytes = match index {
398 0 | 2 => p.gradient_bytes,
399 1 => p.horizontal_bytes,
400 3 => 2 * p.pixel_bytes,
401 5 => 2 * p.pixel_bytes,
402 _ => p.pixel_bytes,
403 };
404 receipt.record_gpu_to_gpu(bytes, STAGES[index]);
405 }
406 GpuImage::from_parts(
407 runtime,
408 source.width(),
409 source.height(),
410 1,
411 output,
412 source.metadata(),
413 receipt,
414 )
415}
416
417#[cfg(all(test, not(target_arch = "wasm32")))]
418#[path = "canny_tests.rs"]
419mod tests;