1use bytemuck::{Pod, Zeroable};
4use spatialrust_core::{SpatialError, SpatialResult};
5use std::sync::OnceLock;
6use wgpu::util::DeviceExt;
7
8use crate::image::gpu_image::{create_texture, GpuImage, GpuImageReceipt};
9use crate::WgpuRuntime;
10
11const WORKGROUP_X: u32 = 16;
12const WORKGROUP_Y: u32 = 16;
13const SEPARABLE_MIN_AREA: u64 = 81;
14const SEPARABLE_MIN_SAMPLES: u64 = 1_048_576;
15fn validate_spatial_dispatch(
16 source: [u32; 2],
17 output: [u32; 2],
18 limits: &wgpu::Limits,
19) -> SpatialResult<()> {
20 if source
21 .into_iter()
22 .chain(output)
23 .any(|v| v == 0 || v > limits.max_texture_dimension_2d || v > i32::MAX as u32)
24 || limits.max_compute_invocations_per_workgroup < WORKGROUP_X * WORKGROUP_Y
25 || limits.max_compute_workgroup_size_x < WORKGROUP_X
26 || limits.max_compute_workgroup_size_y < WORKGROUP_Y
27 || limits.max_compute_workgroup_size_z == 0
28 || output[0].div_ceil(WORKGROUP_X) > limits.max_compute_workgroups_per_dimension
29 || output[1].div_ceil(WORKGROUP_Y) > limits.max_compute_workgroups_per_dimension
30 || limits.max_sampled_textures_per_shader_stage == 0
31 || limits.max_storage_textures_per_shader_stage == 0
32 || limits.max_uniform_buffers_per_shader_stage == 0
33 || limits.max_uniform_buffer_binding_size < std::mem::size_of::<SpatialParams>() as u32
34 || limits.max_buffer_size < std::mem::size_of::<SpatialParams>() as u64
35 || limits.max_bind_groups == 0
36 || limits.max_bindings_per_bind_group < 3
37 {
38 return Err(SpatialError::InvalidArgument(
39 "GPU spatial dispatch requires positive dimensions and supported texture/compute/coordinate limits"
40 .to_owned(),
41 ));
42 }
43 Ok(())
44}
45
46pub(in crate::image) fn validate_resize_dispatch(
47 source: [u32; 2],
48 output: [u32; 2],
49 limits: &wgpu::Limits,
50) -> SpatialResult<()> {
51 validate_spatial_dispatch(source, output, limits)?;
52 if source
54 .into_iter()
55 .zip(output)
56 .any(|(s, o)| u64::from(o - 1) * u64::from(s) > u64::from(u32::MAX))
57 {
58 return Err(SpatialError::InvalidArgument(
59 "GPU nearest resize coordinate product exceeds u32::MAX".to_owned(),
60 ));
61 }
62 Ok(())
63}
64
65pub(crate) fn morphology_pass_count(width: u32, height: u32, kw: u32, kh: u32) -> u32 {
66 let area = u64::from(kw) * u64::from(kh);
67 let count = u64::from(width) * u64::from(height);
68 1 + u32::from(area >= SEPARABLE_MIN_AREA && count >= SEPARABLE_MIN_SAMPLES.div_ceil(area))
70}
71
72struct MorphologyPlan {
73 params: SpatialParams,
74 separable: bool,
75 bytes: u64,
76 packed: bool,
77 scratch_width: u32,
78 scratch_bytes: u64,
79}
80
81fn morphology_plan(
82 width: u32,
83 height: u32,
84 kw: u32,
85 kh: u32,
86 operation: GpuMorphology,
87 limits: &wgpu::Limits,
88) -> SpatialResult<MorphologyPlan> {
89 let invalid = || {
90 SpatialError::InvalidArgument(
91 "GPU morphology requires odd kernels in 1..=31 and supported texture/compute/coordinate limits".to_owned())
92 };
93 let count = u64::from(width) * u64::from(height);
94 let bytes = count.checked_mul(4).ok_or_else(invalid)?;
95 if width == 0
96 || height == 0
97 || kw == 0
98 || kh == 0
99 || kw % 2 == 0
100 || kh % 2 == 0
101 || kw > 31
102 || kh > 31
103 || width > limits.max_texture_dimension_2d
104 || height > limits.max_texture_dimension_2d
105 || width > i32::MAX as u32
106 || height > i32::MAX as u32
107 || u64::from(width - 1) + u64::from(kw / 2) > i32::MAX as u64
108 || u64::from(height - 1) + u64::from(kh / 2) > i32::MAX as u64
109 || limits.max_compute_invocations_per_workgroup < WORKGROUP_X * WORKGROUP_Y
110 || limits.max_compute_workgroup_size_x < WORKGROUP_X
111 || limits.max_compute_workgroup_size_y < WORKGROUP_Y
112 || limits.max_compute_workgroup_size_z == 0
113 || width.div_ceil(WORKGROUP_X) > limits.max_compute_workgroups_per_dimension
114 || height.div_ceil(WORKGROUP_Y) > limits.max_compute_workgroups_per_dimension
115 || limits.max_sampled_textures_per_shader_stage == 0
116 || limits.max_storage_textures_per_shader_stage == 0
117 || limits.max_uniform_buffers_per_shader_stage == 0
118 || limits.max_uniform_buffer_binding_size < std::mem::size_of::<SpatialParams>() as u32
119 || limits.max_buffer_size < std::mem::size_of::<SpatialParams>() as u64
120 || limits.max_bind_groups == 0
121 || limits.max_bindings_per_bind_group < 3
122 {
123 return Err(invalid());
124 }
125 let separable = morphology_pass_count(width, height, kw, kh) == 2;
126 let packed = separable && width > 1;
128 let scratch_width = if packed { width.div_ceil(4) } else { width };
129 let scratch_bytes = u64::from(scratch_width) * u64::from(height) * 4;
130 Ok(MorphologyPlan {
131 params: SpatialParams {
132 source_width: width,
133 source_height: height,
134 output_width: width,
135 output_height: height,
136 kernel_width: kw,
137 kernel_height: kh,
138 operation: u32::from(operation == GpuMorphology::Dilate),
139 _pad: 0,
140 },
141 separable,
142 bytes,
143 packed,
144 scratch_width,
145 scratch_bytes,
146 })
147}
148
149#[derive(Clone, Copy, Debug, PartialEq, Eq)]
151pub enum GpuMorphology {
152 Erode,
154 Dilate,
156}
157
158#[repr(C)]
159#[derive(Clone, Copy, Pod, Zeroable)]
160struct SpatialParams {
161 source_width: u32,
162 source_height: u32,
163 output_width: u32,
164 output_height: u32,
165 kernel_width: u32,
166 kernel_height: u32,
167 operation: u32,
168 _pad: u32,
169}
170
171const SPATIAL_WGSL: &str = r#"
172struct Params {
173 source_width: u32,
174 source_height: u32,
175 output_width: u32,
176 output_height: u32,
177 kernel_width: u32,
178 kernel_height: u32,
179 operation: u32,
180 pad: u32,
181};
182
183@group(0) @binding(0) var<uniform> params: Params;
184@group(0) @binding(1) var input_px: texture_2d<u32>;
185@group(0) @binding(2) var output_px: texture_storage_2d<rgba8uint, write>;
186
187fn in_output(gid: vec3<u32>) -> bool {
188 return gid.x < params.output_width && gid.y < params.output_height;
189}
190
191fn gray_at(x: i32, y: i32) -> i32 {
192 let sx = clamp(x, 0, i32(params.source_width) - 1);
193 let sy = clamp(y, 0, i32(params.source_height) - 1);
194 return i32(textureLoad(input_px, vec2<i32>(sx, sy), 0).r);
195}
196
197@compute @workgroup_size(16, 16)
198fn resize_nearest(@builtin(global_invocation_id) gid: vec3<u32>) {
199 if (!in_output(gid)) { return; }
200 let sx = min((gid.x * params.source_width) / params.output_width, params.source_width - 1u);
201 let sy = min((gid.y * params.source_height) / params.output_height, params.source_height - 1u);
202 textureStore(output_px, vec2<i32>(gid.xy), textureLoad(input_px, vec2<i32>(i32(sx), i32(sy)), 0));
203}
204
205@compute @workgroup_size(16, 16)
206fn sobel(@builtin(global_invocation_id) gid: vec3<u32>) {
207 if (!in_output(gid)) { return; }
208 let x = i32(gid.x);
209 let y = i32(gid.y);
210 let gx = -gray_at(x - 1, y - 1) + gray_at(x + 1, y - 1)
211 - 2 * gray_at(x - 1, y) + 2 * gray_at(x + 1, y)
212 - gray_at(x - 1, y + 1) + gray_at(x + 1, y + 1);
213 let gy = -gray_at(x - 1, y - 1) - 2 * gray_at(x, y - 1) - gray_at(x + 1, y - 1)
214 + gray_at(x - 1, y + 1) + 2 * gray_at(x, y + 1) + gray_at(x + 1, y + 1);
215 let magnitude = u32(clamp(abs(gx) + abs(gy), 0, 255));
216 textureStore(output_px, vec2<i32>(x, y), vec4<u32>(magnitude, 0u, 0u, 0u));
217}
218
219@compute @workgroup_size(16, 16)
220fn morphology(@builtin(global_invocation_id) gid: vec3<u32>) {
221 if (!in_output(gid)) { return; }
222 let x = i32(gid.x);
223 let y = i32(gid.y);
224 let rx = i32(params.kernel_width / 2u);
225 let ry = i32(params.kernel_height / 2u);
226 var value = select(255, 0, params.operation == 1u);
227 for (var dy = -ry; dy <= ry; dy = dy + 1) {
228 for (var dx = -rx; dx <= rx; dx = dx + 1) {
229 let sample = gray_at(x + dx, y + dy);
230 if (params.operation == 0u) { value = min(value, sample); }
231 else { value = max(value, sample); }
232 }
233 }
234 textureStore(output_px, vec2<i32>(x, y), vec4<u32>(u32(value), 0u, 0u, 0u));
235}
236"#;
237
238pub(crate) struct SpatialPipelines {
239 layout: wgpu::BindGroupLayout,
240 resize: wgpu::ComputePipeline,
241 sobel: wgpu::ComputePipeline,
242 morphology: wgpu::ComputePipeline,
243 separable_morphology: OnceLock<[wgpu::ComputePipeline; 2]>,
244 packed_morphology: OnceLock<[wgpu::ComputePipeline; 2]>,
245}
246
247impl SpatialPipelines {
248 fn packed_morphology(&self, device: &wgpu::Device) -> &[wgpu::ComputePipeline; 2] {
249 self.packed_morphology.get_or_init(|| {
250 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
251 label: Some("gpu-morphology-packed-shader"),
252 source: wgpu::ShaderSource::Wgsl(include_str!("morphology_packed.wgsl").into()),
253 });
254 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
255 label: Some("gpu-morphology-packed-pl"),
256 bind_group_layouts: &[&self.layout],
257 push_constant_ranges: &[],
258 });
259 ["horizontal", "vertical"].map(|entry| {
260 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
261 label: Some(entry),
262 layout: Some(&layout),
263 module: &shader,
264 entry_point: Some(entry),
265 compilation_options: Default::default(),
266 cache: None,
267 })
268 })
269 })
270 }
271
272 fn separable_morphology(&self, device: &wgpu::Device) -> &[wgpu::ComputePipeline; 2] {
273 self.separable_morphology.get_or_init(|| {
274 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
275 label: Some("gpu-morphology-separable-shader"),
276 source: wgpu::ShaderSource::Wgsl(include_str!("morphology_separable.wgsl").into()),
277 });
278 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
279 label: Some("gpu-morphology-separable-pl"),
280 bind_group_layouts: &[&self.layout],
281 push_constant_ranges: &[],
282 });
283 ["horizontal", "vertical"].map(|entry| {
284 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
285 label: Some(entry),
286 layout: Some(&layout),
287 module: &shader,
288 entry_point: Some(entry),
289 compilation_options: Default::default(),
290 cache: None,
291 })
292 })
293 })
294 }
295}
296
297pub(crate) fn create_spatial_pipelines(device: &wgpu::Device) -> SpatialPipelines {
298 let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
299 label: Some("gpu-image-spatial-bgl"),
300 entries: &[
301 wgpu::BindGroupLayoutEntry {
302 binding: 0,
303 visibility: wgpu::ShaderStages::COMPUTE,
304 ty: wgpu::BindingType::Buffer {
305 ty: wgpu::BufferBindingType::Uniform,
306 has_dynamic_offset: false,
307 min_binding_size: None,
308 },
309 count: None,
310 },
311 wgpu::BindGroupLayoutEntry {
312 binding: 1,
313 visibility: wgpu::ShaderStages::COMPUTE,
314 ty: wgpu::BindingType::Texture {
315 sample_type: wgpu::TextureSampleType::Uint,
316 view_dimension: wgpu::TextureViewDimension::D2,
317 multisampled: false,
318 },
319 count: None,
320 },
321 wgpu::BindGroupLayoutEntry {
322 binding: 2,
323 visibility: wgpu::ShaderStages::COMPUTE,
324 ty: wgpu::BindingType::StorageTexture {
325 access: wgpu::StorageTextureAccess::WriteOnly,
326 format: wgpu::TextureFormat::Rgba8Uint,
327 view_dimension: wgpu::TextureViewDimension::D2,
328 },
329 count: None,
330 },
331 ],
332 });
333 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
334 label: Some("gpu-image-spatial-shader"),
335 source: wgpu::ShaderSource::Wgsl(SPATIAL_WGSL.into()),
336 });
337 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
338 label: Some("gpu-image-spatial-pl"),
339 bind_group_layouts: &[&layout],
340 push_constant_ranges: &[],
341 });
342 let create = |entry_point| {
343 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
344 label: Some(entry_point),
345 layout: Some(&pipeline_layout),
346 module: &shader,
347 entry_point: Some(entry_point),
348 compilation_options: wgpu::PipelineCompilationOptions::default(),
349 cache: None,
350 })
351 };
352 SpatialPipelines {
353 layout,
354 resize: create("resize_nearest"),
355 sobel: create("sobel"),
356 morphology: create("morphology"),
357 separable_morphology: OnceLock::new(),
358 packed_morphology: OnceLock::new(),
359 }
360}
361
362pub fn resize_nearest_gpu(
367 runtime: &WgpuRuntime,
368 source: &GpuImage,
369 width: u32,
370 height: u32,
371) -> SpatialResult<GpuImage> {
372 resize_nearest_gpu_with_profiler(runtime, source, width, height, None)
373}
374
375pub(crate) fn resize_nearest_gpu_with_profiler(
376 runtime: &WgpuRuntime,
377 source: &GpuImage,
378 width: u32,
379 height: u32,
380 profiler: Option<&mut crate::GpuStageProfiler>,
381) -> SpatialResult<GpuImage> {
382 source.validate_runtime(runtime)?;
383 validate_resize_dispatch(
384 [source.width(), source.height()],
385 [width, height],
386 &runtime.device().limits(),
387 )?;
388 if let Some(profiler) = &profiler {
389 profiler.validate(runtime, 1)?;
390 }
391 dispatch(
392 runtime,
393 source,
394 width,
395 height,
396 1,
397 1,
398 0,
399 &runtime
400 .image_spatial_pipelines
401 .get_or_init(|| create_spatial_pipelines(runtime.device()))
402 .resize,
403 "resize_nearest_gpu",
404 source.channels(),
405 profiler,
406 )
407}
408
409pub fn sobel_gpu(runtime: &WgpuRuntime, source: &GpuImage) -> SpatialResult<GpuImage> {
414 sobel_gpu_with_profiler(runtime, source, None)
415}
416
417pub(crate) fn sobel_gpu_with_profiler(
418 runtime: &WgpuRuntime,
419 source: &GpuImage,
420 profiler: Option<&mut crate::GpuStageProfiler>,
421) -> SpatialResult<GpuImage> {
422 require_gray(source, "sobel_gpu")?;
423 source.validate_runtime(runtime)?;
424 validate_spatial_dispatch(
425 [source.width(), source.height()],
426 [source.width(), source.height()],
427 &runtime.device().limits(),
428 )?;
429 if let Some(profiler) = &profiler {
430 profiler.validate(runtime, 1)?;
431 }
432 let cache =
433 runtime.image_spatial_pipelines.get_or_init(|| create_spatial_pipelines(runtime.device()));
434 dispatch(
435 runtime,
436 source,
437 source.width(),
438 source.height(),
439 3,
440 3,
441 0,
442 &cache.sobel,
443 "sobel_gpu",
444 1,
445 profiler,
446 )
447}
448
449pub fn morphology_gpu(
456 runtime: &WgpuRuntime,
457 source: &GpuImage,
458 kernel_width: u32,
459 kernel_height: u32,
460 operation: GpuMorphology,
461) -> SpatialResult<GpuImage> {
462 morphology_gpu_with_profiler(runtime, source, kernel_width, kernel_height, operation, None)
463}
464
465pub(crate) fn morphology_gpu_with_profiler(
466 runtime: &WgpuRuntime,
467 source: &GpuImage,
468 kernel_width: u32,
469 kernel_height: u32,
470 operation: GpuMorphology,
471 profiler: Option<&mut crate::GpuStageProfiler>,
472) -> SpatialResult<GpuImage> {
473 require_gray(source, "morphology_gpu")?;
474 source.validate_runtime(runtime)?;
475 let p = morphology_plan(
476 source.width(),
477 source.height(),
478 kernel_width,
479 kernel_height,
480 operation,
481 &runtime.device().limits(),
482 )?;
483 let cache =
484 runtime.image_spatial_pipelines.get_or_init(|| create_spatial_pipelines(runtime.device()));
485 let output = create_texture(runtime, source.width(), source.height(), "gpu-morphology-out");
486 let intermediate = p.separable.then(|| {
487 create_texture(runtime, p.scratch_width, source.height(), "gpu-morphology-horizontal")
488 });
489 let intermediate_view = intermediate.as_ref().map(|t| t.create_view(&Default::default()));
490 let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
491 label: Some("gpu-morphology-params"),
492 contents: bytemuck::bytes_of(&p.params),
493 usage: wgpu::BufferUsages::UNIFORM,
494 });
495 let mut encoder = runtime.device().create_command_encoder(&Default::default());
496 encode_morphology(
497 runtime,
498 cache,
499 &p,
500 &source.view(),
501 &output.create_view(&Default::default()),
502 intermediate_view.as_ref(),
503 &uniform,
504 &mut encoder,
505 profiler,
506 );
507 runtime.queue().submit(Some(encoder.finish()));
508 if let Some(texture) = intermediate {
511 runtime.recycle_image_texture(p.scratch_width, source.height(), texture);
512 }
513 let mut receipt = source.receipt().clone();
514 if p.separable {
515 receipt.record_gpu_to_gpu(p.scratch_bytes, "morphology_horizontal_gpu");
516 }
517 receipt.record_gpu_to_gpu(p.bytes, "morphology_gpu");
518 GpuImage::from_parts(
519 runtime,
520 source.width(),
521 source.height(),
522 1,
523 output,
524 source.metadata(),
525 receipt,
526 )
527}
528
529#[allow(clippy::too_many_arguments)]
530fn encode_morphology(
531 runtime: &WgpuRuntime,
532 cache: &SpatialPipelines,
533 p: &MorphologyPlan,
534 source: &wgpu::TextureView,
535 output: &wgpu::TextureView,
536 intermediate: Option<&wgpu::TextureView>,
537 uniform: &wgpu::Buffer,
538 encoder: &mut wgpu::CommandEncoder,
539 mut profiler: Option<&mut crate::GpuStageProfiler>,
540) {
541 let pipelines = p.separable.then(|| {
542 if p.packed {
543 cache.packed_morphology(runtime.device())
544 } else {
545 cache.separable_morphology(runtime.device())
546 }
547 });
548 for index in 0..if p.separable { 2 } else { 1 } {
549 let pipeline = pipelines.map_or(&cache.morphology, |pipelines| &pipelines[index]);
550 let input = if p.separable && index == 1 { intermediate.unwrap() } else { source };
551 let target = if p.separable && index == 0 { intermediate.unwrap() } else { output };
552 let stage =
553 if p.separable && index == 0 { "morphology_horizontal_gpu" } else { "morphology_gpu" };
554 let group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
555 label: Some(stage),
556 layout: &cache.layout,
557 entries: &[
558 wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() },
559 wgpu::BindGroupEntry {
560 binding: 1,
561 resource: wgpu::BindingResource::TextureView(input),
562 },
563 wgpu::BindGroupEntry {
564 binding: 2,
565 resource: wgpu::BindingResource::TextureView(target),
566 },
567 ],
568 });
569 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
570 label: Some(stage),
571 timestamp_writes: crate::profiling::timestamp_writes(&mut profiler, stage),
572 });
573 pass.set_pipeline(pipeline);
574 pass.set_bind_group(0, &group, &[]);
575 pass.dispatch_workgroups(
576 (if p.separable && p.packed && index == 0 {
577 p.scratch_width
578 } else {
579 p.params.output_width
580 })
581 .div_ceil(WORKGROUP_X),
582 p.params.output_height.div_ceil(WORKGROUP_Y),
583 1,
584 );
585 }
586}
587
588#[allow(clippy::too_many_arguments)]
589fn dispatch(
590 runtime: &WgpuRuntime,
591 source: &GpuImage,
592 output_width: u32,
593 output_height: u32,
594 kernel_width: u32,
595 kernel_height: u32,
596 operation: u32,
597 pipeline: &wgpu::ComputePipeline,
598 stage: &'static str,
599 output_channels: u32,
600 mut profiler: Option<&mut crate::GpuStageProfiler>,
601) -> SpatialResult<GpuImage> {
602 source.validate_runtime(runtime)?;
603 let output = create_texture(runtime, output_width, output_height, stage);
604 let params = SpatialParams {
605 source_width: source.width(),
606 source_height: source.height(),
607 output_width,
608 output_height,
609 kernel_width,
610 kernel_height,
611 operation,
612 _pad: 0,
613 };
614 let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
615 label: Some("gpu-image-spatial-params"),
616 contents: bytemuck::bytes_of(¶ms),
617 usage: wgpu::BufferUsages::UNIFORM,
618 });
619 let source_view = source.view();
620 let output_view = output.create_view(&wgpu::TextureViewDescriptor::default());
621 let bind_group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
622 label: Some("gpu-image-spatial-bg"),
623 layout: &runtime
624 .image_spatial_pipelines
625 .get_or_init(|| create_spatial_pipelines(runtime.device()))
626 .layout,
627 entries: &[
628 wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() },
629 wgpu::BindGroupEntry {
630 binding: 1,
631 resource: wgpu::BindingResource::TextureView(&source_view),
632 },
633 wgpu::BindGroupEntry {
634 binding: 2,
635 resource: wgpu::BindingResource::TextureView(&output_view),
636 },
637 ],
638 });
639 let mut encoder = runtime.device().create_command_encoder(&wgpu::CommandEncoderDescriptor {
640 label: Some("gpu-image-spatial-encoder"),
641 });
642 {
643 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
644 label: Some(stage),
645 timestamp_writes: crate::profiling::timestamp_writes(&mut profiler, stage),
646 });
647 pass.set_pipeline(pipeline);
648 pass.set_bind_group(0, &bind_group, &[]);
649 pass.dispatch_workgroups(
650 output_width.div_ceil(WORKGROUP_X),
651 output_height.div_ceil(WORKGROUP_Y),
652 1,
653 );
654 }
655 runtime.queue().submit(Some(encoder.finish()));
656 let output_bytes = u64::from(output_width) * u64::from(output_height) * 4;
657 let mut receipt = GpuImageReceipt::default();
658 receipt.merge_from(source.receipt());
659 receipt.record_gpu_to_gpu(output_bytes, stage);
660 GpuImage::from_parts(
661 runtime,
662 output_width,
663 output_height,
664 output_channels,
665 output,
666 source.metadata(),
667 receipt,
668 )
669}
670
671fn require_gray(source: &GpuImage, operation: &str) -> SpatialResult<()> {
672 if source.channels() != 1 {
673 return Err(SpatialError::InvalidArgument(format!(
674 "{operation} requires a single-channel GpuImage"
675 )));
676 }
677 Ok(())
678}
679
680#[cfg(all(test, not(target_arch = "wasm32")))]
681#[path = "morphology_tests.rs"]
682mod morphology_tests;
683
684#[cfg(all(test, not(target_arch = "wasm32")))]
685#[path = "sobel_tests.rs"]
686mod sobel_tests;