| 1 | //! WebGPU-safe compute pipeline registry and multi-pass dispatcher for `AutoMatte` & `MagicMask`. |
| 2 | //! |
| 3 | //! All input textures use `TextureSampleType::Float { filterable: false }` (read via `textureLoad`), |
| 4 | //! output storage textures are `WriteOnly`, and uniform buffers use a growable 512-slot chunk ring |
| 5 | //! reset via `Engine::reset_uniform_cursors()` and trimmed via `Engine::trim_uniform_chunks()`. |
| 6 | |
| 7 | use super::cache::CachedMatteFrame; |
| 8 | use super::prompts::{AutoMatteParams, MAX_GPU_SEEDS, OutputMode, QualityTier}; |
| 9 | use crate::cache::{CachedTexture, NodeCache}; |
| 10 | use bytemuck::{Pod, Zeroable}; |
| 11 | use model::BitDepth; |
| 12 | use std::collections::{HashMap, VecDeque}; |
| 13 | use std::num::NonZeroU64; |
| 14 | |
| 15 | const AUTO_MATTE_WGSL: &str = include_str!("../shaders/auto_matte.wgsl"); |
| 16 | const AM_UNIFORM_SLOTS_PER_CHUNK: u32 = 512; |
| 17 | const MAX_UPLOADED_MATTE_CACHE: usize = 8; |
| 18 | |
| 19 | /// Exact 640-byte uniform block matching `AutoMatteUniform` in `auto_matte.wgsl`. |
| 20 | #[repr(C)] |
| 21 | #[derive(Clone, Copy, Pod, Zeroable)] |
| 22 | struct AutoMatteUniform { |
| 23 | p: [[f32; 4]; 8], |
| 24 | seeds: [[f32; 4]; MAX_GPU_SEEDS], |
| 25 | } |
| 26 | |
| 27 | impl Default for AutoMatteUniform { |
| 28 | fn default() -> Self { |
| 29 | Self { |
| 30 | p: [[0.0; 4]; 8], |
| 31 | seeds: [[0.0; 4]; MAX_GPU_SEEDS], |
| 32 | } |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | #[derive(Clone, Copy)] |
| 37 | enum AutoMatteOp { |
| 38 | SeedSegment, |
| 39 | BilateralRefine, |
| 40 | PolishAlpha, |
| 41 | MorphoH, |
| 42 | MorphoV, |
| 43 | GaussBlurH, |
| 44 | GaussBlurV, |
| 45 | DecontamInit, |
| 46 | DecontamMergeScale, |
| 47 | CompositeOutput, |
| 48 | } |
| 49 | |
| 50 | fn build_auto_matte_wgsl(format: wgpu::TextureFormat, hdr_float: bool) -> String { |
| 51 | let storage_fmt = match format { |
| 52 | wgpu::TextureFormat::Rgba16Float => "rgba16float", |
| 53 | wgpu::TextureFormat::Rgba32Float => "rgba32float", |
| 54 | _ => "rgba8unorm", |
| 55 | }; |
| 56 | let mut src = AUTO_MATTE_WGSL.to_owned(); |
| 57 | if storage_fmt != "rgba8unorm" { |
| 58 | src = src.replace( |
| 59 | "texture_storage_2d<rgba8unorm, write>", |
| 60 | &format!("texture_storage_2d<{storage_fmt}, write>"), |
| 61 | ); |
| 62 | } |
| 63 | if hdr_float { |
| 64 | src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;"); |
| 65 | } |
| 66 | src |
| 67 | } |
| 68 | |
| 69 | fn unfilterable_tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { |
| 70 | wgpu::BindGroupLayoutEntry { |
| 71 | binding, |
| 72 | visibility: wgpu::ShaderStages::COMPUTE, |
| 73 | ty: wgpu::BindingType::Texture { |
| 74 | sample_type: wgpu::TextureSampleType::Float { filterable: false }, |
| 75 | view_dimension: wgpu::TextureViewDimension::D2, |
| 76 | multisampled: false, |
| 77 | }, |
| 78 | count: None, |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | struct AutoMatteFormatPipelines { |
| 83 | bgl: wgpu::BindGroupLayout, |
| 84 | seed_segment: wgpu::ComputePipeline, |
| 85 | bilateral_refine: wgpu::ComputePipeline, |
| 86 | polish_alpha: wgpu::ComputePipeline, |
| 87 | morpho_h: wgpu::ComputePipeline, |
| 88 | morpho_v: wgpu::ComputePipeline, |
| 89 | gauss_blur_h: wgpu::ComputePipeline, |
| 90 | gauss_blur_v: wgpu::ComputePipeline, |
| 91 | decontam_init: wgpu::ComputePipeline, |
| 92 | decontam_merge_scale: wgpu::ComputePipeline, |
| 93 | composite_output: wgpu::ComputePipeline, |
| 94 | } |
| 95 | |
| 96 | impl AutoMatteFormatPipelines { |
| 97 | fn pipeline(&self, op: AutoMatteOp) -> &wgpu::ComputePipeline { |
| 98 | match op { |
| 99 | AutoMatteOp::SeedSegment => &self.seed_segment, |
| 100 | AutoMatteOp::BilateralRefine => &self.bilateral_refine, |
| 101 | AutoMatteOp::PolishAlpha => &self.polish_alpha, |
| 102 | AutoMatteOp::MorphoH => &self.morpho_h, |
| 103 | AutoMatteOp::MorphoV => &self.morpho_v, |
| 104 | AutoMatteOp::GaussBlurH => &self.gauss_blur_h, |
| 105 | AutoMatteOp::GaussBlurV => &self.gauss_blur_v, |
| 106 | AutoMatteOp::DecontamInit => &self.decontam_init, |
| 107 | AutoMatteOp::DecontamMergeScale => &self.decontam_merge_scale, |
| 108 | AutoMatteOp::CompositeOutput => &self.composite_output, |
| 109 | } |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | struct UploadedMatteTex { |
| 114 | _texture: wgpu::Texture, |
| 115 | view: wgpu::TextureView, |
| 116 | } |
| 117 | |
| 118 | /// GPU pipeline registry and growable uniform chunk ring for `AutoMatte` and `MagicMask`. |
| 119 | pub(crate) struct AutoMattePipelines { |
| 120 | uniform_stride: u32, |
| 121 | uniform_chunks: Vec<wgpu::Buffer>, |
| 122 | uniform_cursor: u32, |
| 123 | by_format: HashMap<(wgpu::TextureFormat, bool), AutoMatteFormatPipelines>, |
| 124 | uploaded_mattes: HashMap<u64, UploadedMatteTex>, |
| 125 | uploaded_order: VecDeque<u64>, |
| 126 | } |
| 127 | |
| 128 | impl AutoMattePipelines { |
| 129 | pub(crate) fn new(device: &wgpu::Device) -> Self { |
| 130 | let uniform_size = std::mem::size_of::<AutoMatteUniform>() as u32; |
| 131 | let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); |
| 132 | let uniform_stride = uniform_size.div_ceil(min_align) * min_align; |
| 133 | Self { |
| 134 | uniform_stride, |
| 135 | uniform_chunks: Vec::new(), |
| 136 | uniform_cursor: 0, |
| 137 | by_format: HashMap::new(), |
| 138 | uploaded_mattes: HashMap::new(), |
| 139 | uploaded_order: VecDeque::new(), |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | pub(crate) fn reset_uniform_cursor(&mut self) { |
| 144 | self.uniform_cursor = 0; |
| 145 | } |
| 146 | |
| 147 | pub(crate) fn trim_uniform_chunks(&mut self, max_chunks: usize) { |
| 148 | self.uniform_cursor = 0; |
| 149 | if self.uniform_chunks.len() > max_chunks { |
| 150 | self.uniform_chunks.truncate(max_chunks); |
| 151 | } |
| 152 | self.uploaded_mattes.clear(); |
| 153 | self.uploaded_order.clear(); |
| 154 | } |
| 155 | |
| 156 | fn alloc_uniform_slot( |
| 157 | &mut self, |
| 158 | device: &wgpu::Device, |
| 159 | queue: &wgpu::Queue, |
| 160 | params: &AutoMatteUniform, |
| 161 | ) -> (usize, u32) { |
| 162 | let slot_global = self.uniform_cursor; |
| 163 | let chunk_idx = (slot_global / AM_UNIFORM_SLOTS_PER_CHUNK) as usize; |
| 164 | let slot_in_chunk = slot_global % AM_UNIFORM_SLOTS_PER_CHUNK; |
| 165 | while chunk_idx >= self.uniform_chunks.len() { |
| 166 | let size = u64::from(AM_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride); |
| 167 | let buf = device.create_buffer(&wgpu::BufferDescriptor { |
| 168 | label: Some("auto-matte-params-ring"), |
| 169 | size, |
| 170 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, |
| 171 | mapped_at_creation: false, |
| 172 | }); |
| 173 | self.uniform_chunks.push(buf); |
| 174 | } |
| 175 | let offset = slot_in_chunk * self.uniform_stride; |
| 176 | queue.write_buffer( |
| 177 | &self.uniform_chunks[chunk_idx], |
| 178 | u64::from(offset), |
| 179 | bytemuck::bytes_of(params), |
| 180 | ); |
| 181 | self.uniform_cursor = slot_global + 1; |
| 182 | (chunk_idx, offset) |
| 183 | } |
| 184 | |
| 185 | fn ensure_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) { |
| 186 | if self.by_format.contains_key(&(format, hdr_float)) { |
| 187 | return; |
| 188 | } |
| 189 | let u_size = std::mem::size_of::<AutoMatteUniform>() as u64; |
| 190 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 191 | label: Some("auto-matte-bgl"), |
| 192 | entries: &[ |
| 193 | unfilterable_tex_entry(0), |
| 194 | unfilterable_tex_entry(1), |
| 195 | unfilterable_tex_entry(2), |
| 196 | unfilterable_tex_entry(3), |
| 197 | wgpu::BindGroupLayoutEntry { |
| 198 | binding: 4, |
| 199 | visibility: wgpu::ShaderStages::COMPUTE, |
| 200 | ty: wgpu::BindingType::StorageTexture { |
| 201 | access: wgpu::StorageTextureAccess::WriteOnly, |
| 202 | format, |
| 203 | view_dimension: wgpu::TextureViewDimension::D2, |
| 204 | }, |
| 205 | count: None, |
| 206 | }, |
| 207 | wgpu::BindGroupLayoutEntry { |
| 208 | binding: 5, |
| 209 | visibility: wgpu::ShaderStages::COMPUTE, |
| 210 | ty: wgpu::BindingType::Buffer { |
| 211 | ty: wgpu::BufferBindingType::Uniform, |
| 212 | has_dynamic_offset: true, |
| 213 | min_binding_size: NonZeroU64::new(u_size), |
| 214 | }, |
| 215 | count: None, |
| 216 | }, |
| 217 | ], |
| 218 | }); |
| 219 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 220 | label: Some("auto-matte-pl"), |
| 221 | bind_group_layouts: &[Some(&bgl)], |
| 222 | immediate_size: 0, |
| 223 | }); |
| 224 | let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 225 | label: Some("auto-matte-wgsl"), |
| 226 | source: wgpu::ShaderSource::Wgsl(build_auto_matte_wgsl(format, hdr_float).into()), |
| 227 | }); |
| 228 | let mk = |entry: &str| { |
| 229 | device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { |
| 230 | label: Some(entry), |
| 231 | layout: Some(&pl), |
| 232 | module: &module, |
| 233 | entry_point: Some(entry), |
| 234 | compilation_options: Default::default(), |
| 235 | cache: None, |
| 236 | }) |
| 237 | }; |
| 238 | self.by_format.insert( |
| 239 | (format, hdr_float), |
| 240 | AutoMatteFormatPipelines { |
| 241 | bgl, |
| 242 | seed_segment: mk("seed_segment_op"), |
| 243 | bilateral_refine: mk("bilateral_refine_op"), |
| 244 | polish_alpha: mk("polish_alpha_op"), |
| 245 | morpho_h: mk("morpho_h_op"), |
| 246 | morpho_v: mk("morpho_v_op"), |
| 247 | gauss_blur_h: mk("gauss_blur_h_op"), |
| 248 | gauss_blur_v: mk("gauss_blur_v_op"), |
| 249 | decontam_init: mk("decontam_init_op"), |
| 250 | decontam_merge_scale: mk("decontam_merge_scale_op"), |
| 251 | composite_output: mk("composite_output_op"), |
| 252 | }, |
| 253 | ); |
| 254 | } |
| 255 | |
| 256 | #[allow(clippy::too_many_arguments)] |
| 257 | fn dispatch( |
| 258 | &mut self, |
| 259 | device: &wgpu::Device, |
| 260 | queue: &wgpu::Queue, |
| 261 | enc: &mut wgpu::CommandEncoder, |
| 262 | op: AutoMatteOp, |
| 263 | inputs: [&wgpu::TextureView; 4], |
| 264 | dst: &CachedTexture, |
| 265 | params: &AutoMatteUniform, |
| 266 | ) { |
| 267 | let hdr_float = dst.depth.is_float(); |
| 268 | self.ensure_format(device, dst.format, hdr_float); |
| 269 | let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params); |
| 270 | let fp = &self.by_format[&(dst.format, hdr_float)]; |
| 271 | let u_size = NonZeroU64::new(std::mem::size_of::<AutoMatteUniform>() as u64); |
| 272 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 273 | label: Some("auto-matte-bg"), |
| 274 | layout: &fp.bgl, |
| 275 | entries: &[ |
| 276 | wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(inputs[0]) }, |
| 277 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(inputs[1]) }, |
| 278 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(inputs[2]) }, |
| 279 | wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(inputs[3]) }, |
| 280 | wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&dst.view) }, |
| 281 | wgpu::BindGroupEntry { |
| 282 | binding: 5, |
| 283 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| 284 | buffer: &self.uniform_chunks[chunk_idx], |
| 285 | offset: 0, |
| 286 | size: u_size, |
| 287 | }), |
| 288 | }, |
| 289 | ], |
| 290 | }); |
| 291 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { |
| 292 | label: Some("auto-matte-pass"), |
| 293 | timestamp_writes: None, |
| 294 | }); |
| 295 | pass.set_pipeline(fp.pipeline(op)); |
| 296 | pass.set_bind_group(0, &bg, &[offset]); |
| 297 | pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1); |
| 298 | } |
| 299 | |
| 300 | fn upload_cached_matte( |
| 301 | &mut self, |
| 302 | device: &wgpu::Device, |
| 303 | queue: &wgpu::Queue, |
| 304 | matte: &CachedMatteFrame, |
| 305 | ) -> wgpu::TextureView { |
| 306 | if let Some(existing) = self.uploaded_mattes.get(&matte.content_hash) { |
| 307 | return existing.view.clone(); |
| 308 | } |
| 309 | let w = matte.size[0].max(1); |
| 310 | let h = matte.size[1].max(1); |
| 311 | let tex = device.create_texture(&wgpu::TextureDescriptor { |
| 312 | label: Some("auto-matte-cached-r32f"), |
| 313 | size: wgpu::Extent3d { |
| 314 | width: w, |
| 315 | height: h, |
| 316 | depth_or_array_layers: 1, |
| 317 | }, |
| 318 | mip_level_count: 1, |
| 319 | sample_count: 1, |
| 320 | dimension: wgpu::TextureDimension::D2, |
| 321 | format: wgpu::TextureFormat::R32Float, |
| 322 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, |
| 323 | view_formats: &[], |
| 324 | }); |
| 325 | queue.write_texture( |
| 326 | tex.as_image_copy(), |
| 327 | bytemuck::cast_slice(&matte.alpha), |
| 328 | wgpu::TexelCopyBufferLayout { |
| 329 | offset: 0, |
| 330 | bytes_per_row: Some(w * 4), |
| 331 | rows_per_image: Some(h), |
| 332 | }, |
| 333 | wgpu::Extent3d { |
| 334 | width: w, |
| 335 | height: h, |
| 336 | depth_or_array_layers: 1, |
| 337 | }, |
| 338 | ); |
| 339 | let view = tex.create_view(&wgpu::TextureViewDescriptor::default()); |
| 340 | let view_clone = view.clone(); |
| 341 | self.uploaded_mattes.insert( |
| 342 | matte.content_hash, |
| 343 | UploadedMatteTex { _texture: tex, view }, |
| 344 | ); |
| 345 | self.uploaded_order.push_back(matte.content_hash); |
| 346 | while self.uploaded_mattes.len() > MAX_UPLOADED_MATTE_CACHE { |
| 347 | if let Some(old) = self.uploaded_order.pop_front() { |
| 348 | self.uploaded_mattes.remove(&old); |
| 349 | } else { |
| 350 | break; |
| 351 | } |
| 352 | } |
| 353 | view_clone |
| 354 | } |
| 355 | |
| 356 | /// Executes the full AutoMatte / MagicMask GPU pipeline: |
| 357 | /// 1. Stage 1/2: uses `cached_matte` if present, otherwise runs GPU multi-seed segmentation + |
| 358 | /// joint-bilateral edge-aware refinement. |
| 359 | /// 2. Stage 3A: Clover's `polish_alpha` (floor, ceiling, toe gamma, invert) + optional |
| 360 | /// `MatteContractExpand` and `MatteBlur`. |
| 361 | /// 3. Stage 3B: Clover's 3-scale `hair_safe_decontaminate` (`sigma = 28, 12, 4` scaled by |
| 362 | /// `proxy_scale`) + final output mode & `EffectMask` / `Blend` composite. |
| 363 | #[allow(clippy::too_many_arguments)] |
| 364 | pub(crate) fn execute( |
| 365 | &mut self, |
| 366 | device: &wgpu::Device, |
| 367 | queue: &wgpu::Queue, |
| 368 | enc: &mut wgpu::CommandEncoder, |
| 369 | node_cache: &NodeCache, |
| 370 | dummy_view: &wgpu::TextureView, |
| 371 | src: &CachedTexture, |
| 372 | mask_view: &wgpu::TextureView, |
| 373 | has_mask: bool, |
| 374 | mask_inv: bool, |
| 375 | mbm: bool, |
| 376 | skip: [f32; 4], |
| 377 | dst: &CachedTexture, |
| 378 | params: &AutoMatteParams, |
| 379 | cached_matte: Option<&CachedMatteFrame>, |
| 380 | proxy_scale: u32, |
| 381 | ) { |
| 382 | let alloc_f16 = || { |
| 383 | node_cache.acquire_texture_dod_fmt( |
| 384 | device, |
| 385 | src.size, |
| 386 | [0, 0], |
| 387 | src.size, |
| 388 | BitDepth::Float16, |
| 389 | wgpu::TextureFormat::Rgba16Float, |
| 390 | 0, |
| 391 | ) |
| 392 | }; |
| 393 | |
| 394 | // --------------------------------------------------------------------- |
| 395 | // Stage 1 & 2: Acquire raw alpha matte (cached neural OR GPU fallback) |
| 396 | // --------------------------------------------------------------------- |
| 397 | let raw_matte_view: wgpu::TextureView; |
| 398 | let _gpu_fallback_keepalive: Option<CachedTexture>; |
| 399 | if let Some(cm) = cached_matte { |
| 400 | raw_matte_view = self.upload_cached_matte(device, queue, cm); |
| 401 | _gpu_fallback_keepalive = None; |
| 402 | } else { |
| 403 | let seeds = params.effective_gpu_seeds(); |
| 404 | let seg_tex = alloc_f16(); |
| 405 | let mut u_seg = AutoMatteUniform::default(); |
| 406 | let mut neg_count = 0u32; |
| 407 | let count = seeds.len().min(MAX_GPU_SEEDS); |
| 408 | for (i, pt) in seeds.iter().take(count).enumerate() { |
| 409 | let [u, v] = pt.to_gpu_uv(); |
| 410 | let label = if pt.positive { 1.0 } else { neg_count += 1; -1.0 }; |
| 411 | u_seg.seeds[i] = [u, v, label, pt.weight.max(0.01)]; |
| 412 | } |
| 413 | let aspect = (src.size[0] as f32) / (src.size[1].max(1) as f32); |
| 414 | u_seg.p[0] = [ |
| 415 | count as f32, |
| 416 | neg_count as f32, |
| 417 | 0.12, // perceptual Oklab color sigma |
| 418 | 0.85, // spatial sigma for positive seeds |
| 419 | ]; |
| 420 | u_seg.p[1] = [ |
| 421 | if neg_count == 0 { 1.25 } else { 0.85 }, |
| 422 | 1.0, // enable automatic border background seeds when no negative clicks exist |
| 423 | aspect, |
| 424 | params.quality_tier as u32 as f32, |
| 425 | ]; |
| 426 | self.dispatch( |
| 427 | device, |
| 428 | queue, |
| 429 | enc, |
| 430 | AutoMatteOp::SeedSegment, |
| 431 | [&src.view, dummy_view, dummy_view, dummy_view], |
| 432 | &seg_tex, |
| 433 | &u_seg, |
| 434 | ); |
| 435 | |
| 436 | // Joint-bilateral edge-aware alpha refinement guided by original RGB |
| 437 | let refined = match params.quality_tier { |
| 438 | QualityTier::FastInteractive => { |
| 439 | let out = alloc_f16(); |
| 440 | let mut ub = AutoMatteUniform::default(); |
| 441 | ub.p[0] = [3.0, 3.0, 0.08, 1.0]; |
| 442 | self.dispatch( |
| 443 | device, |
| 444 | queue, |
| 445 | enc, |
| 446 | AutoMatteOp::BilateralRefine, |
| 447 | [&src.view, &seg_tex.view, dummy_view, dummy_view], |
| 448 | &out, |
| 449 | &ub, |
| 450 | ); |
| 451 | out |
| 452 | } |
| 453 | QualityTier::MatAnyone2 => { |
| 454 | let mid = alloc_f16(); |
| 455 | let out = alloc_f16(); |
| 456 | let mut u1 = AutoMatteUniform::default(); |
| 457 | u1.p[0] = [3.0, 4.5, 0.075, 2.0]; |
| 458 | self.dispatch( |
| 459 | device, |
| 460 | queue, |
| 461 | enc, |
| 462 | AutoMatteOp::BilateralRefine, |
| 463 | [&src.view, &seg_tex.view, dummy_view, dummy_view], |
| 464 | &mid, |
| 465 | &u1, |
| 466 | ); |
| 467 | let mut u2 = AutoMatteUniform::default(); |
| 468 | u2.p[0] = [3.0, 2.5, 0.06, 1.0]; |
| 469 | self.dispatch( |
| 470 | device, |
| 471 | queue, |
| 472 | enc, |
| 473 | AutoMatteOp::BilateralRefine, |
| 474 | [&src.view, &mid.view, dummy_view, dummy_view], |
| 475 | &out, |
| 476 | &u2, |
| 477 | ); |
| 478 | out |
| 479 | } |
| 480 | QualityTier::HeroHair => { |
| 481 | let mid = alloc_f16(); |
| 482 | let out = alloc_f16(); |
| 483 | let mut u1 = AutoMatteUniform::default(); |
| 484 | u1.p[0] = [4.0, 5.0, 0.06, 2.0]; |
| 485 | self.dispatch( |
| 486 | device, |
| 487 | queue, |
| 488 | enc, |
| 489 | AutoMatteOp::BilateralRefine, |
| 490 | [&src.view, &seg_tex.view, dummy_view, dummy_view], |
| 491 | &mid, |
| 492 | &u1, |
| 493 | ); |
| 494 | let mut u2 = AutoMatteUniform::default(); |
| 495 | u2.p[0] = [3.0, 2.2, 0.045, 1.0]; |
| 496 | self.dispatch( |
| 497 | device, |
| 498 | queue, |
| 499 | enc, |
| 500 | AutoMatteOp::BilateralRefine, |
| 501 | [&src.view, &mid.view, dummy_view, dummy_view], |
| 502 | &out, |
| 503 | &u2, |
| 504 | ); |
| 505 | out |
| 506 | } |
| 507 | }; |
| 508 | raw_matte_view = (*refined.view).clone(); |
| 509 | _gpu_fallback_keepalive = Some(refined); |
| 510 | } |
| 511 | |
| 512 | // --------------------------------------------------------------------- |
| 513 | // Stage 3A: Clover's exact `polish_alpha` + optional morpho & blur |
| 514 | // --------------------------------------------------------------------- |
| 515 | let mut matte_tex = alloc_f16(); |
| 516 | let mut u_pol = AutoMatteUniform::default(); |
| 517 | u_pol.p[0] = [ |
| 518 | params.alpha_floor, |
| 519 | params.alpha_ceiling, |
| 520 | params.toe_gamma, |
| 521 | if params.invert { 1.0 } else { 0.0 }, |
| 522 | ]; |
| 523 | self.dispatch( |
| 524 | device, |
| 525 | queue, |
| 526 | enc, |
| 527 | AutoMatteOp::PolishAlpha, |
| 528 | [&raw_matte_view, dummy_view, dummy_view, dummy_view], |
| 529 | &matte_tex, |
| 530 | &u_pol, |
| 531 | ); |
| 532 | |
| 533 | let scale = proxy_scale.max(1) as f32; |
| 534 | if params.matte_contract_expand.abs() > 1e-4 { |
| 535 | let radius_px = (params.matte_contract_expand * (src.size[0] as f32 / 128.0).max(1.0)) |
| 536 | .clamp(-64.0, 64.0); |
| 537 | let tmp = alloc_f16(); |
| 538 | let out = alloc_f16(); |
| 539 | let mut um = AutoMatteUniform::default(); |
| 540 | um.p[0][0] = radius_px; |
| 541 | self.dispatch( |
| 542 | device, |
| 543 | queue, |
| 544 | enc, |
| 545 | AutoMatteOp::MorphoH, |
| 546 | [&matte_tex.view, dummy_view, dummy_view, dummy_view], |
| 547 | &tmp, |
| 548 | &um, |
| 549 | ); |
| 550 | self.dispatch( |
| 551 | device, |
| 552 | queue, |
| 553 | enc, |
| 554 | AutoMatteOp::MorphoV, |
| 555 | [&tmp.view, dummy_view, dummy_view, dummy_view], |
| 556 | &out, |
| 557 | &um, |
| 558 | ); |
| 559 | matte_tex = out; |
| 560 | } |
| 561 | |
| 562 | if params.matte_blur > 1e-3 { |
| 563 | let sigma = (params.matte_blur / scale).clamp(0.1, 64.0); |
| 564 | let max_r = (sigma * 2.5).ceil().clamp(1.0, 76.0); |
| 565 | let tmp = alloc_f16(); |
| 566 | let out = alloc_f16(); |
| 567 | let mut ub = AutoMatteUniform::default(); |
| 568 | ub.p[0] = [sigma, max_r, 0.0, 0.0]; |
| 569 | self.dispatch( |
| 570 | device, |
| 571 | queue, |
| 572 | enc, |
| 573 | AutoMatteOp::GaussBlurH, |
| 574 | [&matte_tex.view, dummy_view, dummy_view, dummy_view], |
| 575 | &tmp, |
| 576 | &ub, |
| 577 | ); |
| 578 | self.dispatch( |
| 579 | device, |
| 580 | queue, |
| 581 | enc, |
| 582 | AutoMatteOp::GaussBlurV, |
| 583 | [&tmp.view, dummy_view, dummy_view, dummy_view], |
| 584 | &out, |
| 585 | &ub, |
| 586 | ); |
| 587 | matte_tex = out; |
| 588 | } |
| 589 | |
| 590 | // --------------------------------------------------------------------- |
| 591 | // Stage 3B: Clover's 3-scale `hair_safe_decontaminate` (sigma = 28, 12, 4) |
| 592 | // --------------------------------------------------------------------- |
| 593 | let need_decontam = params.decontaminate > 1e-4 |
| 594 | && params.output_mode == OutputMode::PremultipliedCutout; |
| 595 | let extrap_keepalive: Option<CachedTexture> = if need_decontam { |
| 596 | let solid_tex = alloc_f16(); |
| 597 | let u_zero = AutoMatteUniform::default(); |
| 598 | self.dispatch( |
| 599 | device, |
| 600 | queue, |
| 601 | enc, |
| 602 | AutoMatteOp::DecontamInit, |
| 603 | [&src.view, &matte_tex.view, dummy_view, dummy_view], |
| 604 | &solid_tex, |
| 605 | &u_zero, |
| 606 | ); |
| 607 | |
| 608 | let blur_tmp = alloc_f16(); |
| 609 | let blur_out = alloc_f16(); |
| 610 | let extrap_a = alloc_f16(); |
| 611 | let extrap_b = alloc_f16(); |
| 612 | |
| 613 | for (idx, &base_sigma) in [28.0_f32, 12.0, 4.0].iter().enumerate() { |
| 614 | let sigma = (base_sigma / scale).max(0.5); |
| 615 | let max_r = (sigma * 2.5).ceil().clamp(1.0, 76.0); |
| 616 | let mut ub = AutoMatteUniform::default(); |
| 617 | ub.p[0] = [sigma, max_r, 0.0, 0.0]; |
| 618 | self.dispatch( |
| 619 | device, |
| 620 | queue, |
| 621 | enc, |
| 622 | AutoMatteOp::GaussBlurH, |
| 623 | [&solid_tex.view, dummy_view, dummy_view, dummy_view], |
| 624 | &blur_tmp, |
| 625 | &ub, |
| 626 | ); |
| 627 | self.dispatch( |
| 628 | device, |
| 629 | queue, |
| 630 | enc, |
| 631 | AutoMatteOp::GaussBlurV, |
| 632 | [&blur_tmp.view, dummy_view, dummy_view, dummy_view], |
| 633 | &blur_out, |
| 634 | &ub, |
| 635 | ); |
| 636 | let prev_view = match idx { |
| 637 | 0 => &src.view, |
| 638 | 1 => &extrap_a.view, |
| 639 | _ => &extrap_b.view, |
| 640 | }; |
| 641 | let next_tex = if idx % 2 == 0 { &extrap_a } else { &extrap_b }; |
| 642 | self.dispatch( |
| 643 | device, |
| 644 | queue, |
| 645 | enc, |
| 646 | AutoMatteOp::DecontamMergeScale, |
| 647 | [prev_view, &blur_out.view, dummy_view, dummy_view], |
| 648 | next_tex, |
| 649 | &u_zero, |
| 650 | ); |
| 651 | } |
| 652 | Some(extrap_a) |
| 653 | } else { |
| 654 | None |
| 655 | }; |
| 656 | |
| 657 | // --------------------------------------------------------------------- |
| 658 | // Stage 3C: Final composite (cutout / matte / overlay + EffectMask/Blend) |
| 659 | // --------------------------------------------------------------------- |
| 660 | let extrap_view = extrap_keepalive |
| 661 | .as_ref() |
| 662 | .map_or(&src.view, |t| &t.view); |
| 663 | let mut u_comp = AutoMatteUniform::default(); |
| 664 | u_comp.p[0] = [ |
| 665 | params.decontaminate, |
| 666 | params.output_mode as u32 as f32, |
| 667 | params.blend, |
| 668 | if has_mask { 1.0 } else { 0.0 }, |
| 669 | ]; |
| 670 | u_comp.p[1] = [ |
| 671 | if mask_inv { 1.0 } else { 0.0 }, |
| 672 | if mbm { 1.0 } else { 0.0 }, |
| 673 | 0.0, |
| 674 | 0.0, |
| 675 | ]; |
| 676 | u_comp.p[2] = skip; |
| 677 | self.dispatch( |
| 678 | device, |
| 679 | queue, |
| 680 | enc, |
| 681 | AutoMatteOp::CompositeOutput, |
| 682 | [&src.view, &matte_tex.view, extrap_view, mask_view], |
| 683 | dst, |
| 684 | &u_comp, |
| 685 | ); |
| 686 | } |
| 687 | } |