| 1 | use super::*; |
| 2 | |
| 3 | /// GPU post-processing applied to a CPU-rasterized mask. |
| 4 | pub(super) struct MaskPost<'a> { |
| 5 | pub soft_px: f32, |
| 6 | pub is_box: bool, |
| 7 | pub clamp_edges: f32, |
| 8 | pub paint_mode: f32, |
| 9 | pub invert: bool, |
| 10 | pub level: f32, |
| 11 | pub prev: Option<&'a CachedTexture>, |
| 12 | } |
| 13 | |
| 14 | impl Engine { |
| 15 | /// Maps Fusion `FitMask` / `FitInput` FuID or numeric enum to shader mode id: |
| 16 | /// `0=Crop, 1=Stretch, 2=Inside, 3=Width, 4=Height, 5=Outside`. |
| 17 | pub(super) fn fit_mask_mode(comp: &Comp, node: &Node, input: &str, time: f64, expr: &ExprEngine) -> f32 { |
| 18 | if let Some(s) = node.static_str(input) { |
| 19 | return match s { |
| 20 | "Stretch" => 1.0, |
| 21 | "Inside" => 2.0, |
| 22 | "Width" => 3.0, |
| 23 | "Height" => 4.0, |
| 24 | "Outside" => 5.0, |
| 25 | _ => 0.0, // Crop |
| 26 | }; |
| 27 | } |
| 28 | let n = comp.eval_number(node, input, time, 0.0, expr).round().clamp(0.0, 5.0); |
| 29 | n as f32 |
| 30 | } |
| 31 | |
| 32 | pub(super) fn paint_mode_id(node: &Node) -> f32 { |
| 33 | match node.static_str("PaintMode").unwrap_or("Merge") { |
| 34 | "Add" => 1.0, |
| 35 | "Subtract" => 2.0, |
| 36 | "Multiply" => 3.0, |
| 37 | "Minimum" => 4.0, |
| 38 | "Maximum" => 5.0, |
| 39 | "Invert" => 6.0, |
| 40 | "Replace" => 7.0, |
| 41 | "Average" => 8.0, |
| 42 | _ => 0.0, // Merge |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | fn is_paint_ignore(node: &Node) -> bool { |
| 47 | node.static_str("PaintMode") |
| 48 | .unwrap_or("Merge") |
| 49 | .eq_ignore_ascii_case("Ignore") |
| 50 | } |
| 51 | |
| 52 | pub(super) fn eval_paint_ignore( |
| 53 | &self, |
| 54 | node: &Node, |
| 55 | size: [u32; 2], |
| 56 | prev_mask: Option<CachedTexture>, |
| 57 | ) -> Option<CachedTexture> { |
| 58 | if !Self::is_paint_ignore(node) { |
| 59 | return None; |
| 60 | } |
| 61 | Some(prev_mask.unwrap_or_else(|| create_texture(&self.device, size, 0))) |
| 62 | } |
| 63 | |
| 64 | /// Runs Fusion-calibrated separable mask `SoftEdge` blur with progressive 2x downsampling so |
| 65 | /// large `SoftEdge` values (up to 0.5+ / ~960px at 1080p) neither alias nor hit the 64-tap cap. |
| 66 | pub(super) fn blur_mask_texture( |
| 67 | &self, |
| 68 | enc: &mut wgpu::CommandEncoder, |
| 69 | raw: &CachedTexture, |
| 70 | soft_px: f32, |
| 71 | is_box: bool, |
| 72 | clamp_edges: f32, |
| 73 | ) -> CachedTexture { |
| 74 | let size = raw.size; |
| 75 | let mode = if is_box { 1.0 } else { 0.0 }; |
| 76 | // Fusion mask Box filter has half-width ~0.707 * soft_px (1/sqrt(2)); Fast Gaussian matches FWHM sigma ≈ 0.42466*soft_px + 0.29. |
| 77 | let eff_r = if is_box { soft_px * 0.707 } else { (soft_px * 0.42466 + 0.29) / 0.45 }; |
| 78 | // Keep per-level radius <= 48px (16px in Fast mode) via progressive 2x pyramid steps so thin shapes don't alias. |
| 79 | let max_level_r = if self.hiq { 48.0 } else { 16.0 }; |
| 80 | let mut levels = 0u32; |
| 81 | let mut r_s = eff_r; |
| 82 | let mut ws = size; |
| 83 | while r_s > max_level_r && ws[0] >= 16 && ws[1] >= 16 && levels < 5 { |
| 84 | levels += 1; |
| 85 | r_s *= 0.5; |
| 86 | ws = [(ws[0] / 2).max(1), (ws[1] / 2).max(1)]; |
| 87 | } |
| 88 | |
| 89 | let mut u_blit = UniformParams::default(); |
| 90 | u_blit.p[0] = [1.0, 1.0, 0.0, 0.0]; |
| 91 | let mut cur = raw.clone(); |
| 92 | if levels > 0 { |
| 93 | let mut cur_sz = size; |
| 94 | for _ in 0..levels { |
| 95 | cur_sz = [(cur_sz[0] / 2).max(1), (cur_sz[1] / 2).max(1)]; |
| 96 | let next = create_texture(&self.device, cur_sz, 0); |
| 97 | self.dispatch_op(enc, ShaderOp::DisplayBlit, &cur.view, &self.dummy.view, &self.dummy.view, &next, &u_blit); |
| 98 | cur = next; |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | let tmp1 = self.alloc_tex(cur.size, BitDepth::Float32, 0); |
| 103 | let tmp2 = create_texture(&self.device, cur.size, 0); |
| 104 | let mut uh = UniformParams::default(); |
| 105 | uh.p[0] = [1.0, 0.0, r_s, mode]; |
| 106 | uh.p[1] = [1.0, 0.0, 0.0, clamp_edges]; |
| 107 | self.dispatch_op(enc, ShaderOp::Blur, &cur.view, &self.dummy.view, &self.dummy.view, &tmp1, &uh); |
| 108 | let mut uv = UniformParams::default(); |
| 109 | uv.p[0] = [0.0, 1.0, r_s, mode]; |
| 110 | uv.p[1] = [1.0, 0.0, 0.0, clamp_edges]; |
| 111 | self.dispatch_op(enc, ShaderOp::Blur, &tmp1.view, &self.dummy.view, &self.dummy.view, &tmp2, &uv); |
| 112 | |
| 113 | if levels > 0 { |
| 114 | let up = create_texture(&self.device, size, 0); |
| 115 | self.dispatch_op(enc, ShaderOp::DisplayBlit, &tmp2.view, &self.dummy.view, &self.dummy.view, &up, &u_blit); |
| 116 | up |
| 117 | } else { |
| 118 | tmp2 |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | pub(super) fn mask_filter_is_box(node: &Node) -> bool { |
| 123 | node.static_str("Filter").unwrap_or("Fast Gaussian").eq_ignore_ascii_case("Box") |
| 124 | } |
| 125 | |
| 126 | pub(super) fn mask_clamp_edges(node: &Node) -> f32 { |
| 127 | // Fusion masks default to ClippingMode = "Frame" (clamp to border); "None" pads with 0 outside frame. |
| 128 | if node.static_str("ClippingMode").unwrap_or("Frame").eq_ignore_ascii_case("None") { |
| 129 | 0.0 |
| 130 | } else { |
| 131 | 1.0 |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | #[allow(clippy::too_many_arguments)] |
| 136 | pub(super) fn eval_mask_shape( |
| 137 | &mut self, |
| 138 | comp: &Comp, |
| 139 | node: &Node, |
| 140 | time: f64, |
| 141 | frame_i: i64, |
| 142 | comp_dims: [u32; 2], |
| 143 | shape: u32, |
| 144 | enc: &mut wgpu::CommandEncoder, |
| 145 | visiting: &mut HashSet<(NodeId, i64)>, |
| 146 | stats: &mut EvalStats, |
| 147 | ) -> CachedTexture { |
| 148 | let output_size_mode = node.static_str("OutputSize").unwrap_or("Default"); |
| 149 | let size = if output_size_mode != "Custom" { |
| 150 | if let Some(ts) = self.mask_target_size { |
| 151 | ts |
| 152 | } else { |
| 153 | let w = comp.eval_number(node, "MaskWidth", time, comp.width as f64, &self.expr) as u32; |
| 154 | let h = comp.eval_number(node, "MaskHeight", time, comp.height as f64, &self.expr) as u32; |
| 155 | if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims } |
| 156 | } |
| 157 | } else { |
| 158 | let w = comp.eval_number(node, "MaskWidth", time, comp.width as f64, &self.expr) as u32; |
| 159 | let h = comp.eval_number(node, "MaskHeight", time, comp.height as f64, &self.expr) as u32; |
| 160 | if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims } |
| 161 | }; |
| 162 | let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); |
| 163 | let mw = comp.eval_number(node, "Width", time, 0.5, &self.expr) as f32; |
| 164 | let mh = comp.eval_number(node, "Height", time, 0.5, &self.expr) as f32; |
| 165 | let angle = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians(); |
| 166 | let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr).max(0.0) as f32; |
| 167 | let corner = comp.eval_number(node, "CornerRadius", time, 0.0, &self.expr) as f32; |
| 168 | let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) as f32; |
| 169 | let level = (comp.eval_number(node, "Level", time, 1.0, &self.expr).clamp(0.0, 1.0) * 255.0).floor() as f32 / 255.0; |
| 170 | let border_w = comp.eval_number(node, "BorderWidth", time, 0.0, &self.expr) as f32; |
| 171 | let solid = if comp.eval_number(node, "Solid", time, 1.0, &self.expr) > 0.5 { 1.0 } else { 0.0 }; |
| 172 | let is_box = Self::mask_filter_is_box(node); |
| 173 | let clamp_edges = Self::mask_clamp_edges(node); |
| 174 | let (prev_mask, _) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); |
| 175 | if let Some(ignored) = self.eval_paint_ignore(node, size, prev_mask.clone()) { |
| 176 | return ignored; |
| 177 | } |
| 178 | let prev_hash = prev_mask.as_ref().map_or(0, |m| m.content_hash); |
| 179 | let paint_mode = Self::paint_mode_id(node); |
| 180 | |
| 181 | let mut u = UniformParams::default(); |
| 182 | u.p[0] = [center[0] as f32, center[1] as f32, mw, mh]; |
| 183 | u.p[1] = [angle, soft, corner, invert]; |
| 184 | u.p[2] = [shape as f32, level, if prev_mask.is_some() { 1.0 } else { 0.0 }, paint_mode]; |
| 185 | u.p[3] = [border_w, solid, if is_box { 1.0 } else { 0.0 }, clamp_edges]; |
| 186 | |
| 187 | let key = self.make_key(node, "MaskShape", size, &[prev_hash], bytemuck::cast_slice(&u.p[..4])); |
| 188 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 189 | stats.cache_hits += 1; |
| 190 | return hit; |
| 191 | } |
| 192 | stats.cache_misses += 1; |
| 193 | stats.nodes_evaluated += 1; |
| 194 | let mv = prev_mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 195 | let soft_px = soft * size[0] as f32; |
| 196 | let dst = if soft_px >= 0.5 { |
| 197 | let raw = create_texture(&self.device, size, 0); |
| 198 | let mut u_raw = u; |
| 199 | u_raw.p[1] = [angle, 0.0, corner, 0.0]; |
| 200 | u_raw.p[2] = [shape as f32, 1.0, 0.0, 0.0]; |
| 201 | self.dispatch_op(enc, ShaderOp::MaskShape, &self.dummy.view, &self.dummy.view, &self.dummy.view, &raw, &u_raw); |
| 202 | |
| 203 | let blurred = self.blur_mask_texture(enc, &raw, soft_px, is_box, clamp_edges); |
| 204 | |
| 205 | let out_tex = create_texture(&self.device, size, key); |
| 206 | let mut uc = UniformParams::default(); |
| 207 | uc.p[0] = [paint_mode, invert, level, if prev_mask.is_some() { 1.0 } else { 0.0 }]; |
| 208 | self.dispatch_op(enc, ShaderOp::MaskCombine, &blurred.view, &self.dummy.view, mv, &out_tex, &uc); |
| 209 | out_tex |
| 210 | } else { |
| 211 | let out_tex = create_texture(&self.device, size, key); |
| 212 | self.dispatch_op(enc, ShaderOp::MaskShape, &self.dummy.view, &self.dummy.view, mv, &out_tex, &u); |
| 213 | out_tex |
| 214 | }; |
| 215 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 216 | dst |
| 217 | } |
| 218 | |
| 219 | #[allow(clippy::too_many_arguments)] |
| 220 | pub(super) fn eval_polyline_mask( |
| 221 | &mut self, |
| 222 | comp: &Comp, |
| 223 | node: &Node, |
| 224 | time: f64, |
| 225 | frame_i: i64, |
| 226 | comp_dims: [u32; 2], |
| 227 | enc: &mut wgpu::CommandEncoder, |
| 228 | visiting: &mut HashSet<(NodeId, i64)>, |
| 229 | stats: &mut EvalStats, |
| 230 | ) -> CachedTexture { |
| 231 | let size = self.explicit_mask_size(comp, node, time, comp_dims); |
| 232 | let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); |
| 233 | let angle = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32; |
| 234 | let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr).max(0.0) as f32; |
| 235 | let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) > 0.5; |
| 236 | let level = (comp.eval_number(node, "Level", time, 1.0, &self.expr).clamp(0.0, 1.0) * 255.0).floor() as f32 / 255.0; |
| 237 | let is_box = Self::mask_filter_is_box(node); |
| 238 | let clamp_edges = Self::mask_clamp_edges(node); |
| 239 | let (prev_mask, _) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); |
| 240 | if let Some(ignored) = self.eval_paint_ignore(node, size, prev_mask.clone()) { |
| 241 | return ignored; |
| 242 | } |
| 243 | let prev_hash = prev_mask.as_ref().map_or(0, |m| m.content_hash); |
| 244 | let paint_mode = Self::paint_mode_id(node); |
| 245 | |
| 246 | let points = Self::polyline_points(comp, node, time); |
| 247 | |
| 248 | let mut hash_floats = Vec::with_capacity(9 + points.len() * 6); |
| 249 | hash_floats.extend_from_slice(&[ |
| 250 | center[0] as f32, |
| 251 | center[1] as f32, |
| 252 | angle, |
| 253 | soft, |
| 254 | if invert { 1.0 } else { 0.0 }, |
| 255 | level, |
| 256 | paint_mode, |
| 257 | if is_box { 1.0 } else { 0.0 }, |
| 258 | clamp_edges, |
| 259 | ]); |
| 260 | for p in &points { |
| 261 | hash_floats.extend_from_slice(&[p.x as f32, p.y as f32, p.lx as f32, p.ly as f32, p.rx as f32, p.ry as f32]); |
| 262 | } |
| 263 | let key = self.make_key(node, "PolylineMask", size, &[prev_hash], &hash_floats); |
| 264 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 265 | stats.cache_hits += 1; |
| 266 | return hit; |
| 267 | } |
| 268 | stats.cache_misses += 1; |
| 269 | stats.nodes_evaluated += 1; |
| 270 | |
| 271 | let soft_px = soft * size[0] as f32; |
| 272 | let need_post = soft_px >= 0.5 || invert || (level - 1.0).abs() > 1e-4 || prev_mask.is_some(); |
| 273 | let raw_tex = self.alloc_tex(size, BitDepth::Int8, if need_post { 0 } else { key }); |
| 274 | let soft_px = soft * raw_tex.size[0] as f32; |
| 275 | |
| 276 | let has_coverage = match polyline_tight_commands(raw_tex.size, &points, [center[0] as f32, center[1] as f32], angle) { |
| 277 | Some(([bx0, by0, bx1, by1], cmds)) => { |
| 278 | let bw = (bx1 - bx0) as u32; |
| 279 | let bh = (by1 - by0) as u32; |
| 280 | let mut cov_buf = vec![0u8; (bw as usize) * (bh as usize)]; |
| 281 | let mut scratch = zeno::Scratch::new(); |
| 282 | let _ = zeno::Mask::with_scratch(&cmds, &mut scratch) |
| 283 | .size(bw, bh) |
| 284 | .origin(zeno::Origin::TopLeft) |
| 285 | .render_into(&mut cov_buf, None); |
| 286 | |
| 287 | let eff_level = if need_post { 1.0 } else { level }; |
| 288 | let mut rgba = vec![0u8; cov_buf.len() * 4]; |
| 289 | if (eff_level - 1.0).abs() <= 1e-6 { |
| 290 | for (dst, &cov) in rgba.chunks_exact_mut(4).zip(cov_buf.iter()) { |
| 291 | dst.fill(cov); |
| 292 | } |
| 293 | } else { |
| 294 | for (dst, &cov) in rgba.chunks_exact_mut(4).zip(cov_buf.iter()) { |
| 295 | let b = (cov as f32 * eff_level).clamp(0.0, 255.0) as u8; |
| 296 | dst.fill(b); |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | if bw == raw_tex.size[0] && bh == raw_tex.size[1] { |
| 301 | self.queue.write_texture( |
| 302 | raw_tex.texture.as_image_copy(), |
| 303 | &rgba, |
| 304 | wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(bw * 4), rows_per_image: Some(bh) }, |
| 305 | wgpu::Extent3d { width: bw, height: bh, depth_or_array_layers: 1 }, |
| 306 | ); |
| 307 | } else { |
| 308 | let small_tex = self.alloc_tex([bw, bh], BitDepth::Int8, 0); |
| 309 | self.queue.write_texture( |
| 310 | small_tex.texture.as_image_copy(), |
| 311 | &rgba, |
| 312 | wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(bw * 4), rows_per_image: Some(bh) }, |
| 313 | wgpu::Extent3d { width: bw, height: bh, depth_or_array_layers: 1 }, |
| 314 | ); |
| 315 | clear_texture_transparent(enc, &raw_tex.view); |
| 316 | enc.copy_texture_to_texture( |
| 317 | small_tex.texture.as_image_copy(), |
| 318 | wgpu::TexelCopyTextureInfo { |
| 319 | texture: &raw_tex.texture, |
| 320 | mip_level: 0, |
| 321 | origin: wgpu::Origin3d { x: bx0 as u32, y: by0 as u32, z: 0 }, |
| 322 | aspect: wgpu::TextureAspect::All, |
| 323 | }, |
| 324 | wgpu::Extent3d { width: bw, height: bh, depth_or_array_layers: 1 }, |
| 325 | ); |
| 326 | } |
| 327 | true |
| 328 | } |
| 329 | _ => { |
| 330 | clear_texture_transparent(enc, &raw_tex.view); |
| 331 | false |
| 332 | } |
| 333 | }; |
| 334 | |
| 335 | let tex = if need_post { |
| 336 | let post = MaskPost { |
| 337 | soft_px: if has_coverage { soft_px } else { 0.0 }, |
| 338 | is_box, |
| 339 | clamp_edges, |
| 340 | paint_mode, |
| 341 | invert, |
| 342 | level, |
| 343 | prev: prev_mask.as_ref(), |
| 344 | }; |
| 345 | self.apply_mask_post(enc, size, key, raw_tex, post) |
| 346 | } else { |
| 347 | raw_tex |
| 348 | }; |
| 349 | self.cache.insert(key, tex.clone(), node.id, frame_i); |
| 350 | tex |
| 351 | } |
| 352 | |
| 353 | /// Mask size from explicit `MaskWidth`/`MaskHeight`, else the inherited target size, else the comp's. |
| 354 | /// Always clamped to the device's `max_texture_dimension_2d` so CPU mask rasterizers and |
| 355 | /// `queue.write_texture` uploads cannot OOM or exceed GPU texture extents. |
| 356 | pub(super) fn explicit_mask_size(&self, comp: &Comp, node: &Node, time: f64, comp_dims: [u32; 2]) -> [u32; 2] { |
| 357 | let raw = if node.inputs.contains_key("MaskWidth") || node.inputs.contains_key("MaskHeight") { |
| 358 | let w_f = comp.eval_number(node, "MaskWidth", time, comp.width as f64, &self.expr); |
| 359 | let h_f = comp.eval_number(node, "MaskHeight", time, comp.height as f64, &self.expr); |
| 360 | let w = if w_f.is_finite() && w_f > 0.0 { |
| 361 | w_f.min(u32::MAX as f64) as u32 |
| 362 | } else { |
| 363 | 0 |
| 364 | }; |
| 365 | let h = if h_f.is_finite() && h_f > 0.0 { |
| 366 | h_f.min(u32::MAX as f64) as u32 |
| 367 | } else { |
| 368 | 0 |
| 369 | }; |
| 370 | if w >= 16 && h >= 16 { |
| 371 | self.scaled_dims(w, h) |
| 372 | } else { |
| 373 | comp_dims |
| 374 | } |
| 375 | } else { |
| 376 | self.mask_target_size.unwrap_or(comp_dims) |
| 377 | }; |
| 378 | crate::cache::clamp_dims_to_limit(raw[0], raw[1], self.device.limits().max_texture_dimension_2d.max(1)).0 |
| 379 | } |
| 380 | |
| 381 | /// Control points of `node`'s `Polyline` input: animated spline, `PolyPath` modifier, or inline value. |
| 382 | pub(super) fn polyline_points(comp: &Comp, node: &Node, time: f64) -> Vec<model::PolyPoint> { |
| 383 | if let Some(src) = node.connected_node("Polyline") { |
| 384 | if let Some(pts) = comp.eval_polyline_spline(src, time) { |
| 385 | return pts; |
| 386 | } |
| 387 | return comp.poly_paths.get(src).map(|pp| pp.points.clone()).unwrap_or_default(); |
| 388 | } |
| 389 | node.raw |
| 390 | .get_table("Inputs") |
| 391 | .and_then(|i| i.get_table("Polyline").or_else(|| i.get_table("PolyLine"))) |
| 392 | .and_then(|p| p.get_table("Value")) |
| 393 | .map(|t| model::PolyPath::parse_polyline_table(t).1) |
| 394 | .unwrap_or_default() |
| 395 | } |
| 396 | |
| 397 | /// Uploads CPU-rasterized RGBA8 mask `pixels`; with `post`, applies `SoftEdge`, `Invert`, `Level` |
| 398 | /// and `PaintMode` chaining against the previous mask on the GPU. |
| 399 | pub(super) fn upload_cpu_mask( |
| 400 | &self, |
| 401 | enc: &mut wgpu::CommandEncoder, |
| 402 | size: [u32; 2], |
| 403 | key: u64, |
| 404 | pixels: &[u8], |
| 405 | post: Option<MaskPost>, |
| 406 | ) -> CachedTexture { |
| 407 | let raw_tex = self.alloc_tex(size, BitDepth::Int8, if post.is_some() { 0 } else { key }); |
| 408 | self.queue.write_texture( |
| 409 | raw_tex.texture.as_image_copy(), |
| 410 | pixels, |
| 411 | wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(size[0] * 4), rows_per_image: Some(size[1]) }, |
| 412 | wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 }, |
| 413 | ); |
| 414 | match post { |
| 415 | Some(p) => self.apply_mask_post(enc, size, key, raw_tex, p), |
| 416 | None => raw_tex, |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | pub(super) fn apply_mask_post( |
| 421 | &self, |
| 422 | enc: &mut wgpu::CommandEncoder, |
| 423 | size: [u32; 2], |
| 424 | key: u64, |
| 425 | raw_tex: CachedTexture, |
| 426 | p: MaskPost, |
| 427 | ) -> CachedTexture { |
| 428 | let blurred = if p.soft_px >= 0.5 { |
| 429 | self.blur_mask_texture(enc, &raw_tex, p.soft_px, p.is_box, p.clamp_edges) |
| 430 | } else { |
| 431 | raw_tex |
| 432 | }; |
| 433 | let combined = self.alloc_tex(size, BitDepth::Int8, key); |
| 434 | let mut u = UniformParams::default(); |
| 435 | u.p[0] = [p.paint_mode, if p.invert { 1.0 } else { 0.0 }, p.level, if p.prev.is_some() { 1.0 } else { 0.0 }]; |
| 436 | let mv = p.prev.map_or(&self.dummy.view, |m| &m.view); |
| 437 | self.dispatch_op(enc, ShaderOp::MaskCombine, &blurred.view, &self.dummy.view, mv, &combined, &u); |
| 438 | combined |
| 439 | } |
| 440 | |
| 441 | /// `BitmapMask` and `WandMask` only chain `EffectMask` when it is driven by a mask node/port, |
| 442 | /// ignoring regular `Image` outputs wired into `EffectMask`. |
| 443 | pub(super) fn bitmap_or_wand_prev_mask( |
| 444 | &mut self, |
| 445 | comp: &Comp, |
| 446 | node: &Node, |
| 447 | time: f64, |
| 448 | size: [u32; 2], |
| 449 | enc: &mut wgpu::CommandEncoder, |
| 450 | visiting: &mut HashSet<(NodeId, i64)>, |
| 451 | stats: &mut EvalStats, |
| 452 | ) -> Option<CachedTexture> { |
| 453 | let port = node |
| 454 | .raw |
| 455 | .get_table("Inputs") |
| 456 | .and_then(|t| t.get_table("EffectMask")) |
| 457 | .and_then(|t| t.get_str("Source")); |
| 458 | let mask_id = node.connected_node("EffectMask").and_then(|s| comp.find_node(s))?; |
| 459 | let is_mask_kind = matches!( |
| 460 | comp.node(mask_id).kind.as_str(), |
| 461 | "EllipseMask" |
| 462 | | "RectangleMask" |
| 463 | | "PolylineMask" |
| 464 | | "BSplineMask" |
| 465 | | "MultiPoly" |
| 466 | | "TeapotMask" |
| 467 | | "TriangleMask" |
| 468 | | "BitmapMask" |
| 469 | | "WandMask" |
| 470 | | "RangesMask" |
| 471 | | "PaintMask" |
| 472 | ); |
| 473 | if port == Some("Output") && !is_mask_kind { |
| 474 | return None; |
| 475 | } |
| 476 | self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats).0 |
| 477 | } |
| 478 | |
| 479 | #[allow(clippy::too_many_arguments)] |
| 480 | pub(super) fn eval_bitmap_mask( |
| 481 | &mut self, |
| 482 | comp: &Comp, |
| 483 | node: &Node, |
| 484 | time: f64, |
| 485 | frame_i: i64, |
| 486 | comp_dims: [u32; 2], |
| 487 | enc: &mut wgpu::CommandEncoder, |
| 488 | visiting: &mut HashSet<(NodeId, i64)>, |
| 489 | stats: &mut EvalStats, |
| 490 | ) -> CachedTexture { |
| 491 | let Some(src_id) = node.connected_node("Image").and_then(|s| comp.find_node(s)) else { |
| 492 | return self.dummy.clone(); |
| 493 | }; |
| 494 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 495 | |
| 496 | let output_size_mode = node.static_str("OutputSize").unwrap_or("Default"); |
| 497 | let size = if output_size_mode == "Custom" { |
| 498 | let w = comp.eval_number(node, "MaskWidth", time, comp.width as f64, &self.expr) as u32; |
| 499 | let h = comp.eval_number(node, "MaskHeight", time, comp.height as f64, &self.expr) as u32; |
| 500 | if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { comp_dims } |
| 501 | } else if let Some(ts) = self.mask_target_size { |
| 502 | ts |
| 503 | } else if node.inputs.contains_key("MaskWidth") || node.inputs.contains_key("MaskHeight") { |
| 504 | let w = comp.eval_number(node, "MaskWidth", time, comp.width as f64, &self.expr) as u32; |
| 505 | let h = comp.eval_number(node, "MaskHeight", time, comp.height as f64, &self.expr) as u32; |
| 506 | if w >= 16 && h >= 16 { self.scaled_dims(w, h) } else { src.canvas_size } |
| 507 | } else { |
| 508 | src.canvas_size |
| 509 | }; |
| 510 | |
| 511 | let ch_id: f32 = match node.static_str("Channel").unwrap_or("Alpha") { |
| 512 | "Luminance" => 1.0, |
| 513 | "Red" => 2.0, |
| 514 | "Green" => 3.0, |
| 515 | "Blue" => 4.0, |
| 516 | "Saturation" => 5.0, |
| 517 | "Lightness" => 6.0, |
| 518 | "Hue" => 7.0, |
| 519 | "Coverage" => 8.0, |
| 520 | _ => 0.0, // Alpha (Fusion default) |
| 521 | }; |
| 522 | let low = comp.eval_number(node, "Low", time, 0.0, &self.expr) as f32; |
| 523 | let high = comp.eval_number(node, "High", time, 1.0, &self.expr) as f32; |
| 524 | let clip_black = comp.eval_number(node, "ClipBlack", time, 1.0, &self.expr) > 0.5; |
| 525 | let clip_white = comp.eval_number(node, "ClipWhite", time, 1.0, &self.expr) > 0.5; |
| 526 | let no_clip_black = if clip_black { 0.0 } else { 1.0 }; |
| 527 | let no_clip_white = if clip_white { 0.0 } else { 1.0 }; |
| 528 | let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr).max(0.0) as f32; |
| 529 | let invert = if comp.eval_number(node, "Invert", time, 0.0, &self.expr) > 0.5 { 1.0 } else { 0.0 }; |
| 530 | let level = comp.eval_number(node, "Level", time, 1.0, &self.expr) as f32; |
| 531 | let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); |
| 532 | let fit_mode = Self::fit_mask_mode(comp, node, "FitInput", time, &self.expr); |
| 533 | let is_box = Self::mask_filter_is_box(node); |
| 534 | let clamp_edges = Self::mask_clamp_edges(node); |
| 535 | let prev_mask = self.bitmap_or_wand_prev_mask(comp, node, time, size, enc, visiting, stats); |
| 536 | if let Some(ignored) = self.eval_paint_ignore(node, size, prev_mask.clone()) { |
| 537 | return ignored; |
| 538 | } |
| 539 | let prev_hash = prev_mask.as_ref().map_or(0, |m| m.content_hash); |
| 540 | let paint_mode = Self::paint_mode_id(node); |
| 541 | |
| 542 | let key = self.make_key( |
| 543 | node, |
| 544 | "BitmapMask", |
| 545 | size, |
| 546 | &[src.content_hash, prev_hash], |
| 547 | &[ |
| 548 | ch_id, low, high, no_clip_black, no_clip_white, soft, invert, level, |
| 549 | center[0] as f32, center[1] as f32, fit_mode, |
| 550 | if is_box { 1.0 } else { 0.0 }, clamp_edges, paint_mode, |
| 551 | ], |
| 552 | ); |
| 553 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 554 | stats.cache_hits += 1; |
| 555 | return hit; |
| 556 | } |
| 557 | stats.cache_misses += 1; |
| 558 | stats.nodes_evaluated += 1; |
| 559 | |
| 560 | let soft_px = soft * size[0] as f32; |
| 561 | let need_post = soft_px >= 0.5 || invert > 0.5 || (level - 1.0).abs() > 1e-4 || prev_mask.is_some(); |
| 562 | |
| 563 | let raw_tex = create_texture(&self.device, size, if need_post { 0 } else { key }); |
| 564 | let mut u = UniformParams::default(); |
| 565 | u.p[0] = [ch_id, low, high, fit_mode]; |
| 566 | u.p[1] = [center[0] as f32, center[1] as f32, src.origin[0] as f32, src.origin[1] as f32]; |
| 567 | u.p[2] = [src.canvas_size[0] as f32, src.canvas_size[1] as f32, no_clip_black, no_clip_white]; |
| 568 | self.dispatch_op(enc, ShaderOp::BitmapMask, &src.view, &self.dummy.view, &self.dummy.view, &raw_tex, &u); |
| 569 | |
| 570 | let out_tex = if need_post { |
| 571 | // Fusion BitmapMask applies Invert before SoftEdge so ClippingMode=None feathers inverted edges to 0. |
| 572 | let (pre_blur, post_invert) = if soft_px >= 0.5 && invert > 0.5 { |
| 573 | let inv_tex = create_texture(&self.device, size, 0); |
| 574 | let mut ui = UniformParams::default(); |
| 575 | ui.p[0] = [0.0, 1.0, 1.0, 0.0]; |
| 576 | self.dispatch_op(enc, ShaderOp::MaskCombine, &raw_tex.view, &self.dummy.view, &self.dummy.view, &inv_tex, &ui); |
| 577 | (inv_tex, 0.0) |
| 578 | } else { |
| 579 | (raw_tex, invert) |
| 580 | }; |
| 581 | let blurred = if soft_px >= 0.5 { |
| 582 | self.blur_mask_texture(enc, &pre_blur, soft_px, is_box, clamp_edges) |
| 583 | } else { |
| 584 | pre_blur |
| 585 | }; |
| 586 | let combined = create_texture(&self.device, size, key); |
| 587 | let mut uc = UniformParams::default(); |
| 588 | uc.p[0] = [paint_mode, post_invert, level, if prev_mask.is_some() { 1.0 } else { 0.0 }]; |
| 589 | let mv = prev_mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 590 | self.dispatch_op(enc, ShaderOp::MaskCombine, &blurred.view, &self.dummy.view, mv, &combined, &uc); |
| 591 | combined |
| 592 | } else { |
| 593 | raw_tex |
| 594 | }; |
| 595 | |
| 596 | self.cache.insert(key, out_tex.clone(), node.id, frame_i); |
| 597 | out_tex |
| 598 | } |
| 599 | |
| 600 | pub(super) fn eval_wand_mask( |
| 601 | &mut self, |
| 602 | comp: &Comp, |
| 603 | node: &Node, |
| 604 | time: f64, |
| 605 | frame_i: i64, |
| 606 | comp_dims: [u32; 2], |
| 607 | enc: &mut wgpu::CommandEncoder, |
| 608 | visiting: &mut HashSet<(NodeId, i64)>, |
| 609 | stats: &mut EvalStats, |
| 610 | ) -> CachedTexture { |
| 611 | let Some(src_id) = node |
| 612 | .connected_node("Source") |
| 613 | .or_else(|| node.connected_node("Input")) |
| 614 | .and_then(|s| comp.find_node(s)) |
| 615 | else { |
| 616 | return create_texture(&self.device, comp_dims, 0); |
| 617 | }; |
| 618 | let src = self.eval_node(comp, src_id, time, enc, visiting, stats); |
| 619 | let src = self.crop_to_canvas(enc, src); |
| 620 | let size = src.size; |
| 621 | |
| 622 | let seed_pt = comp.eval_point(node, "SelectionPoint", time, [0.5, 0.5], &self.expr); |
| 623 | let range_default = comp.eval_number(node, "SelectionRange", time, 0.1, &self.expr); |
| 624 | let range = comp.eval_number(node, "Range", time, range_default, &self.expr).max(0.0) as f32; |
| 625 | let range_soft = comp.eval_number(node, "RangeSoftEdge", time, 0.0, &self.expr).max(0.0) as f32; |
| 626 | let color_space = comp.eval_number(node, "ColorSpace", time, 0.0, &self.expr).round() as i32; |
| 627 | let channel = comp.eval_number(node, "Channel", time, 0.0, &self.expr).round() as i32; |
| 628 | let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr).max(0.0) as f32; |
| 629 | let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) as f32; |
| 630 | let level = comp.eval_number(node, "Level", time, 1.0, &self.expr) as f32; |
| 631 | let is_box = Self::mask_filter_is_box(node); |
| 632 | let clamp_edges = Self::mask_clamp_edges(node); |
| 633 | let prev_mask = self.bitmap_or_wand_prev_mask(comp, node, time, size, enc, visiting, stats); |
| 634 | if let Some(ignored) = self.eval_paint_ignore(node, size, prev_mask.clone()) { |
| 635 | return ignored; |
| 636 | } |
| 637 | let prev_hash = prev_mask.as_ref().map_or(0, |m| m.content_hash); |
| 638 | let paint_mode = Self::paint_mode_id(node); |
| 639 | |
| 640 | let key = self.make_key( |
| 641 | node, |
| 642 | "WandMask", |
| 643 | size, |
| 644 | &[src.content_hash, prev_hash], |
| 645 | &[ |
| 646 | seed_pt[0] as f32, |
| 647 | seed_pt[1] as f32, |
| 648 | range, |
| 649 | range_soft, |
| 650 | color_space as f32, |
| 651 | channel as f32, |
| 652 | soft, |
| 653 | invert, |
| 654 | level, |
| 655 | if is_box { 1.0 } else { 0.0 }, |
| 656 | clamp_edges, |
| 657 | paint_mode, |
| 658 | ], |
| 659 | ); |
| 660 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 661 | stats.cache_hits += 1; |
| 662 | return hit; |
| 663 | } |
| 664 | stats.cache_misses += 1; |
| 665 | stats.nodes_evaluated += 1; |
| 666 | |
| 667 | // Flush pending GPU commands so readback sees fresh source pixels. |
| 668 | let flush_enc = std::mem::replace( |
| 669 | enc, |
| 670 | self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 671 | label: Some("comp-eval-post-wand"), |
| 672 | }), |
| 673 | ); |
| 674 | self.queue.submit(Some(flush_enc.finish())); |
| 675 | |
| 676 | let w = size[0].max(1) as usize; |
| 677 | let h = size[1].max(1) as usize; |
| 678 | let mut mask_rgba = if seed_pt[0] < 0.0 || seed_pt[0] > 1.0 || seed_pt[1] < 0.0 || seed_pt[1] > 1.0 { |
| 679 | vec![0; w * h * 4] |
| 680 | } else { |
| 681 | match self.readback_rgba(&src) { |
| 682 | Ok(src_rgba) if src_rgba.len() >= w * h * 4 => { |
| 683 | let sx = (seed_pt[0] * (w - 1) as f64).round() as usize; |
| 684 | let sy = ((1.0 - seed_pt[1]) * (h - 1) as f64).round() as usize; |
| 685 | wand_flood_fill(&src_rgba, w, h, [sx, sy], range, range_soft, channel, color_space) |
| 686 | } |
| 687 | _ => vec![0; w * h * 4], |
| 688 | } |
| 689 | }; |
| 690 | |
| 691 | let soft_px = soft * size[0] as f32; |
| 692 | let invert_before_blur = soft_px >= 0.5 && invert > 0.5; |
| 693 | if invert_before_blur { |
| 694 | for b in &mut mask_rgba { |
| 695 | *b = 255 - *b; |
| 696 | } |
| 697 | } |
| 698 | let post_invert = if invert_before_blur { 0.0 } else { invert }; |
| 699 | let need_post = soft_px >= 0.5 || post_invert > 0.5 || (level - 1.0).abs() > 1e-4 || prev_mask.is_some(); |
| 700 | let raw_tex = create_texture(&self.device, size, if need_post { 0 } else { key }); |
| 701 | self.queue.write_texture( |
| 702 | raw_tex.texture.as_image_copy(), |
| 703 | &mask_rgba, |
| 704 | wgpu::TexelCopyBufferLayout { |
| 705 | offset: 0, |
| 706 | bytes_per_row: Some(size[0] * 4), |
| 707 | rows_per_image: Some(size[1]), |
| 708 | }, |
| 709 | wgpu::Extent3d { |
| 710 | width: size[0], |
| 711 | height: size[1], |
| 712 | depth_or_array_layers: 1, |
| 713 | }, |
| 714 | ); |
| 715 | |
| 716 | let out_tex = if need_post { |
| 717 | let blurred = if soft_px >= 0.5 { |
| 718 | self.blur_mask_texture(enc, &raw_tex, soft_px, is_box, clamp_edges) |
| 719 | } else { |
| 720 | raw_tex |
| 721 | }; |
| 722 | let combined = create_texture(&self.device, size, key); |
| 723 | let mut uc = UniformParams::default(); |
| 724 | uc.p[0] = [paint_mode, post_invert, level, if prev_mask.is_some() { 1.0 } else { 0.0 }]; |
| 725 | let mv = prev_mask.as_ref().map_or(&self.dummy.view, |m| &m.view); |
| 726 | self.dispatch_op(enc, ShaderOp::MaskCombine, &blurred.view, &self.dummy.view, mv, &combined, &uc); |
| 727 | combined |
| 728 | } else { |
| 729 | raw_tex |
| 730 | }; |
| 731 | |
| 732 | self.cache.insert(key, out_tex.clone(), node.id, frame_i); |
| 733 | out_tex |
| 734 | } |
| 735 | |
| 736 | } |
| 737 | |
| 738 | fn rgb_to_hls([r, g, b]: [f32; 3]) -> [f32; 3] { |
| 739 | let max = r.max(g).max(b); |
| 740 | let min = r.min(g).min(b); |
| 741 | let l = 0.5 * (max + min); |
| 742 | let d = max - min; |
| 743 | if d <= 1e-6 { |
| 744 | return [0.0, l, 0.0]; |
| 745 | } |
| 746 | let s = if l <= 0.5 { |
| 747 | d / (max + min).max(1e-6) |
| 748 | } else { |
| 749 | d / (2.0 - max - min).max(1e-6) |
| 750 | }; |
| 751 | let h = if (max - r).abs() <= 1e-6 { |
| 752 | (g - b) / d + if g < b { 6.0 } else { 0.0 } |
| 753 | } else if (max - g).abs() <= 1e-6 { |
| 754 | (b - r) / d + 2.0 |
| 755 | } else { |
| 756 | (r - g) / d + 4.0 |
| 757 | } / 6.0; |
| 758 | [h.rem_euclid(1.0), l, s] |
| 759 | } |
| 760 | |
| 761 | fn rgb_to_yuv([r, g, b]: [f32; 3]) -> [f32; 3] { |
| 762 | let y = 0.299 * r + 0.587 * g + 0.114 * b; |
| 763 | let u = 0.492111 * (b - y) * 0.5; |
| 764 | let v = 0.877283 * (r - y) * 0.5; |
| 765 | [y, u, v] |
| 766 | } |
| 767 | |
| 768 | /// Flood fill from `seed` over RGBA8 `src`: Fusion 21.1 `WandMask` halves `Range` and |
| 769 | /// `RangeSoftEdge` (`r = 0.5 * range`, `s = 0.5 * range_soft`), converts RGB according to |
| 770 | /// `color_space` (`0=RGB`, `1=HLS`, `2=YUV`), selects `Channel` (`0=Color`, `1..3=component`, |
| 771 | /// `4=Alpha`), and falls off linearly from `1.0` at `d <= r` to `0.0` at `r + s`. |
| 772 | #[allow(clippy::too_many_arguments)] |
| 773 | fn wand_flood_fill( |
| 774 | src: &[u8], |
| 775 | w: usize, |
| 776 | h: usize, |
| 777 | seed: [usize; 2], |
| 778 | range: f32, |
| 779 | range_soft: f32, |
| 780 | channel: i32, |
| 781 | color_space: i32, |
| 782 | ) -> Vec<u8> { |
| 783 | let rgba = |i: usize| [ |
| 784 | src[i * 4] as f32 / 255.0, |
| 785 | src[i * 4 + 1] as f32 / 255.0, |
| 786 | src[i * 4 + 2] as f32 / 255.0, |
| 787 | src[i * 4 + 3] as f32 / 255.0, |
| 788 | ]; |
| 789 | let to_space = |rgb: [f32; 3]| match color_space { |
| 790 | 1 => rgb_to_hls(rgb), |
| 791 | 2 => rgb_to_yuv(rgb), |
| 792 | _ => rgb, |
| 793 | }; |
| 794 | let start = seed[1] * w + seed[0]; |
| 795 | let [sr, sg, sb, sa] = rgba(start); |
| 796 | let [sc0, sc1, sc2] = to_space([sr, sg, sb]); |
| 797 | let hue_dist = |a: f32, b: f32| { |
| 798 | let d = (a - b).abs(); |
| 799 | d.min(1.0 - d) |
| 800 | }; |
| 801 | let dist = |i: usize| { |
| 802 | let [r, g, b, a] = rgba(i); |
| 803 | let [c0, c1, c2] = to_space([r, g, b]); |
| 804 | let d0 = if color_space == 1 { hue_dist(c0, sc0) } else { (c0 - sc0).abs() }; |
| 805 | match channel { |
| 806 | 0 => { |
| 807 | let d1 = c1 - sc1; |
| 808 | let d2 = c2 - sc2; |
| 809 | (d0 * d0 + d1 * d1 + d2 * d2).sqrt() |
| 810 | } |
| 811 | 1 => d0, |
| 812 | 2 => (c1 - sc1).abs(), |
| 813 | 3 => (c2 - sc2).abs(), |
| 814 | 4 => (a - sa).abs(), |
| 815 | _ => { |
| 816 | if src[i * 4..i * 4 + 4] == src[start * 4..start * 4 + 4] { |
| 817 | 0.0 |
| 818 | } else { |
| 819 | f32::INFINITY |
| 820 | } |
| 821 | } |
| 822 | } |
| 823 | }; |
| 824 | let r_half = range * 0.5; |
| 825 | let soft_half = range_soft * 0.5; |
| 826 | let max_d = r_half + soft_half; |
| 827 | let mut out = vec![0u8; w * h * 4]; |
| 828 | let mut visited = vec![false; w * h]; |
| 829 | visited[start] = true; |
| 830 | let mut queue = std::collections::VecDeque::from([start]); |
| 831 | while let Some(i) = queue.pop_front() { |
| 832 | let d = dist(i); |
| 833 | let a = if d <= r_half { |
| 834 | 1.0 |
| 835 | } else if soft_half <= 1e-6 { |
| 836 | 0.0 |
| 837 | } else { |
| 838 | (1.0 - (d - r_half) / soft_half).clamp(0.0, 1.0) |
| 839 | }; |
| 840 | out[i * 4..i * 4 + 4].fill((a * 255.0).round() as u8); |
| 841 | let (x, y) = (i % w, i / w); |
| 842 | let nbrs = [(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)]; |
| 843 | for n in nbrs.into_iter().flatten() { |
| 844 | if !visited[n] && dist(n) <= max_d { |
| 845 | visited[n] = true; |
| 846 | queue.push_back(n); |
| 847 | } |
| 848 | } |
| 849 | } |
| 850 | out |
| 851 | } |
| 852 | |
| 853 | pub(super) fn clear_texture_transparent(enc: &mut wgpu::CommandEncoder, view: &wgpu::TextureView) { |
| 854 | let _pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { |
| 855 | label: Some("mask-clear"), |
| 856 | color_attachments: &[Some(wgpu::RenderPassColorAttachment { |
| 857 | view, |
| 858 | depth_slice: None, |
| 859 | resolve_target: None, |
| 860 | ops: wgpu::Operations { |
| 861 | load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), |
| 862 | store: wgpu::StoreOp::Store, |
| 863 | }, |
| 864 | })], |
| 865 | depth_stencil_attachment: None, |
| 866 | timestamp_writes: None, |
| 867 | occlusion_query_set: None, |
| 868 | multiview_mask: None, |
| 869 | }); |
| 870 | } |
| 871 | |
| 872 | /// Builds `zeno` commands for a `PolylineMask` shifted into its tight pixel bounding box |
| 873 | /// `[bx0, by0, bx1, by1]` clamped to `[0..w, 0..h]`, returning `None` if empty or off-canvas. |
| 874 | pub(super) fn polyline_tight_commands( |
| 875 | size: [u32; 2], |
| 876 | points: &[model::PolyPoint], |
| 877 | center: [f32; 2], |
| 878 | angle_deg: f32, |
| 879 | ) -> Option<([i32; 4], Vec<zeno::Command>)> { |
| 880 | if points.len() < 2 || size[0] == 0 || size[1] == 0 { |
| 881 | return None; |
| 882 | } |
| 883 | let [w, h] = size; |
| 884 | let aspect = w as f32 / (h as f32).max(1.0); |
| 885 | let (s, c) = angle_deg.to_radians().sin_cos(); |
| 886 | let to_px = |x: f64, y: f64| -> [f32; 2] { |
| 887 | let (x, y) = (x as f32, y as f32 / aspect); |
| 888 | let (rx, ry) = (x * c - y * s, (x * s + y * c) * aspect); |
| 889 | [(center[0] + rx) * w as f32, (1.0 - (center[1] + ry)) * h as f32] |
| 890 | }; |
| 891 | |
| 892 | let mut min_x = f32::INFINITY; |
| 893 | let mut min_y = f32::INFINITY; |
| 894 | let mut max_x = f32::NEG_INFINITY; |
| 895 | let mut max_y = f32::NEG_INFINITY; |
| 896 | let mut grow = |p: [f32; 2]| { |
| 897 | if p[0].is_finite() && p[1].is_finite() { |
| 898 | min_x = min_x.min(p[0]); |
| 899 | min_y = min_y.min(p[1]); |
| 900 | max_x = max_x.max(p[0]); |
| 901 | max_y = max_y.max(p[1]); |
| 902 | } |
| 903 | }; |
| 904 | |
| 905 | let mut cmds = Vec::with_capacity(points.len() + 2); |
| 906 | let p0 = to_px(points[0].x, points[0].y); |
| 907 | grow(p0); |
| 908 | cmds.push(zeno::Command::MoveTo(zeno::Vector::new(p0[0], p0[1]))); |
| 909 | for i in 0..points.len() { |
| 910 | let a = &points[i]; |
| 911 | let b = &points[(i + 1) % points.len()]; |
| 912 | let p = to_px(b.x, b.y); |
| 913 | grow(p); |
| 914 | if a.linear && b.linear { |
| 915 | cmds.push(zeno::Command::LineTo(zeno::Vector::new(p[0], p[1]))); |
| 916 | } else { |
| 917 | let c1 = to_px(a.x + a.rx, a.y + a.ry); |
| 918 | let c2 = to_px(b.x + b.lx, b.y + b.ly); |
| 919 | grow(c1); |
| 920 | grow(c2); |
| 921 | cmds.push(zeno::Command::CurveTo( |
| 922 | zeno::Vector::new(c1[0], c1[1]), |
| 923 | zeno::Vector::new(c2[0], c2[1]), |
| 924 | zeno::Vector::new(p[0], p[1]), |
| 925 | )); |
| 926 | } |
| 927 | } |
| 928 | cmds.push(zeno::Command::Close); |
| 929 | |
| 930 | if min_x > max_x || min_y > max_y { |
| 931 | return None; |
| 932 | } |
| 933 | let wi = w as i32; |
| 934 | let hi = h as i32; |
| 935 | let bx0 = (min_x.floor() as i32).saturating_sub(2).clamp(0, wi); |
| 936 | let by0 = (min_y.floor() as i32).saturating_sub(2).clamp(0, hi); |
| 937 | let bx1 = (max_x.ceil() as i32).saturating_add(2).clamp(0, wi); |
| 938 | let by1 = (max_y.ceil() as i32).saturating_add(2).clamp(0, hi); |
| 939 | if bx1 <= bx0 || by1 <= by0 { |
| 940 | return None; |
| 941 | } |
| 942 | |
| 943 | if bx0 != 0 || by0 != 0 { |
| 944 | let ox = bx0 as f32; |
| 945 | let oy = by0 as f32; |
| 946 | let shift = |v: &mut zeno::Vector| { |
| 947 | v.x -= ox; |
| 948 | v.y -= oy; |
| 949 | }; |
| 950 | for cmd in &mut cmds { |
| 951 | match cmd { |
| 952 | zeno::Command::MoveTo(p) | zeno::Command::LineTo(p) => shift(p), |
| 953 | zeno::Command::QuadTo(c, p) => { |
| 954 | shift(c); |
| 955 | shift(p); |
| 956 | } |
| 957 | zeno::Command::CurveTo(c1, c2, p) => { |
| 958 | shift(c1); |
| 959 | shift(c2); |
| 960 | shift(p); |
| 961 | } |
| 962 | zeno::Command::Close => {} |
| 963 | } |
| 964 | } |
| 965 | } |
| 966 | Some(([bx0, by0, bx1, by1], cmds)) |
| 967 | } |
| 968 | |
| 969 | #[cfg(test)] |
| 970 | mod tests { |
| 971 | use super::*; |
| 972 | |
| 973 | /// Runs `MaskCombine` over 4 pixels with alpha bytes `cur` against `prev`. |
| 974 | fn combine(paint_mode: &str, invert: bool, level: f32, prev: [u8; 4], cur: [u8; 4]) -> Vec<u8> { |
| 975 | let eng = Engine::new_headless().expect("gpu"); |
| 976 | let comp = Comp::from_fusion_str(&format!( |
| 977 | "Composition {{ Tools = ordered() {{ M = EllipseMask {{ Inputs = {{ PaintMode = Input {{ Value = FuID {{ \"{paint_mode}\" }}, }}, }}, }}, }}, }}" |
| 978 | )) |
| 979 | .expect("parse"); |
| 980 | let mode = Engine::paint_mode_id(comp.node(comp.find_node("M").unwrap())); |
| 981 | let upload = |a: [u8; 4]| { |
| 982 | let tex = create_texture(&eng.device, [4, 1], 0); |
| 983 | let px: Vec<u8> = a.iter().flat_map(|&v| [v, v, v, v]).collect(); |
| 984 | eng.queue.write_texture( |
| 985 | tex.texture.as_image_copy(), |
| 986 | &px, |
| 987 | wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(16), rows_per_image: Some(1) }, |
| 988 | wgpu::Extent3d { width: 4, height: 1, depth_or_array_layers: 1 }, |
| 989 | ); |
| 990 | tex |
| 991 | }; |
| 992 | let (prev, cur, dst) = (upload(prev), upload(cur), create_texture(&eng.device, [4, 1], 0)); |
| 993 | let mut u = UniformParams::default(); |
| 994 | u.p[0] = [mode, f32::from(u8::from(invert)), level, 1.0]; |
| 995 | let mut enc = eng.device.create_command_encoder(&Default::default()); |
| 996 | eng.dispatch_op(&mut enc, ShaderOp::MaskCombine, &cur.view, &eng.dummy.view, &prev.view, &dst, &u); |
| 997 | eng.queue.submit(Some(enc.finish())); |
| 998 | eng.readback_rgba(&dst).expect("readback").chunks(4).map(|p| p[3]).collect() |
| 999 | } |
| 1000 | |
| 1001 | fn assert_close(got: &[u8], want: [u8; 4]) { |
| 1002 | assert!(got.iter().zip(want).all(|(&g, w)| g.abs_diff(w) <= 1), "got {got:?}, want {want:?}"); |
| 1003 | } |
| 1004 | |
| 1005 | #[test] |
| 1006 | fn average_is_arithmetic_mean_of_prev_and_cur() { |
| 1007 | assert_close(&combine("Average", false, 1.0, [255, 0, 255, 128], [0, 204, 204, 255]), [128, 102, 230, 192]); |
| 1008 | } |
| 1009 | |
| 1010 | #[test] |
| 1011 | fn average_applies_level_before_averaging() { |
| 1012 | assert_close(&combine("Average", false, 0.8, [255, 0, 0, 0], [255, 255, 0, 0]), [230, 102, 0, 0]); |
| 1013 | } |
| 1014 | |
| 1015 | #[test] |
| 1016 | fn replace_overwrites_prev_only_where_cur_has_extent() { |
| 1017 | assert_close(&combine("Replace", false, 1.0, [255, 0, 255, 128], [0, 204, 204, 0]), [255, 204, 204, 128]); |
| 1018 | } |
| 1019 | |
| 1020 | #[test] |
| 1021 | fn replace_uses_level_and_invert_for_extent() { |
| 1022 | assert_close(&combine("Replace", false, 0.8, [100; 4], [255, 0, 128, 0]), [204, 100, 102, 100]); |
| 1023 | assert_close(&combine("Replace", true, 1.0, [100; 4], [255, 0, 0, 255]), [100, 255, 255, 100]); |
| 1024 | } |
| 1025 | |
| 1026 | fn gray_row(vals: &[u8]) -> Vec<u8> { |
| 1027 | vals.iter().flat_map(|&v| [v, v, v, 255]).collect() |
| 1028 | } |
| 1029 | |
| 1030 | fn alphas(px: &[u8]) -> Vec<u8> { |
| 1031 | px.chunks(4).map(|p| p[3]).collect() |
| 1032 | } |
| 1033 | |
| 1034 | #[test] |
| 1035 | fn wand_range_soft_edge_falls_off_linearly() { |
| 1036 | // Channel 1 (Red) compares |r - sr| against half-scale range (0.1) and soft (0.2). |
| 1037 | // Distances from seed 0: 0, 25/255 (~0.098 <= 0.1), 51/255 (0.2), 76/255 (~0.298), 102/255 (0.4). |
| 1038 | let src = gray_row(&[0, 25, 51, 76, 102]); |
| 1039 | let hard = wand_flood_fill(&src, 5, 1, [0, 0], 0.2, 0.0, 1, 0); |
| 1040 | assert_eq!(alphas(&hard), [255, 255, 0, 0, 0]); |
| 1041 | let soft = wand_flood_fill(&src, 5, 1, [0, 0], 0.2, 0.4, 1, 0); |
| 1042 | let a = alphas(&soft); |
| 1043 | assert_eq!((a[0], a[1], a[2], a[4]), (255, 255, 128, 0)); |
| 1044 | assert!(a[3] <= 3, "falloff reaches 0 at 0.5*(range + soft), got {a:?}"); |
| 1045 | } |
| 1046 | |
| 1047 | #[test] |
| 1048 | fn wand_channel_modes_match_fusion_euclidean_and_per_channel() { |
| 1049 | // Seed=(0, 128, 255, 255); px1=(51, 128, 255, 255) -> dr=0.2; px2=(0, 179, 255, 255) -> dg=0.2. |
| 1050 | let src = vec![0, 128, 255, 255, 51, 128, 255, 255, 0, 179, 255, 255]; |
| 1051 | assert_eq!(alphas(&wand_flood_fill(&src, 3, 1, [0, 0], 0.2, 0.4, 1, 0)), [255, 128, 255]); |
| 1052 | assert_eq!(alphas(&wand_flood_fill(&src, 3, 1, [0, 0], 0.2, 0.4, 2, 0)), [255, 255, 128]); |
| 1053 | // Color mode (Channel=0): Euclidean RGB distance for gray step v=26 (sqrt(3)*0.102=0.177). |
| 1054 | // With r_half=0.1, soft_half=0.2: 1 - (0.177 - 0.1) / 0.2 = 0.617 (~157). |
| 1055 | let gray = gray_row(&[0, 26]); |
| 1056 | let a = alphas(&wand_flood_fill(&gray, 2, 1, [0, 0], 0.2, 0.4, 0, 0)); |
| 1057 | assert!((a[1] as i32 - 157).abs() <= 2, "Euclidean RGB gray falloff got {a:?}"); |
| 1058 | } |
| 1059 | |
| 1060 | #[test] |
| 1061 | fn wand_soft_edge_stays_connected() { |
| 1062 | // The second 0-distance pixel is cut off from the seed by a pixel beyond 0.5*(range + soft). |
| 1063 | let src = gray_row(&[0, 255, 0]); |
| 1064 | assert_eq!(alphas(&wand_flood_fill(&src, 3, 1, [0, 0], 0.2, 0.4, 1, 0)), [255, 0, 0]); |
| 1065 | } |
| 1066 | |
| 1067 | #[test] |
| 1068 | fn invert_flips_prev_in_proportion_to_cur() { |
| 1069 | assert_close(&combine("Invert", false, 1.0, [255, 0, 255, 128], [255, 255, 0, 255]), [0, 255, 255, 127]); |
| 1070 | assert_close(&combine("Invert", false, 1.0, [128, 255, 0, 51], [128, 128, 128, 204]), [128, 127, 128, 173]); |
| 1071 | } |
| 1072 | |
| 1073 | #[test] |
| 1074 | fn wand_color_spaces_range_unclamped_and_oob_seed() { |
| 1075 | // ColorSpace=1 (HLS), Channel=2 (Lightness): seed RGB=(0,0,0) -> L=0; px1=(51,51,51) -> L=0.2; px2=(255,255,255) -> L=1.0. |
| 1076 | let src = gray_row(&[0, 51, 255]); |
| 1077 | assert_eq!(alphas(&wand_flood_fill(&src, 3, 1, [0, 0], 0.2, 0.4, 2, 1)), [255, 128, 0]); |
| 1078 | // ColorSpace=2 (YUV), Channel=1 (Y): same luminance steps. |
| 1079 | assert_eq!(alphas(&wand_flood_fill(&src, 3, 1, [0, 0], 0.2, 0.4, 1, 2)), [255, 128, 0]); |
| 1080 | // Range = 2.0 (> 1.0) halves to 1.0 so full [0..1] lightness range matches. |
| 1081 | assert_eq!(alphas(&wand_flood_fill(&src, 3, 1, [0, 0], 2.0, 0.0, 2, 1)), [255, 255, 255]); |
| 1082 | |
| 1083 | // Comp-level out-of-bounds SelectionPoint yields empty mask, and PaintMode="Ignore" passes previous mask unchanged. |
| 1084 | let comp_src = r#"{ |
| 1085 | Tools = ordered() { |
| 1086 | Bg = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, }, |
| 1087 | WandOob = WandMask { |
| 1088 | Inputs = { |
| 1089 | MaskWidth = Input { Value = 32, }, |
| 1090 | MaskHeight = Input { Value = 32, }, |
| 1091 | SelectionPoint = Input { Value = { 1.5, 0.5 }, }, |
| 1092 | Input = Input { SourceOp = "Bg", Source = "Output", }, |
| 1093 | }, |
| 1094 | }, |
| 1095 | Rect = RectangleMask { |
| 1096 | Inputs = { MaskWidth = Input { Value = 32, }, MaskHeight = Input { Value = 32, }, Width = Input { Value = 0.5, }, Height = Input { Value = 0.5, }, }, |
| 1097 | }, |
| 1098 | EllIgnore = EllipseMask { |
| 1099 | Inputs = { |
| 1100 | MaskWidth = Input { Value = 32, }, |
| 1101 | MaskHeight = Input { Value = 32, }, |
| 1102 | PaintMode = Input { Value = FuID { "Ignore" }, }, |
| 1103 | Width = Input { Value = 0.9, }, |
| 1104 | Height = Input { Value = 0.9, }, |
| 1105 | EffectMask = Input { SourceOp = "Rect", Source = "Mask", }, |
| 1106 | }, |
| 1107 | }, |
| 1108 | } |
| 1109 | }"#; |
| 1110 | let comp = Comp::from_fusion_str(comp_src).expect("parse mask comp"); |
| 1111 | let Ok(mut eng) = Engine::new_headless() else { |
| 1112 | return; |
| 1113 | }; |
| 1114 | let (oob_tex, _) = eng.evaluate(&comp, comp.find_node("WandOob").unwrap(), 0.0); |
| 1115 | let oob_px = eng.readback_rgba(&oob_tex).unwrap(); |
| 1116 | assert!(oob_px.iter().all(|&b| b == 0), "OOB WandMask should return empty zero mask"); |
| 1117 | let (rect_tex, _) = eng.evaluate(&comp, comp.find_node("Rect").unwrap(), 0.0); |
| 1118 | let (ign_tex, _) = eng.evaluate(&comp, comp.find_node("EllIgnore").unwrap(), 0.0); |
| 1119 | assert_eq!(eng.readback_rgba(&rect_tex).unwrap(), eng.readback_rgba(&ign_tex).unwrap()); |
| 1120 | } |
| 1121 | |
| 1122 | #[test] |
| 1123 | fn polyline_empty_with_invert_and_level_fills_scaled_alpha() { |
| 1124 | let comp_src = r#"{ |
| 1125 | Tools = ordered() { |
| 1126 | Poly = PolylineMask { |
| 1127 | Inputs = { |
| 1128 | MaskWidth = Input { Value = 32, }, |
| 1129 | MaskHeight = Input { Value = 32, }, |
| 1130 | Invert = Input { Value = 1, }, |
| 1131 | Level = Input { Value = 0.5, }, |
| 1132 | }, |
| 1133 | }, |
| 1134 | } |
| 1135 | }"#; |
| 1136 | let comp = Comp::from_fusion_str(comp_src).expect("parse empty polyline comp"); |
| 1137 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 1138 | let (tex, _) = eng.evaluate(&comp, comp.find_node("Poly").unwrap(), 0.0); |
| 1139 | let px = eng.readback_rgba(&tex).unwrap(); |
| 1140 | assert!((px[3] as i32 - 128).abs() <= 2, "expected ~128 alpha, got {}", px[3]); |
| 1141 | } |
| 1142 | |
| 1143 | #[test] |
| 1144 | fn bitmap_and_wand_ignore_image_effect_mask_and_invert_before_soft_edge() { |
| 1145 | let comp_src = r#"{ |
| 1146 | Tools = ordered() { |
| 1147 | Bg = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftAlpha = Input { Value = 0, }, }, }, |
| 1148 | Full = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, }, |
| 1149 | Rect = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 0.5, }, Height = Input { Value = 0.5, }, }, }, |
| 1150 | -- Non-mask Output on EffectMask must be ignored by BitmapMask/WandMask. |
| 1151 | BmpIgn = BitmapMask { |
| 1152 | Inputs = { |
| 1153 | MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, |
| 1154 | Channel = Input { Value = FuID { "Red" }, }, |
| 1155 | Image = Input { SourceOp = "Full", Source = "Output", }, |
| 1156 | EffectMask = Input { SourceOp = "Bg", Source = "Output", }, |
| 1157 | }, |
| 1158 | }, |
| 1159 | -- Mask Output on EffectMask still chains, and Invert=1 runs before SoftEdge with ClippingMode=None. |
| 1160 | BmpSoftInv = BitmapMask { |
| 1161 | Inputs = { |
| 1162 | MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, |
| 1163 | Channel = Input { Value = FuID { "Red" }, }, |
| 1164 | Invert = Input { Value = 1, }, |
| 1165 | SoftEdge = Input { Value = 0.25, }, |
| 1166 | ClippingMode = Input { Value = FuID { "None" }, }, |
| 1167 | Image = Input { SourceOp = "Full", Source = "Output", }, |
| 1168 | }, |
| 1169 | }, |
| 1170 | WandIgn = WandMask { |
| 1171 | Inputs = { |
| 1172 | MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, |
| 1173 | SelectionPoint = Input { Value = { 0.5, 0.5 }, }, |
| 1174 | Input = Input { SourceOp = "Full", Source = "Output", }, |
| 1175 | EffectMask = Input { SourceOp = "Bg", Source = "Output", }, |
| 1176 | }, |
| 1177 | }, |
| 1178 | WandChain = WandMask { |
| 1179 | Inputs = { |
| 1180 | MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, |
| 1181 | SelectionPoint = Input { Value = { 0.5, 0.5 }, }, |
| 1182 | Input = Input { SourceOp = "Full", Source = "Output", }, |
| 1183 | EffectMask = Input { SourceOp = "Rect", Source = "Mask", }, |
| 1184 | }, |
| 1185 | }, |
| 1186 | } |
| 1187 | }"#; |
| 1188 | let comp = Comp::from_fusion_str(comp_src).expect("parse mask comp"); |
| 1189 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 1190 | let (t_bi, _) = eng.evaluate(&comp, comp.find_node("BmpIgn").unwrap(), 0.0); |
| 1191 | let bmp_ign = eng.readback_rgba(&t_bi).unwrap(); |
| 1192 | assert_eq!(bmp_ign[3], 255, "BitmapMask should ignore Background.Output on EffectMask"); |
| 1193 | let (t_bsi, _) = eng.evaluate(&comp, comp.find_node("BmpSoftInv").unwrap(), 0.0); |
| 1194 | let bmp_si = eng.readback_rgba(&t_bsi).unwrap(); |
| 1195 | assert_eq!(bmp_si[3], 0, "Invert=1 before SoftEdge with ClippingMode=None keeps corner dark: {}", bmp_si[3]); |
| 1196 | let (t_wi, _) = eng.evaluate(&comp, comp.find_node("WandIgn").unwrap(), 0.0); |
| 1197 | let wand_ign = eng.readback_rgba(&t_wi).unwrap(); |
| 1198 | assert_eq!(wand_ign[3], 255, "WandMask should ignore Background.Output on EffectMask"); |
| 1199 | let (t_wc, _) = eng.evaluate(&comp, comp.find_node("WandChain").unwrap(), 0.0); |
| 1200 | let wand_chain = eng.readback_rgba(&t_wc).unwrap(); |
| 1201 | assert_eq!(wand_chain[3], 255); |
| 1202 | } |
| 1203 | |
| 1204 | #[test] |
| 1205 | fn polyline_mask_tight_bbox_matches_full_canvas_across_invert_soft_edge_and_oob() { |
| 1206 | let comp_src = r#"{ |
| 1207 | Tools = ordered() { |
| 1208 | PolySmall = PolylineMask { |
| 1209 | Inputs = { |
| 1210 | MaskWidth = Input { Value = 96, }, MaskHeight = Input { Value = 64, }, |
| 1211 | Center = Input { Value = { 0.65, 0.35 }, }, |
| 1212 | Angle = Input { Value = 22.0, }, |
| 1213 | Polyline = Input { |
| 1214 | Value = Polyline { |
| 1215 | Closed = true, |
| 1216 | Points = { |
| 1217 | { Linear = true, X = -0.1, Y = -0.1 }, |
| 1218 | { Linear = true, X = 0.12, Y = -0.05 }, |
| 1219 | { Linear = true, X = 0.08, Y = 0.12 }, |
| 1220 | { Linear = true, X = -0.08, Y = 0.1 }, |
| 1221 | } |
| 1222 | }, |
| 1223 | }, |
| 1224 | }, |
| 1225 | }, |
| 1226 | PolyInvertLevel = PolylineMask { |
| 1227 | Inputs = { |
| 1228 | MaskWidth = Input { Value = 96, }, MaskHeight = Input { Value = 64, }, |
| 1229 | Center = Input { Value = { 0.5, 0.5 }, }, |
| 1230 | Invert = Input { Value = 1, }, |
| 1231 | Level = Input { Value = 0.75, }, |
| 1232 | Polyline = Input { |
| 1233 | Value = Polyline { |
| 1234 | Closed = true, |
| 1235 | Points = { |
| 1236 | { Linear = true, X = -0.15, Y = -0.15 }, |
| 1237 | { Linear = true, X = 0.15, Y = -0.15 }, |
| 1238 | { Linear = true, X = 0.15, Y = 0.15 }, |
| 1239 | { Linear = true, X = -0.15, Y = 0.15 }, |
| 1240 | } |
| 1241 | }, |
| 1242 | }, |
| 1243 | }, |
| 1244 | }, |
| 1245 | PolySoft = PolylineMask { |
| 1246 | Inputs = { |
| 1247 | MaskWidth = Input { Value = 96, }, MaskHeight = Input { Value = 64, }, |
| 1248 | SoftEdge = Input { Value = 0.06, }, |
| 1249 | ClippingMode = Input { Value = FuID { "None" }, }, |
| 1250 | Polyline = Input { |
| 1251 | Value = Polyline { |
| 1252 | Closed = true, |
| 1253 | Points = { |
| 1254 | { Linear = true, X = -0.1, Y = -0.1 }, |
| 1255 | { Linear = true, X = 0.1, Y = -0.1 }, |
| 1256 | { Linear = true, X = 0.1, Y = 0.1 }, |
| 1257 | { Linear = true, X = -0.1, Y = 0.1 }, |
| 1258 | } |
| 1259 | }, |
| 1260 | }, |
| 1261 | }, |
| 1262 | }, |
| 1263 | PolyPartialOob = PolylineMask { |
| 1264 | Inputs = { |
| 1265 | MaskWidth = Input { Value = 96, }, MaskHeight = Input { Value = 64, }, |
| 1266 | Polyline = Input { |
| 1267 | Value = Polyline { |
| 1268 | Closed = true, |
| 1269 | Points = { |
| 1270 | { Linear = true, X = -0.8, Y = -0.2 }, |
| 1271 | { Linear = true, X = -0.2, Y = -0.2 }, |
| 1272 | { Linear = true, X = -0.2, Y = 0.2 }, |
| 1273 | { Linear = true, X = -0.8, Y = 0.2 }, |
| 1274 | } |
| 1275 | }, |
| 1276 | }, |
| 1277 | }, |
| 1278 | }, |
| 1279 | PolyAllOob = PolylineMask { |
| 1280 | Inputs = { |
| 1281 | MaskWidth = Input { Value = 96, }, MaskHeight = Input { Value = 64, }, |
| 1282 | Polyline = Input { |
| 1283 | Value = Polyline { |
| 1284 | Closed = true, |
| 1285 | Points = { |
| 1286 | { Linear = true, X = 1.2, Y = 0.0 }, |
| 1287 | { Linear = true, X = 1.5, Y = 0.0 }, |
| 1288 | { Linear = true, X = 1.5, Y = 0.3 }, |
| 1289 | { Linear = true, X = 1.2, Y = 0.3 }, |
| 1290 | } |
| 1291 | }, |
| 1292 | }, |
| 1293 | }, |
| 1294 | }, |
| 1295 | PolyCoverAll = PolylineMask { |
| 1296 | Inputs = { |
| 1297 | MaskWidth = Input { Value = 96, }, MaskHeight = Input { Value = 64, }, |
| 1298 | Polyline = Input { |
| 1299 | Value = Polyline { |
| 1300 | Closed = true, |
| 1301 | Points = { |
| 1302 | { Linear = true, X = -1.0, Y = -1.0 }, |
| 1303 | { Linear = true, X = 1.0, Y = -1.0 }, |
| 1304 | { Linear = true, X = 1.0, Y = 1.0 }, |
| 1305 | { Linear = true, X = -1.0, Y = 1.0 }, |
| 1306 | } |
| 1307 | }, |
| 1308 | }, |
| 1309 | }, |
| 1310 | }, |
| 1311 | } |
| 1312 | }"#; |
| 1313 | let comp = Comp::from_fusion_str(comp_src).expect("parse polyline comp"); |
| 1314 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 1315 | |
| 1316 | let check_hard = |eng: &mut Engine, name: &str, center: [f32; 2], angle: f32, invert: bool, level: f32| { |
| 1317 | let nid = comp.find_node(name).unwrap(); |
| 1318 | let pts = Engine::polyline_points(&comp, comp.node(nid), 0.0); |
| 1319 | let expected = rasterize_polyline_mask([96, 64], &pts, center, angle, invert, level); |
| 1320 | let (tex, _) = eng.evaluate(&comp, nid, 0.0); |
| 1321 | let got = eng.readback_rgba(&tex).unwrap(); |
| 1322 | for (i, (&g, &e)) in got.iter().zip(expected.iter()).enumerate() { |
| 1323 | assert!(g.abs_diff(e) <= 1, "{name} byte {i}: got {g}, expected {e}"); |
| 1324 | } |
| 1325 | }; |
| 1326 | |
| 1327 | check_hard(&mut eng, "PolySmall", [0.65, 0.35], 22.0, false, 1.0); |
| 1328 | check_hard(&mut eng, "PolyInvertLevel", [0.5, 0.5], 0.0, true, 0.75); |
| 1329 | check_hard(&mut eng, "PolyPartialOob", [0.5, 0.5], 0.0, false, 1.0); |
| 1330 | check_hard(&mut eng, "PolyAllOob", [0.5, 0.5], 0.0, false, 1.0); |
| 1331 | check_hard(&mut eng, "PolyCoverAll", [0.5, 0.5], 0.0, false, 1.0); |
| 1332 | |
| 1333 | // SoftEdge > 0: compare GPU-blurred tight upload against full-canvas upload_cpu_mask. |
| 1334 | let soft_id = comp.find_node("PolySoft").unwrap(); |
| 1335 | let soft_pts = Engine::polyline_points(&comp, comp.node(soft_id), 0.0); |
| 1336 | let full_raw = rasterize_polyline_mask([96, 64], &soft_pts, [0.5, 0.5], 0.0, false, 1.0); |
| 1337 | let mut enc = eng.device.create_command_encoder(&Default::default()); |
| 1338 | let ref_tex = eng.upload_cpu_mask( |
| 1339 | &mut enc, |
| 1340 | [96, 64], |
| 1341 | 0, |
| 1342 | &full_raw, |
| 1343 | Some(MaskPost { |
| 1344 | soft_px: 0.06 * 96.0, |
| 1345 | is_box: false, |
| 1346 | clamp_edges: 0.0, |
| 1347 | paint_mode: 0.0, |
| 1348 | invert: false, |
| 1349 | level: 1.0, |
| 1350 | prev: None, |
| 1351 | }), |
| 1352 | ); |
| 1353 | eng.queue.submit(Some(enc.finish())); |
| 1354 | let ref_px = eng.readback_rgba(&ref_tex).unwrap(); |
| 1355 | let (soft_tex, _) = eng.evaluate(&comp, soft_id, 0.0); |
| 1356 | let soft_px = eng.readback_rgba(&soft_tex).unwrap(); |
| 1357 | assert_eq!(soft_px, ref_px, "SoftEdge PolylineMask must match full-canvas pixel-for-pixel"); |
| 1358 | } |
| 1359 | |
| 1360 | #[test] |
| 1361 | fn polyline_mask_larger_than_max_texture_dimension_rasterizes_into_clamped_size() { |
| 1362 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 1363 | let max_dim = eng.device.limits().max_texture_dimension_2d.max(1); |
| 1364 | let req_w = max_dim * 2; |
| 1365 | let comp_src = format!( |
| 1366 | r#"{{ |
| 1367 | Tools = ordered() {{ |
| 1368 | BigPoly = PolylineMask {{ |
| 1369 | Inputs = {{ |
| 1370 | MaskWidth = Input {{ Value = {req_w}, }}, |
| 1371 | MaskHeight = Input {{ Value = 32, }}, |
| 1372 | Polyline = Input {{ |
| 1373 | Value = Polyline {{ |
| 1374 | Closed = true, |
| 1375 | Points = {{ |
| 1376 | {{ Linear = true, X = -0.25, Y = -0.25 }}, |
| 1377 | {{ Linear = true, X = 0.25, Y = -0.25 }}, |
| 1378 | {{ Linear = true, X = 0.25, Y = 0.25 }}, |
| 1379 | {{ Linear = true, X = -0.25, Y = 0.25 }}, |
| 1380 | }} |
| 1381 | }}, |
| 1382 | }}, |
| 1383 | }}, |
| 1384 | }}, |
| 1385 | }} |
| 1386 | }}"# |
| 1387 | ); |
| 1388 | let comp = Comp::from_fusion_str(&comp_src).expect("parse clamped polyline comp"); |
| 1389 | let (tex, _) = eng.evaluate(&comp, comp.find_node("BigPoly").unwrap(), 0.0); |
| 1390 | assert_eq!(tex.size, [max_dim, 16]); |
| 1391 | let px = eng.readback_rgba(&tex).unwrap(); |
| 1392 | assert!(px.chunks_exact(4).any(|c| c[3] > 200), "clamped PolylineMask must rasterize cleanly instead of clearing to transparent"); |
| 1393 | } |
| 1394 | |
| 1395 | #[test] |
| 1396 | fn bitmap_mask_fit_input_modes_and_coverage_channel() { |
| 1397 | // Source is 16x32 solid white; destination mask is 32x16: |
| 1398 | // - Crop: 16px wide centered -> x=2 is 0, x=16 is 255 |
| 1399 | // - Stretch / Width / Outside: fills full width -> x=2 is 255 |
| 1400 | // - Inside / Height: uniform scale = 16/32 = 0.5 -> 8px wide centered (x=12..20) -> x=10 is 0, x=16 is 255 |
| 1401 | // - Coverage channel: returns 0 mask cleanly |
| 1402 | let comp_src = r#"{ |
| 1403 | Tools = ordered() { |
| 1404 | Src = Background { |
| 1405 | Inputs = { |
| 1406 | Width = Input { Value = 16, }, |
| 1407 | Height = Input { Value = 32, }, |
| 1408 | TopLeftRed = Input { Value = 1, }, |
| 1409 | TopLeftGreen = Input { Value = 1, }, |
| 1410 | TopLeftBlue = Input { Value = 1, }, |
| 1411 | TopLeftAlpha = Input { Value = 1, }, |
| 1412 | }, |
| 1413 | }, |
| 1414 | BCrop = BitmapMask { |
| 1415 | Inputs = { |
| 1416 | OutputSize = Input { Value = FuID { "Custom" }, }, |
| 1417 | MaskWidth = Input { Value = 32, }, MaskHeight = Input { Value = 16, }, |
| 1418 | FitInput = Input { Value = FuID { "Crop" }, }, |
| 1419 | Image = Input { SourceOp = "Src", Source = "Output", }, |
| 1420 | }, |
| 1421 | }, |
| 1422 | BStretch = BitmapMask { |
| 1423 | Inputs = { |
| 1424 | OutputSize = Input { Value = FuID { "Custom" }, }, |
| 1425 | MaskWidth = Input { Value = 32, }, MaskHeight = Input { Value = 16, }, |
| 1426 | FitInput = Input { Value = FuID { "Stretch" }, }, |
| 1427 | Image = Input { SourceOp = "Src", Source = "Output", }, |
| 1428 | }, |
| 1429 | }, |
| 1430 | BInside = BitmapMask { |
| 1431 | Inputs = { |
| 1432 | OutputSize = Input { Value = FuID { "Custom" }, }, |
| 1433 | MaskWidth = Input { Value = 32, }, MaskHeight = Input { Value = 16, }, |
| 1434 | FitInput = Input { Value = FuID { "Inside" }, }, |
| 1435 | Image = Input { SourceOp = "Src", Source = "Output", }, |
| 1436 | }, |
| 1437 | }, |
| 1438 | BOutside = BitmapMask { |
| 1439 | Inputs = { |
| 1440 | OutputSize = Input { Value = FuID { "Custom" }, }, |
| 1441 | MaskWidth = Input { Value = 32, }, MaskHeight = Input { Value = 16, }, |
| 1442 | FitInput = Input { Value = FuID { "Outside" }, }, |
| 1443 | Image = Input { SourceOp = "Src", Source = "Output", }, |
| 1444 | }, |
| 1445 | }, |
| 1446 | BCov = BitmapMask { |
| 1447 | Inputs = { |
| 1448 | OutputSize = Input { Value = FuID { "Custom" }, }, |
| 1449 | MaskWidth = Input { Value = 32, }, MaskHeight = Input { Value = 16, }, |
| 1450 | Channel = Input { Value = FuID { "Coverage" }, }, |
| 1451 | Image = Input { SourceOp = "Src", Source = "Output", }, |
| 1452 | }, |
| 1453 | }, |
| 1454 | } |
| 1455 | }"#; |
| 1456 | let comp = Comp::from_fusion_str(comp_src).expect("parse BitmapMask FitInput comp"); |
| 1457 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 1458 | let sample = |eng: &mut Engine, name: &str, x: usize, y: usize| -> u8 { |
| 1459 | let (tex, _) = eng.evaluate(&comp, comp.find_node(name).unwrap(), 0.0); |
| 1460 | let px = eng.readback_rgba(&tex).unwrap(); |
| 1461 | px[(y * 32 + x) * 4 + 3] |
| 1462 | }; |
| 1463 | assert_eq!(sample(&mut eng, "BCrop", 2, 8), 0); |
| 1464 | assert_eq!(sample(&mut eng, "BCrop", 10, 8), 255); |
| 1465 | assert_eq!(sample(&mut eng, "BStretch", 2, 8), 255); |
| 1466 | assert_eq!(sample(&mut eng, "BInside", 10, 8), 0); |
| 1467 | assert_eq!(sample(&mut eng, "BInside", 16, 8), 255); |
| 1468 | assert_eq!(sample(&mut eng, "BOutside", 2, 8), 255); |
| 1469 | assert_eq!(sample(&mut eng, "BCov", 16, 8), 0); |
| 1470 | } |
| 1471 | |
| 1472 | #[test] |
| 1473 | fn ellipse_polyline_level_floors_to_u8_and_bitmap_softedge_smooth() { |
| 1474 | let comp_src = r#"{ |
| 1475 | Tools = ordered() { |
| 1476 | El = EllipseMask { |
| 1477 | Inputs = { |
| 1478 | MaskWidth = Input { Value = 32, }, MaskHeight = Input { Value = 32, }, |
| 1479 | Center = Input { Value = { 0.5, 0.5 }, }, |
| 1480 | Width = Input { Value = 0.8, }, Height = Input { Value = 0.8, }, |
| 1481 | Level = Input { Value = 0.44521, }, |
| 1482 | }, |
| 1483 | }, |
| 1484 | PL = PolylineMask { |
| 1485 | Inputs = { |
| 1486 | MaskWidth = Input { Value = 32, }, MaskHeight = Input { Value = 32, }, |
| 1487 | Level = Input { Value = 0.44521, }, |
| 1488 | Polyline = Input { |
| 1489 | Value = Polyline { |
| 1490 | Closed = true, |
| 1491 | Points = { |
| 1492 | { Linear = true, X = -0.3, Y = -0.3 }, |
| 1493 | { Linear = true, X = 0.3, Y = -0.3 }, |
| 1494 | { Linear = true, X = 0.3, Y = 0.3 }, |
| 1495 | { Linear = true, X = -0.3, Y = 0.3 }, |
| 1496 | }, |
| 1497 | }, |
| 1498 | }, |
| 1499 | }, |
| 1500 | }, |
| 1501 | BG = Background { |
| 1502 | Inputs = { |
| 1503 | Width = Input { Value = 32, }, Height = Input { Value = 32, }, |
| 1504 | TopLeftAlpha = Input { Value = 1, }, TopLeftRed = Input { Value = 1, }, |
| 1505 | }, |
| 1506 | }, |
| 1507 | BM = BitmapMask { |
| 1508 | Inputs = { |
| 1509 | SoftEdge = Input { Value = 0.15, }, |
| 1510 | Image = Input { SourceOp = "BG", Source = "Output", }, |
| 1511 | }, |
| 1512 | }, |
| 1513 | } |
| 1514 | }"#; |
| 1515 | let comp = Comp::from_fusion_str(comp_src).expect("parse mask level comp"); |
| 1516 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 1517 | let center_a = |eng: &mut Engine, name: &str| -> u8 { |
| 1518 | let (tex, _) = eng.evaluate(&comp, comp.find_node(name).unwrap(), 0.0); |
| 1519 | let px = eng.readback_rgba(&tex).unwrap(); |
| 1520 | px[(16 * 32 + 16) * 4 + 3] |
| 1521 | }; |
| 1522 | // 0.44521 * 255 = 113.52855 -> Fusion floors to 113 (not 114). |
| 1523 | assert_eq!(center_a(&mut eng, "El"), 113); |
| 1524 | assert_eq!(center_a(&mut eng, "PL"), 113); |
| 1525 | let (bm, _) = eng.evaluate(&comp, comp.find_node("BM").unwrap(), 0.0); |
| 1526 | let bm_px = eng.readback_rgba(&bm).unwrap(); |
| 1527 | assert_eq!(bm_px[(16 * 32 + 16) * 4 + 3], 255); |
| 1528 | } |
| 1529 | } |