1use super::GpuImageBorder;
3use crate::{
4 image::gpu_image::{create_texture, runtime_device_key, GpuImage, GpuImageReceipt},
5 WgpuRuntime,
6};
7use bytemuck::{Pod, Zeroable};
8use spatialrust_core::{SpatialError, SpatialResult};
9use std::sync::Arc;
10use wgpu::util::DeviceExt;
11const SHADER: &str = concat!(
12 include_str!("../rounding_u32.wgsl"),
13 "\n",
14 include_str!("../binary64_positive.wgsl"),
15 "\n",
16 include_str!("bilateral_round.wgsl"),
17 "\n",
18 include_str!("bilateral.wgsl")
19);
20#[derive(Clone, Copy, Debug, PartialEq)]
22pub struct GpuBilateralOptions {
23 pub diameter: u32,
25 pub sigma_color: f64,
27 pub sigma_space: f64,
29 pub border: GpuImageBorder,
31}
32impl Default for GpuBilateralOptions {
33 fn default() -> Self {
34 Self { diameter: 5, sigma_color: 40.0, sigma_space: 3.0, border: GpuImageBorder::Replicate }
35 }
36}
37#[repr(C)]
38#[derive(Clone, Copy, Pod, Zeroable)]
39struct Params {
40 width: u32,
41 height: u32,
42 channels: u32,
43 taps: u32,
44 border: u32,
45 padding: [u32; 3],
46}
47fn invalid() -> SpatialError {
48 SpatialError::InvalidArgument("GPU bilateral requires 1..=4 u8 channels, diameter 1..=7, finite positive sigmas, normal-or-zero weights and supported device limits".into())
49}
50fn control(
51 channels: u32,
52 options: GpuBilateralOptions,
53 limits: &wgpu::Limits,
54) -> SpatialResult<(Vec<[u32; 2]>, u32)> {
55 if !(1..=4).contains(&channels)
56 || !(1..=7).contains(&options.diameter)
57 || !options.sigma_color.is_finite()
58 || options.sigma_color <= 0.0
59 || !options.sigma_space.is_finite()
60 || options.sigma_space <= 0.0
61 {
62 return Err(invalid());
63 }
64 let cf = -0.5 / (options.sigma_color * options.sigma_color);
65 let sf = -0.5 / (options.sigma_space * options.sigma_space);
66 if !cf.is_finite() || !sf.is_finite() {
67 return Err(invalid());
68 }
69 let radius = (options.diameter / 2) as i32;
70 let mut taps = Vec::new();
71 let mut distances = Vec::new();
72 for dy in -radius..=radius {
73 for dx in -radius..=radius {
74 let d = dx * dx + dy * dy;
75 if d <= radius * radius {
76 taps.push((dx, dy, d));
77 if !distances.contains(&d) {
78 distances.push(d);
79 }
80 }
81 }
82 }
83 distances.sort_unstable();
84 let colors = 255 * channels + 1;
85 let entries = taps.len() * 2 + distances.len() * colors as usize;
86 let bytes = (entries * 8) as u64;
87 capabilities(bytes, limits)?;
88 let mut data = Vec::with_capacity(entries);
89 for &(dx, dy, d) in &taps {
90 let index = distances.iter().position(|&v| v == d).unwrap();
91 data.push([dx as u32, dy as u32]);
92 data.push([(taps.len() * 2 + index * colors as usize) as u32, 0]);
93 }
94 for d in distances {
95 for color in 0..colors {
96 let w = if d == 0 {
98 if color == 0 {
99 1.0
100 } else {
101 0.0
102 }
103 } else {
104 let c = f64::from(color);
105 (c.mul_add(c, 0.0).mul_add(cf, f64::from(d) * sf)).exp()
106 };
107 if !w.is_finite() || w < 0.0 || (w != 0.0 && !w.is_normal()) {
108 return Err(invalid());
109 }
110 let bits = w.to_bits();
111 data.push([bits as u32, (bits >> 32) as u32]);
112 }
113 }
114 Ok((data, taps.len() as u32))
115}
116fn capabilities(bytes: u64, l: &wgpu::Limits) -> SpatialResult<()> {
117 if bytes > l.max_buffer_size
118 || bytes > u64::from(l.max_storage_buffer_binding_size)
119 || l.max_storage_buffers_per_shader_stage == 0
120 || l.max_uniform_buffer_binding_size < 32
121 || l.max_buffer_size < 32
122 || l.max_bind_groups == 0
123 || l.max_bindings_per_bind_group < 4
124 || l.max_uniform_buffers_per_shader_stage == 0
125 || l.max_sampled_textures_per_shader_stage == 0
126 || l.max_storage_textures_per_shader_stage == 0
127 || l.max_compute_workgroup_size_x < 16
128 || l.max_compute_workgroup_size_y < 16
129 || l.max_compute_workgroup_size_z == 0
130 || l.max_compute_invocations_per_workgroup < 256
131 {
132 return Err(invalid());
133 }
134 Ok(())
135}
136fn dimensions(w: u32, h: u32, r: u32, l: &wgpu::Limits) -> SpatialResult<u64> {
137 if w == 0
138 || h == 0
139 || w > i32::MAX as u32
140 || h > i32::MAX as u32
141 || w > l.max_texture_dimension_2d
142 || h > l.max_texture_dimension_2d
143 || u64::from(w - 1) + u64::from(r) > i32::MAX as u64
144 || u64::from(h - 1) + u64::from(r) > i32::MAX as u64
145 || w.div_ceil(16) > l.max_compute_workgroups_per_dimension
146 || h.div_ceil(16) > l.max_compute_workgroups_per_dimension
147 {
148 return Err(invalid());
149 }
150 Ok(u64::from(w) * u64::from(h) * 4)
151}
152pub struct GpuBilateralFilter {
159 device_key: Arc<()>,
160 channels: u32,
161 options: GpuBilateralOptions,
162 coefficients: wgpu::Buffer,
163 taps: u32,
164 receipt: GpuImageReceipt,
165}
166impl GpuBilateralFilter {
167 pub fn prepare(
170 runtime: &WgpuRuntime,
171 channels: u32,
172 options: GpuBilateralOptions,
173 ) -> SpatialResult<Self> {
174 let (data, taps) = control(channels, options, &runtime.device().limits())?;
175 let bytes = (data.len() * 8) as u64;
176 let coefficients = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
177 label: Some("bilateral-coefficients"),
178 contents: bytemuck::cast_slice(&data),
179 usage: wgpu::BufferUsages::STORAGE,
180 });
181 let mut receipt = GpuImageReceipt::default();
182 receipt.record_host_to_device(bytes, "prepare_bilateral_coefficients");
183 Ok(Self {
184 device_key: runtime_device_key(runtime),
185 channels,
186 options,
187 coefficients,
188 taps,
189 receipt,
190 })
191 }
192 #[must_use]
194 pub fn receipt(&self) -> &GpuImageReceipt {
195 &self.receipt
196 }
197 pub fn filter(&self, runtime: &WgpuRuntime, source: &GpuImage) -> SpatialResult<GpuImage> {
201 if !Arc::ptr_eq(&self.device_key, &runtime_device_key(runtime))
202 || source.channels() != self.channels
203 {
204 return Err(invalid());
205 }
206 source.validate_runtime(runtime)?;
207 let limits = runtime.device().limits();
208 capabilities(self.receipt.host_to_device_bytes(), &limits)?;
209 let bytes =
210 dimensions(source.width(), source.height(), self.options.diameter / 2, &limits)?;
211 let cache = runtime
212 .image_bilateral_pipeline
213 .get_or_init(|| BilateralPipeline::new(runtime.device()));
214 let output = create_texture(runtime, source.width(), source.height(), "bilateral-output");
215 let params = Params {
216 width: source.width(),
217 height: source.height(),
218 channels: self.channels,
219 taps: self.taps,
220 border: u32::from(self.options.border == GpuImageBorder::ConstantZero),
221 padding: [0; 3],
222 };
223 let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
224 label: Some("bilateral-params"),
225 contents: bytemuck::bytes_of(¶ms),
226 usage: wgpu::BufferUsages::UNIFORM,
227 });
228 let group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
229 label: Some("bilateral-group"),
230 layout: &cache.layout,
231 entries: &[
232 wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() },
233 wgpu::BindGroupEntry {
234 binding: 1,
235 resource: wgpu::BindingResource::TextureView(&source.view()),
236 },
237 wgpu::BindGroupEntry {
238 binding: 2,
239 resource: self.coefficients.as_entire_binding(),
240 },
241 wgpu::BindGroupEntry {
242 binding: 3,
243 resource: wgpu::BindingResource::TextureView(
244 &output.create_view(&Default::default()),
245 ),
246 },
247 ],
248 });
249 let mut encoder = runtime.device().create_command_encoder(&Default::default());
250 {
251 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
252 label: Some("bilateral_filter_gpu"),
253 timestamp_writes: None,
254 });
255 pass.set_pipeline(&cache.pipeline);
256 pass.set_bind_group(0, &group, &[]);
257 pass.dispatch_workgroups(source.width().div_ceil(16), source.height().div_ceil(16), 1);
258 }
259 runtime.queue().submit(Some(encoder.finish()));
260 let mut receipt = source.receipt().clone();
261 receipt.record_gpu_to_gpu(bytes, "bilateral_filter_gpu");
262 GpuImage::from_parts(
263 runtime,
264 source.width(),
265 source.height(),
266 source.channels(),
267 output,
268 source.metadata(),
269 receipt,
270 )
271 }
272}
273pub(crate) struct BilateralPipeline {
274 layout: wgpu::BindGroupLayout,
275 pipeline: wgpu::ComputePipeline,
276}
277impl BilateralPipeline {
278 fn new(device: &wgpu::Device) -> Self {
279 Self::with_shader(device, SHADER)
280 }
281 fn with_shader(device: &wgpu::Device, shader: &str) -> Self {
282 let buffer = |binding, ty| wgpu::BindGroupLayoutEntry {
283 binding,
284 visibility: wgpu::ShaderStages::COMPUTE,
285 ty: wgpu::BindingType::Buffer { ty, has_dynamic_offset: false, min_binding_size: None },
286 count: None,
287 };
288 let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
289 label: Some("bilateral-layout"),
290 entries: &[
291 buffer(0, wgpu::BufferBindingType::Uniform),
292 wgpu::BindGroupLayoutEntry {
293 binding: 1,
294 visibility: wgpu::ShaderStages::COMPUTE,
295 ty: wgpu::BindingType::Texture {
296 sample_type: wgpu::TextureSampleType::Uint,
297 view_dimension: wgpu::TextureViewDimension::D2,
298 multisampled: false,
299 },
300 count: None,
301 },
302 buffer(2, wgpu::BufferBindingType::Storage { read_only: true }),
303 wgpu::BindGroupLayoutEntry {
304 binding: 3,
305 visibility: wgpu::ShaderStages::COMPUTE,
306 ty: wgpu::BindingType::StorageTexture {
307 access: wgpu::StorageTextureAccess::WriteOnly,
308 format: wgpu::TextureFormat::Rgba8Uint,
309 view_dimension: wgpu::TextureViewDimension::D2,
310 },
311 count: None,
312 },
313 ],
314 });
315 let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
316 label: Some("bilateral-shader"),
317 source: wgpu::ShaderSource::Wgsl(shader.into()),
318 });
319 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
320 label: Some("bilateral-pipeline-layout"),
321 bind_group_layouts: &[&layout],
322 push_constant_ranges: &[],
323 });
324 let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
325 label: Some("bilateral-pipeline"),
326 layout: Some(&pipeline_layout),
327 module: &module,
328 entry_point: Some("bilateral"),
329 compilation_options: Default::default(),
330 cache: None,
331 });
332 Self { layout, pipeline }
333 }
334}
335#[cfg(all(test, not(target_arch = "wasm32")))]
336#[path = "bilateral_tests.rs"]
337mod tests;