1use super::*;
2
3#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4pub(super) enum RoiBox {
5 Empty,
6 Rect { x0: i32, y0: i32, x1: i32, y1: i32 },
7}
8
9impl RoiBox {
10 fn union(self, other: Self) -> Self {
11 match (self, other) {
12 (Self::Empty, r) | (r, Self::Empty) => r,
13 (
14 Self::Rect { x0: ax0, y0: ay0, x1: ax1, y1: ay1 },
15 Self::Rect { x0: bx0, y0: by0, x1: bx1, y1: by1 },
16 ) => Self::Rect {
17 x0: ax0.min(bx0),
18 y0: ay0.min(by0),
19 x1: ax1.max(bx1),
20 y1: ay1.max(by1),
21 },
22 }
23 }
24
25 fn canvas(canvas_size: [u32; 2]) -> Self {
26 Self::Rect {
27 x0: 0,
28 y0: 0,
29 x1: canvas_size[0].max(1) as i32,
30 y1: canvas_size[1].max(1) as i32,
31 }
32 }
33}
34
35/// Expands `[bg0, bg1)` to include `[fg0, fg1)` with a 2px AA apron while
36/// clamping total span to `max_dim` without an artificial symmetric half-cap.
37fn expand_dod_axis(bg0: i32, bg1: i32, fg0: f32, fg1: f32, max_dim: i32) -> (i32, i32) {
38 let want0 = if fg0 < bg0 as f32 - 0.5 { bg0.min(fg0.floor() as i32 - 2) } else { bg0 };
39 let want1 = if fg1 > bg1 as f32 + 0.5 { bg1.max(fg1.ceil() as i32 + 2) } else { bg1 };
40 if want1 - want0 <= max_dim {
41 return (want0, want1);
42 }
43 let bg_span = bg1 - bg0;
44 if bg_span >= max_dim {
45 return (bg0, bg1);
46 }
47 let avail = max_dim - bg_span;
48 let pad0 = bg0 - want0;
49 let pad1 = want1 - bg1;
50 let total_pad = (pad0 + pad1).max(1);
51 let take0 = ((pad0 as i64 * avail as i64) / total_pad as i64) as i32;
52 let take1 = (avail - take0).min(pad1);
53 let take0 = (avail - take1).min(pad0);
54 (bg0 - take0, bg1 + take1)
55}
56
57fn infer_node_canvas_size(
58 comp: &Comp,
59 start_id: NodeId,
60 time: f64,
61 expr: &ExprEngine,
62 comp_dims: [u32; 2],
63 proxy_scale: u32,
64 hiq: bool,
65 depth: usize,
66) -> Option<[u32; 2]> {
67 let mut cur_id = start_id;
68 for _ in 0..depth {
69 let n = comp.node(cur_id);
70 if n.bypassed
71 || matches!(
72 n.kind.as_str(),
73 "PipeRouter"
74 | "Fuse.Wireless"
75 | "Tracker"
76 | "Dimension.OpticalFlow"
77 | "OpticalFlow"
78 | "Dimension.CopyAux"
79 | "ColorCorrector"
80 | "ColorCurves"
81 | "BrightnessContrast"
82 | "ColorGain"
83 | "InvertColor"
84 | "GamutConvert"
85 | "HueCurves"
86 | "ChangeDepth"
87 | "LumaKeyer"
88 | "UltraKeyer"
89 | "DeltaKeyer"
90 | "Blur"
91 | "DirectionalBlur"
92 | "Glow"
93 | "SoftGlow"
94 | "Fuse.XGlow"
95 | "Filter"
96 | "Sharpen"
97 | "ErodeDilate"
98 | "Transform"
99 | "Displace"
100 )
101 {
102 let port = default_main_input_port(&n.kind);
103 cur_id = n.connected_node(port).and_then(|s| comp.find_node(s))?;
104 continue;
105 }
106 match n.kind.as_str() {
107 "MacroOperator" | "GroupOperator" => {
108 cur_id = n.macro_output?;
109 }
110 "Custom" => {
111 if let Some(img1_id) = n.connected_node("Image1").and_then(|s| comp.find_node(s)) {
112 cur_id = img1_id;
113 } else {
114 return Some(comp_dims);
115 }
116 }
117 "Merge" | "ChannelBoolean" | "Dissolve" => {
118 cur_id = n.connected_node("Background").and_then(|s| comp.find_node(s))?;
119 }
120 "Fuse.Colorize" => {
121 cur_id = n
122 .connected_node("Image")
123 .or_else(|| n.connected_node("Input"))
124 .and_then(|s| comp.find_node(s))?;
125 }
126 "Background" | "FastNoise" | "Plasma" | "DaySky" => {
127 if Engine::resolve_effect_mask_id(comp, n).is_some()
128 || comp.eval_number(n, "UseFrameFormatSettings", time, 0.0, expr) > 0.5
129 {
130 return None;
131 }
132 if !n.inputs.contains_key("Width") && !n.inputs.contains_key("Height") {
133 return Some(comp_dims);
134 }
135 let w = comp.eval_number(n, "Width", time, comp.width as f64, expr).round().max(1.0) as u32;
136 let h = comp.eval_number(n, "Height", time, comp.height as f64, expr).round().max(1.0) as u32;
137 if matches!(n.kind.as_str(), "Background" | "FastNoise") && (w < 16 || h < 16) {
138 return Some(comp_dims);
139 }
140 let s = proxy_scale.max(1);
141 let scaled = [(w / s).max(1), (h / s).max(1)];
142 if n.kind == "FastNoise" {
143 let cap = if hiq { 8192 } else { 4096 };
144 if scaled[0].max(scaled[1]) > cap {
145 return None;
146 }
147 }
148 return Some(scaled);
149 }
150 _ => return None,
151 }
152 }
153 None
154}
155
156fn inverse_transform_box(
157 comp: &Comp,
158 node: &Node,
159 time: f64,
160 expr: &ExprEngine,
161 canvas_size: [u32; 2],
162 has_mask: bool,
163 blend: f32,
164 downstream: RoiBox,
165) -> Option<RoiBox> {
166 let RoiBox::Rect { x0: dx0, y0: dy0, x1: dx1, y1: dy1 } = downstream else {
167 return Some(RoiBox::Empty);
168 };
169 let (dx0, dy0, dx1, dy1) = if has_mask {
170 (
171 dx0.max(0),
172 dy0.max(0),
173 dx1.min(canvas_size[0].max(1) as i32),
174 dy1.min(canvas_size[1].max(1) as i32),
175 )
176 } else {
177 (dx0, dy0, dx1, dy1)
178 };
179 if dx0 >= dx1 || dy0 >= dy1 {
180 return Some(RoiBox::Empty);
181 }
182
183 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], expr);
184 let pivot = comp.eval_point(node, "Pivot", time, [0.5, 0.5], expr);
185 let use_xy = comp.eval_number(node, "UseSizeAndAspect", time, 1.0, expr) < 0.5;
186 let (sx, sy) = if use_xy {
187 (
188 comp.eval_number(node, "XSize", time, 1.0, expr) as f32,
189 comp.eval_number(node, "YSize", time, 1.0, expr) as f32,
190 )
191 } else {
192 let s = comp.eval_number(node, "Size", time, 1.0, expr) as f32;
193 let asp = comp.eval_number(node, "Aspect", time, 1.0, expr) as f32;
194 (s, s * asp)
195 };
196 let angle = (comp.eval_number(node, "Angle", time, 0.0, expr) as f32).to_radians();
197 let flip_h = comp.eval_number(node, "FlipHoriz", time, 0.0, expr) > 0.5;
198 let flip_v = comp.eval_number(node, "FlipVert", time, 0.0, expr) > 0.5;
199
200 if !sx.is_finite()
201 || !sy.is_finite()
202 || !angle.is_finite()
203 || !center[0].is_finite()
204 || !center[1].is_finite()
205 || !pivot[0].is_finite()
206 || !pivot[1].is_finite()
207 || sx <= 1e-4
208 || sy <= 1e-4
209 {
210 return None;
211 }
212
213 let cw = canvas_size[0].max(1) as f32;
214 let ch = canvas_size[1].max(1) as f32;
215 let cx = center[0] as f32;
216 let cy = center[1] as f32;
217 let px = pivot[0] as f32;
218 let py = pivot[1] as f32;
219 let is_identity = (cx - 0.5).abs() < 1e-5
220 && (cy - 0.5).abs() < 1e-5
221 && (sx - 1.0).abs() < 1e-5
222 && (sy - 1.0).abs() < 1e-5
223 && angle.abs() < 1e-5
224 && !flip_h
225 && !flip_v;
226 if is_identity {
227 return Some(RoiBox::Rect { x0: dx0, y0: dy0, x1: dx1, y1: dy1 });
228 }
229
230 let shift_x = cx - 0.5;
231 let shift_y = cy - 0.5;
232 let (s, c) = angle.sin_cos();
233
234 let mut min_x = f32::INFINITY;
235 let mut max_x = f32::NEG_INFINITY;
236 let mut min_y = f32::INFINITY;
237 let mut max_y = f32::NEG_INFINITY;
238 if blend < 1.0 - 1e-5 || has_mask {
239 min_x = dx0 as f32;
240 max_x = dx1 as f32;
241 min_y = dy0 as f32;
242 max_y = dy1 as f32;
243 }
244 for &(x, y) in &[
245 (dx0 as f32, dy0 as f32),
246 (dx1 as f32, dy0 as f32),
247 (dx0 as f32, dy1 as f32),
248 (dx1 as f32, dy1 as f32),
249 ] {
250 let fu_x = x / cw;
251 let fu_y = 1.0 - y / ch;
252 let rel_x = (fu_x - px - shift_x) * cw;
253 let rel_y = (fu_y - py - shift_y) * ch;
254 let unrot_x = rel_x * c + rel_y * s;
255 let unrot_y = -rel_x * s + rel_y * c;
256 let mut sfu_x = unrot_x / sx / cw + px;
257 let mut sfu_y = unrot_y / sy / ch + py;
258 if flip_h {
259 sfu_x = 1.0 - sfu_x;
260 }
261 if flip_v {
262 sfu_y = 1.0 - sfu_y;
263 }
264 let sx_px = sfu_x * cw;
265 let sy_px = (1.0 - sfu_y) * ch;
266 min_x = min_x.min(sx_px);
267 max_x = max_x.max(sx_px);
268 min_y = min_y.min(sy_px);
269 max_y = max_y.max(sy_px);
270 }
271 if !min_x.is_finite() || !max_x.is_finite() || !min_y.is_finite() || !max_y.is_finite() {
272 return None;
273 }
274 let pad = 6;
275 Some(RoiBox::Rect {
276 x0: (min_x.floor() as i32).saturating_sub(pad),
277 y0: (min_y.floor() as i32).saturating_sub(pad),
278 x1: (max_x.ceil() as i32).saturating_add(pad),
279 y1: (max_y.ceil() as i32).saturating_add(pad),
280 })
281}
282
283fn inverse_merge_fg_box(
284 comp: &Comp,
285 node: &Node,
286 time: f64,
287 expr: &ExprEngine,
288 bg_canvas: [u32; 2],
289 fg_canvas: [u32; 2],
290 downstream: RoiBox,
291) -> Option<RoiBox> {
292 let RoiBox::Rect { x0: dx0, y0: dy0, x1: dx1, y1: dy1 } = downstream else {
293 return Some(RoiBox::Empty);
294 };
295 if dx0 >= dx1 || dy0 >= dy1 {
296 return Some(RoiBox::Empty);
297 }
298 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], expr);
299 let size = comp.eval_number(node, "Size", time, 1.0, expr) as f32;
300 let angle = (comp.eval_number(node, "Angle", time, 0.0, expr) as f32).to_radians();
301 let flip_h = comp.eval_number(node, "FlipHoriz", time, 0.0, expr) > 0.5;
302 let flip_v = comp.eval_number(node, "FlipVert", time, 0.0, expr) > 0.5;
303 if !size.is_finite()
304 || !angle.is_finite()
305 || !center[0].is_finite()
306 || !center[1].is_finite()
307 || size <= 1e-4
308 {
309 return None;
310 }
311
312 let bg_cw = bg_canvas[0].max(1) as f32;
313 let bg_ch = bg_canvas[1].max(1) as f32;
314 let fg_cw = fg_canvas[0].max(1) as f32;
315 let fg_ch = fg_canvas[1].max(1) as f32;
316 let cx = center[0] as f32;
317 let cy = center[1] as f32;
318 let is_identity = bg_canvas == fg_canvas
319 && (cx - 0.5).abs() < 1e-5
320 && (cy - 0.5).abs() < 1e-5
321 && (size - 1.0).abs() < 1e-5
322 && angle.abs() < 1e-5
323 && !flip_h
324 && !flip_v;
325 if is_identity {
326 return Some(RoiBox::Rect { x0: dx0, y0: dy0, x1: dx1, y1: dy1 });
327 }
328
329 let (s, c) = angle.sin_cos();
330 let mut min_x = f32::INFINITY;
331 let mut max_x = f32::NEG_INFINITY;
332 let mut min_y = f32::INFINITY;
333 let mut max_y = f32::NEG_INFINITY;
334 for &(x, y) in &[
335 (dx0 as f32, dy0 as f32),
336 (dx1 as f32, dy0 as f32),
337 (dx0 as f32, dy1 as f32),
338 (dx1 as f32, dy1 as f32),
339 ] {
340 let fu_x = x / bg_cw;
341 let fu_y = 1.0 - y / bg_ch;
342 let delta_x = (fu_x - cx) * bg_cw;
343 let delta_y = (fu_y - cy) * bg_ch;
344 let rot_x = (delta_x * c + delta_y * s) / size;
345 let rot_y = (-delta_x * s + delta_y * c) / size;
346 let mut fg_fu_x = rot_x / fg_cw + 0.5;
347 let mut fg_fu_y = rot_y / fg_ch + 0.5;
348 if flip_h {
349 fg_fu_x = 1.0 - fg_fu_x;
350 }
351 if flip_v {
352 fg_fu_y = 1.0 - fg_fu_y;
353 }
354 let sx_px = fg_fu_x * fg_cw;
355 let sy_px = (1.0 - fg_fu_y) * fg_ch;
356 min_x = min_x.min(sx_px);
357 max_x = max_x.max(sx_px);
358 min_y = min_y.min(sy_px);
359 max_y = max_y.max(sy_px);
360 }
361 if !min_x.is_finite() || !max_x.is_finite() || !min_y.is_finite() || !max_y.is_finite() {
362 return None;
363 }
364 let pad = 6;
365 Some(RoiBox::Rect {
366 x0: (min_x.floor() as i32).saturating_sub(pad),
367 y0: (min_y.floor() as i32).saturating_sub(pad),
368 x1: (max_x.ceil() as i32).saturating_add(pad),
369 y1: (max_y.ceil() as i32).saturating_add(pad),
370 })
371}
372
373#[allow(clippy::too_many_arguments)]
374fn roi_for_node(
375 comp: &Comp,
376 node_id: NodeId,
377 canvas_size: [u32; 2],
378 comp_dims: [u32; 2],
379 proxy_scale: u32,
380 time: f64,
381 time_key: i64,
382 hiq: bool,
383 expr: &ExprEngine,
384 consumers: &[Vec<(NodeId, String)>],
385 memo: &mut HashMap<(NodeId, i64), Option<RoiBox>>,
386 visiting: &mut HashSet<NodeId>,
387 depth: usize,
388) -> Option<RoiBox> {
389 if depth == 0 {
390 return None;
391 }
392 let mut mh = DefaultHasher::new();
393 time_key.hash(&mut mh);
394 canvas_size.hash(&mut mh);
395 let memo_key = mh.finish() as i64;
396 if let Some(&cached) = memo.get(&(node_id, memo_key)) {
397 return cached;
398 }
399 if !visiting.insert(node_id) {
400 return None;
401 }
402
403 let node_consumers = &consumers[node_id.0];
404 let res = if node_consumers.is_empty() {
405 Some(RoiBox::canvas(canvas_size))
406 } else {
407 let mut acc = RoiBox::Empty;
408 let mut ok = true;
409 for (cid, port) in node_consumers {
410 if let Some(r) = roi_from_consumer(
411 comp,
412 *cid,
413 port,
414 canvas_size,
415 comp_dims,
416 proxy_scale,
417 time,
418 time_key,
419 hiq,
420 expr,
421 consumers,
422 memo,
423 visiting,
424 depth - 1,
425 ) {
426 acc = acc.union(r);
427 } else {
428 ok = false;
429 break;
430 }
431 }
432 if ok { Some(acc) } else { None }
433 };
434
435 visiting.remove(&node_id);
436 memo.insert((node_id, memo_key), res);
437 res
438}
439
440#[allow(clippy::too_many_arguments)]
441fn roi_from_consumer(
442 comp: &Comp,
443 cid: NodeId,
444 port: &str,
445 canvas_size: [u32; 2],
446 comp_dims: [u32; 2],
447 proxy_scale: u32,
448 time: f64,
449 time_key: i64,
450 hiq: bool,
451 expr: &ExprEngine,
452 consumers: &[Vec<(NodeId, String)>],
453 memo: &mut HashMap<(NodeId, i64), Option<RoiBox>>,
454 visiting: &mut HashSet<NodeId>,
455 depth: usize,
456) -> Option<RoiBox> {
457 if matches!(
458 port,
459 "EffectMask" | "GlowMask" | "Garbage.Matte" | "GarbageMatte" | "Solid.Matte" | "SolidMatte"
460 ) {
461 return None;
462 }
463 let n = comp.node(cid);
464 if port == "__macro_output" {
465 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
466 }
467 if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") {
468 return None;
469 }
470 if n.bypassed
471 || matches!(
472 n.kind.as_str(),
473 "PipeRouter" | "Fuse.Wireless" | "Tracker" | "Dimension.OpticalFlow" | "OpticalFlow" | "Dimension.CopyAux"
474 )
475 {
476 if port == default_main_input_port(&n.kind) {
477 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
478 }
479 return None;
480 }
481
482 match n.kind.as_str() {
483 "Saver" | "MediaOut" => Some(RoiBox::canvas(canvas_size)),
484 "BrightnessContrast" | "ColorCorrector" | "ColorCurves" | "ColorGain" | "InvertColor"
485 | "GamutConvert" | "HueCurves" | "ChangeDepth" | "LumaKeyer" => {
486 let main_ok = port == "Input" || (n.kind == "InvertColor" && port == "Image1");
487 if !main_ok {
488 return None;
489 }
490 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
491 let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some();
492 let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
493 if blend <= 1e-6 && !mbm {
494 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
495 }
496 if has_mask {
497 return Some(RoiBox::canvas(canvas_size));
498 }
499 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
500 }
501 "Fuse.Colorize" => {
502 if port != "Image" && port != "Input" {
503 return None;
504 }
505 if Engine::resolve_effect_mask_id(comp, n).is_some() {
506 return Some(RoiBox::canvas(canvas_size));
507 }
508 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
509 }
510 "ChannelBoolean" => {
511 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
512 let mbm = Engine::resolve_effect_mask_id(comp, n).is_some()
513 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
514 if blend <= 1e-6 && !mbm {
515 return match port {
516 "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth),
517 "Foreground" => Some(RoiBox::Empty),
518 _ => None,
519 };
520 }
521 if port == "Background" || port == "Foreground" {
522 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
523 } else {
524 None
525 }
526 }
527 "DirectionalBlur" => {
528 if port != "Input" {
529 return None;
530 }
531 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
532 let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some();
533 let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
534 if blend <= 1e-6 && !mbm {
535 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
536 }
537 if n.static_str("ClippingMode").unwrap_or("Frame") != "None" || has_mask {
538 Some(RoiBox::canvas(canvas_size))
539 } else {
540 None
541 }
542 }
543 "Dissolve" => {
544 let mix_v = comp.eval_number(n, "Mix", time, 1.0, expr).clamp(0.0, 1.0);
545 let blend = comp.eval_number(n, "Blend", time, 1.0, expr);
546 let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some();
547 let mbm = has_mask && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
548 if (blend <= 1e-6 || mix_v <= 1e-6) && !mbm {
549 return match port {
550 "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth),
551 "Foreground" => Some(RoiBox::Empty),
552 _ => None,
553 };
554 }
555 if mix_v >= 1.0 - 1e-6 && blend >= 1.0 - 1e-6 && !has_mask {
556 return match port {
557 "Foreground" => roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth),
558 "Background" => Some(RoiBox::Empty),
559 _ => None,
560 };
561 }
562 if port == "Background" || port == "Foreground" {
563 Some(RoiBox::canvas(canvas_size))
564 } else {
565 None
566 }
567 }
568 "Scale" | "BetterResize" => {
569 if port != "Input" {
570 return None;
571 }
572 let hiq_only = comp.eval_number(n, "HiQOnly", time, 0.0, expr) > 0.5;
573 if n.kind == "Scale" && !hiq && hiq_only {
574 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
575 } else {
576 Some(RoiBox::canvas(canvas_size))
577 }
578 }
579 "Shadow" | "Glow" | "SoftGlow" | "Fuse.XGlow" | "DeltaKeyer" => {
580 if port != "Input" {
581 return None;
582 }
583 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
584 let mbm = n.kind != "Fuse.XGlow"
585 && Engine::resolve_effect_mask_id(comp, n).is_some()
586 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
587 if blend <= 1e-6 && !mbm {
588 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
589 } else {
590 Some(RoiBox::canvas(canvas_size))
591 }
592 }
593 "Displace" => {
594 if port != "Input" && port != "Foreground" {
595 return None;
596 }
597 let fg_none = n.connected_node("Foreground").and_then(|s| comp.find_node(s)).is_none();
598 let mbm = Engine::resolve_effect_mask_id(comp, n).is_some()
599 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
600 if fg_none && !mbm {
601 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
602 } else {
603 Some(RoiBox::canvas(canvas_size))
604 }
605 }
606 "CameraShake" => {
607 if port != "Input" {
608 return None;
609 }
610 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
611 let strength = comp.eval_number(n, "OverallStrength", time, 1.0, expr);
612 let mbm = Engine::resolve_effect_mask_id(comp, n).is_some()
613 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
614 if (blend <= 1e-6 || strength.abs() <= 1e-6) && !mbm {
615 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
616 } else {
617 None
618 }
619 }
620 "GridWarp" => {
621 if port != "Input" {
622 return None;
623 }
624 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
625 if blend <= 1e-6 {
626 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
627 } else {
628 None
629 }
630 }
631 "Fuse.XfChroma" => {
632 if port != "Input" && port != "Image" {
633 return None;
634 }
635 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
636 if blend <= 1e-6 {
637 roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)
638 } else {
639 None
640 }
641 }
642 "DVE" | "Vortex" | "Drip" | "Dent" | "VariBlur"
643 | "RemoveNoise" | "Fuse.Duplicate" | "Fuse.KScope" | "Fuse.Outline" | "Paint" => {
644 if port != default_main_input_port(&n.kind) && port != "Input" && port != "Image" {
645 return None;
646 }
647 // Conservatively union canvas crop with downstream RoI in case the node short-circuits
648 // on an idle parameter (e.g. Blend = 0, radius = 0, etc.).
649 let down = roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
650 Some(RoiBox::canvas(canvas_size).union(down))
651 }
652 "Custom" => {
653 if port != "Image1" && port != "Image2" && port != "Image3" {
654 return None;
655 }
656 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
657 let mbm = Engine::resolve_effect_mask_id(comp, n).is_some()
658 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
659 if blend <= 1e-6 && !mbm {
660 return match port {
661 "Image1" => roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth),
662 _ => Some(RoiBox::Empty),
663 };
664 }
665 if port == "Image1" {
666 let down = roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
667 Some(RoiBox::canvas(canvas_size).union(down))
668 } else {
669 Some(RoiBox::canvas(canvas_size))
670 }
671 }
672 "ErodeDilate" => {
673 if port != "Input" {
674 return None;
675 }
676 if Engine::resolve_effect_mask_id(comp, n).is_some() {
677 return Some(RoiBox::canvas(canvas_size));
678 }
679 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
680 if blend <= 1e-6 {
681 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
682 }
683 let amount = comp.eval_number(n, "Amount", time, 0.0, expr);
684 let amt_x = comp.eval_number(n, "XAmount", time, amount, expr) as f32;
685 let amt_y = if comp.eval_number(n, "LockXY", time, 1.0, expr) > 0.5 {
686 amt_x
687 } else {
688 comp.eval_number(n, "YAmount", time, amount, expr) as f32
689 };
690 let filter = match comp.eval_number(n, "Filter", time, 0.0, expr).round() {
691 f @ 0.0..=3.0 => f as u32,
692 _ => 0,
693 };
694 let w = canvas_size[0].max(1) as f32;
695 let (rx, ry) = (amt_x.abs() * w, amt_y.abs() * w);
696 if rx < 1e-3 && ry < 1e-3 {
697 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
698 }
699 let down = roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
700 let RoiBox::Rect { x0, y0, x1, y1 } = down else {
701 return Some(RoiBox::Empty);
702 };
703 let tap_pad = |r: f32| -> i32 {
704 if r < 1e-3 {
705 0
706 } else {
707 match filter {
708 1 => (1.0 + std::f32::consts::SQRT_2 * r).ceil().min(160.0) as i32,
709 2 => (3.5 * 0.658 * r).ceil().min(160.0) as i32,
710 3 => r.ceil().min(64.0) as i32,
711 _ => r.ceil().min(160.0) as i32,
712 }
713 }
714 };
715 let pad_x = tap_pad(rx) + 2;
716 let pad_y = tap_pad(ry) + 2;
717 Some(RoiBox::Rect {
718 x0: x0 - pad_x,
719 y0: y0 - pad_y,
720 x1: x1 + pad_x,
721 y1: y1 + pad_y,
722 })
723 }
724 "Blur" => {
725 if port != "Input" {
726 return None;
727 }
728 let lock_xy = comp.eval_number(n, "LockXY", time, 1.0, expr) > 0.5;
729 let filter_name = n.static_str("Filter").unwrap_or("Fast Gaussian");
730 let gauss_k = match filter_name {
731 "Box" => 1.0_f32,
732 "Gaussian" => 1.07_f32,
733 _ => 0.96_f32,
734 };
735 let scale_ref = canvas_size[0].max(1) as f32 / 720.0;
736 let x_raw = comp.eval_number(n, "XBlurSize", time, 1.0, expr) as f32;
737 let y_raw = if lock_xy {
738 x_raw
739 } else {
740 comp.eval_number(n, "YBlurSize", time, 1.0, expr) as f32
741 };
742 let rx = x_raw * scale_ref * gauss_k;
743 let ry = y_raw * scale_ref * gauss_k;
744 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
745 if rx.max(ry) < 0.25 || blend <= 1e-6 {
746 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
747 }
748 if Engine::resolve_effect_mask_id(comp, n).is_some() {
749 return Some(RoiBox::canvas(canvas_size));
750 }
751 if !rx.is_finite() || !ry.is_finite() || rx.abs() * 1.6 > 2048.0 || ry.abs() * 1.6 > 2048.0 {
752 return None;
753 }
754 let down = roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
755 let RoiBox::Rect { x0, y0, x1, y1 } = down else {
756 return Some(RoiBox::Empty);
757 };
758 let pad_x = (rx.abs() * 1.6).ceil() as i32 + 16;
759 let pad_y = (ry.abs() * 1.6).ceil() as i32 + 16;
760 Some(RoiBox::Rect {
761 x0: x0 - pad_x,
762 y0: y0 - pad_y,
763 x1: x1 + pad_x,
764 y1: y1 + pad_y,
765 })
766 }
767 "Transform" => {
768 if port != "Input" {
769 return None;
770 }
771 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
772 if blend <= 1e-6 {
773 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
774 }
775 if comp.eval_number(n, "InvertTransform", time, 0.0, expr) > 0.5 {
776 return None;
777 }
778 let edges = comp.eval_number(n, "Edges", time, 0.0, expr).round() as i32;
779 if edges != 0 {
780 return None;
781 }
782 let has_mask = Engine::resolve_effect_mask_id(comp, n).is_some();
783 let down = roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
784 inverse_transform_box(comp, n, time, expr, canvas_size, has_mask, blend, down)
785 }
786 "Merge" => {
787 let blend = comp.eval_number(n, "Blend", time, 1.0, expr) as f32;
788 let mbm = Engine::resolve_effect_mask_id(comp, n).is_some()
789 && comp.eval_number(n, "MultiplyByMask", time, 0.0, expr) > 0.5;
790 if blend <= 1e-6 && !mbm {
791 return match port {
792 "Background" => roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth),
793 "Foreground" => Some(RoiBox::Empty),
794 _ => None,
795 };
796 }
797 if port == "Background" {
798 return roi_for_node(comp, cid, canvas_size, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth);
799 }
800 if port == "Foreground" {
801 let raw_edges = comp.eval_number(n, "Edges", time, 0.0, expr) as f32;
802 let fg_id = n.connected_node("Foreground").and_then(|s| comp.find_node(s));
803 let edges = if raw_edges < 0.5 {
804 fg_id
805 .and_then(|fid| Engine::flattened_fg_edge_mode(comp, fid, time, expr))
806 .unwrap_or(raw_edges)
807 } else {
808 raw_edges
809 };
810 if edges.round() as i32 != 0 {
811 return None;
812 }
813 let bg_id = n.connected_node("Background").and_then(|s| comp.find_node(s))?;
814 let bg_canvas = infer_node_canvas_size(comp, bg_id, time, expr, comp_dims, proxy_scale, hiq, 64)?;
815 let down = roi_for_node(comp, cid, bg_canvas, comp_dims, proxy_scale, time, time_key, hiq, expr, consumers, memo, visiting, depth)?;
816 return inverse_merge_fg_box(comp, n, time, expr, bg_canvas, canvas_size, down);
817 }
818 None
819 }
820 _ => None,
821 }
822}
823
824impl Engine {
825 fn ensure_frame_consumers(&mut self, comp: &Comp) {
826 if self.frame_consumers.len() == comp.nodes.len() {
827 return;
828 }
829 self.frame_consumers.clear();
830 self.frame_consumers.resize_with(comp.nodes.len(), Vec::new);
831 for n in &comp.nodes {
832 if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") {
833 if let Some(out_id) = n.macro_output {
834 if out_id.0 < self.frame_consumers.len() {
835 self.frame_consumers[out_id.0].push((n.id, "__macro_output".to_owned()));
836 }
837 continue;
838 }
839 }
840 for (port, binding) in &n.inputs {
841 if let Some(src_id) = binding.source_op.as_deref().and_then(|s| comp.find_node(s)) {
842 if src_id.0 < self.frame_consumers.len() {
843 self.frame_consumers[src_id.0].push((n.id, port.clone()));
844 }
845 }
846 }
847 if n.connected_node("EffectMask").is_none() {
848 if let Some(mid) = Self::resolve_effect_mask_id(comp, n) {
849 if mid.0 < self.frame_consumers.len() {
850 self.frame_consumers[mid.0].push((n.id, "EffectMask".to_owned()));
851 }
852 }
853 }
854 }
855 }
856
857 fn merge_downstream_roi_bounds(
858 &mut self,
859 comp: &Comp,
860 merge_id: NodeId,
861 canvas_size: [u32; 2],
862 time: f64,
863 ) -> Option<(i32, i32, i32, i32)> {
864 self.ensure_frame_consumers(comp);
865 let comp_dims = self.scaled_dims(comp.width, comp.height);
866 let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64;
867 let mut visiting = HashSet::new();
868 let res = roi_for_node(
869 comp,
870 merge_id,
871 canvas_size,
872 comp_dims,
873 self.proxy_scale,
874 time,
875 time_key,
876 self.hiq,
877 &self.expr,
878 &self.frame_consumers,
879 &mut self.frame_roi_memo,
880 &mut visiting,
881 32,
882 )?;
883 match res {
884 RoiBox::Rect { x0, y0, x1, y1 } => Some((x0, y0, x1, y1)),
885 RoiBox::Empty => Some((0, 0, canvas_size[0].max(1) as i32, canvas_size[1].max(1) as i32)),
886 }
887 }
888
889 fn flattened_fg_edge_mode(
890 comp: &Comp,
891 fg_id: NodeId,
892 time: f64,
893 expr: &ExprEngine,
894 ) -> Option<f32> {
895 let mut cur_id = fg_id;
896 for _ in 0..24 {
897 let n = comp.node(cur_id);
898 if n.bypassed || matches!(n.kind.as_str(), "PipeRouter" | "Fuse.Wireless") {
899 let port = default_main_input_port(&n.kind);
900 cur_id = n.connected_node(port).and_then(|s| comp.find_node(s))?;
901 continue;
902 }
903 if n.kind == "Transform" {
904 if comp.eval_number(n, "FlattenTransform", time, 0.0, expr) <= 0.5 {
905 return None;
906 }
907 let e = comp.eval_number(n, "Edges", time, 0.0, expr).round() as i32;
908 return (e == 1 || e == 3).then_some(e as f32);
909 }
910 return None;
911 }
912 None
913 }
914
915 pub(super) fn eval_merge(
916 &mut self,
917 comp: &Comp,
918 node: &Node,
919 time: f64,
920 frame_i: i64,
921 enc: &mut wgpu::CommandEncoder,
922 visiting: &mut HashSet<(NodeId, i64)>,
923 stats: &mut EvalStats,
924 ) -> CachedTexture {
925 let bg = match node.connected_node("Background").and_then(|s| comp.find_node(s)) {
926 Some(bid) => self.eval_node(comp, bid, time, enc, visiting, stats),
927 None => return self.dummy.clone(),
928 };
929
930 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
931 let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
932 if blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some()) {
933 // Temporal liveness pruning — don't even evaluate Foreground!
934 stats.pruned_branches += 1;
935 return bg;
936 }
937
938 let fg_node = node.connected_node("Foreground").and_then(|s| comp.find_node(s));
939 let fg = match fg_node {
940 Some(fid) => self.eval_node(comp, fid, time, enc, visiting, stats),
941 None => return bg,
942 };
943
944 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
945 let size_s = comp.eval_number(node, "Size", time, 1.0, &self.expr) as f32;
946 let angle_deg = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32;
947 let gain = (comp.eval_number(node, "Gain", time, 1.0, &self.expr) as f32).clamp(0.0, 1.0);
948 let burn_in = comp.eval_number(node, "BurnIn", time, 0.0, &self.expr) as f32;
949 let sub_add = comp.eval_number(node, "SubtractiveAdditive", time, 1.0, &self.expr) as f32;
950 let raw_edges = comp.eval_number(node, "Edges", time, 0.0, &self.expr) as f32;
951 let edges = if raw_edges < 0.5 {
952 fg_node
953 .and_then(|fid| Self::flattened_fg_edge_mode(comp, fid, time, &self.expr))
954 .unwrap_or(raw_edges)
955 } else {
956 raw_edges
957 };
958 let flip_h = comp.eval_number(node, "FlipHoriz", time, 0.0, &self.expr) as f32;
959 let flip_v = comp.eval_number(node, "FlipVert", time, 0.0, &self.expr) as f32;
960
961 let mode_str = node.static_str("ApplyMode").unwrap_or("Normal");
962 let mode_id = match mode_str {
963 "Screen" => 1.0,
964 "Multiply" => 2.0,
965 "Darken" => 3.0,
966 "Lighten" => 4.0,
967 "Difference" => 5.0,
968 "Exclusion" => 6.0,
969 "Overlay" => 7.0,
970 "Hard Light" => 8.0,
971 "Soft Light" => 9.0,
972 "LinearLight" | "Linear Light" => 10.0,
973 "Color Dodge" => 11.0,
974 "LinearDodge" => 12.0,
975 "VividLight" | "Vivid Light" => 13.0,
976 "Hypotenuse" => 14.0,
977 "DarkerColor" | "Darker Color" => 15.0,
978 "LighterColor" | "Lighter Color" => 16.0,
979 "PinLight" | "Pin Light" => 17.0,
980 "Color Burn" => 18.0,
981 "LinearBurn" | "Linear Burn" => 19.0,
982 "Geometric" => 20.0,
983 "Hue" => 21.0,
984 "Saturation" => 22.0,
985 "Color" => 23.0,
986 "Luminosity" => 24.0,
987 _ => 0.0,
988 };
989 let filter_method = comp.eval_number(node, "FilterMethod", time, 2.0, &self.expr).round() as i32;
990 let nearest = if filter_method == 0 { 1.0 } else { 0.0 };
991 let cubic_filter = if filter_method == 4 { 1.0 } else { 0.0 };
992 let op_id = match node.static_str("Operator").unwrap_or("Over") {
993 "Under" => 1.0,
994 "In" => 2.0,
995 "Held Out" | "HeldOut" => 3.0,
996 "Atop" => 4.0,
997 "XOr" => 5.0,
998 "Conjoint" => 6.0,
999 "Disjoint" => 7.0,
1000 "Mask" => 8.0,
1001 "Stencil" => 9.0,
1002 _ => 0.0, // Over
1003 };
1004 let skip = self.process_skip(comp, node, time);
1005
1006 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(bg.canvas_size), enc, visiting, stats);
1007 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1008
1009 let eff_size = size_s * (bg.tex_scale / fg.tex_scale.max(1e-4));
1010
1011 // Fusion Merge preserves/expands Domain of Definition (DoD) when FG extends outside BG
1012 // (e.g. a grid of tiles placed partly above y=1.0 before a downstream Transform zooms out).
1013 let bg_x0 = bg.origin[0];
1014 let bg_y0 = bg.origin[1];
1015 let bg_x1 = bg.origin[0] + bg.size[0] as i32;
1016 let bg_y1 = bg.origin[1] + bg.size[1] as i32;
1017 let mut dst_origin = bg.origin;
1018 let mut dst_size = bg.size;
1019
1020 let roi_bounds = if bg.tex_scale >= 0.99 && fg.tex_scale >= 0.99 {
1021 self.merge_downstream_roi_bounds(comp, node.id, bg.canvas_size, time).map(|(rx0, ry0, rx1, ry1)| {
1022 if visiting.len() == 1 {
1023 (
1024 rx0.min(0),
1025 ry0.min(0),
1026 rx1.max(bg.canvas_size[0].max(1) as i32),
1027 ry1.max(bg.canvas_size[1].max(1) as i32),
1028 )
1029 } else {
1030 (rx0, ry0, rx1, ry1)
1031 }
1032 })
1033 } else {
1034 None
1035 };
1036
1037 if edges < 0.5
1038 && mask.is_none()
1039 && mode_id == 0.0
1040 && (op_id == 0.0 || op_id == 1.0 || op_id == 5.0 || op_id == 6.0 || op_id == 7.0)
1041 && bg.tex_scale >= 0.99
1042 && eff_size > 1e-4
1043 {
1044 let bg_cw = bg.canvas_size[0].max(1) as f32;
1045 let bg_ch = bg.canvas_size[1].max(1) as f32;
1046 let fg_cw = fg.canvas_size[0].max(1) as f32;
1047 let fg_ch = fg.canvas_size[1].max(1) as f32;
1048 let u0 = fg.origin[0] as f32 / fg_cw;
1049 let u1 = (fg.origin[0] + fg.size[0] as i32) as f32 / fg_cw;
1050 let v0 = 1.0 - (fg.origin[1] + fg.size[1] as i32) as f32 / fg_ch;
1051 let v1 = 1.0 - fg.origin[1] as f32 / fg_ch;
1052 let ang = angle_deg.to_radians();
1053 let (ca, sa) = (ang.cos(), ang.sin());
1054 let mut fg_x0 = f32::INFINITY;
1055 let mut fg_x1 = f32::NEG_INFINITY;
1056 let mut fg_y0 = f32::INFINITY;
1057 let mut fg_y1 = f32::NEG_INFINITY;
1058 for &(fu, fv) in &[(u0, v0), (u1, v0), (u0, v1), (u1, v1)] {
1059 let fu = if flip_h > 0.5 { 1.0 - fu } else { fu };
1060 let fv = if flip_v > 0.5 { 1.0 - fv } else { fv };
1061 let rx = (fu - 0.5) * fg_cw * eff_size;
1062 let ry = (fv - 0.5) * fg_ch * eff_size;
1063 let dx = rx * ca - ry * sa;
1064 let dy = rx * sa + ry * ca;
1065 let px = center[0] as f32 * bg_cw + dx;
1066 let py = (1.0 - center[1] as f32) * bg_ch - dy;
1067 fg_x0 = fg_x0.min(px);
1068 fg_x1 = fg_x1.max(px);
1069 fg_y0 = fg_y0.min(py);
1070 fg_y1 = fg_y1.max(py);
1071 }
1072 let max_dim = self.device.limits().max_texture_dimension_2d.min(8192) as i32;
1073 let (mut ux0, mut ux1) = expand_dod_axis(bg_x0, bg_x1, fg_x0, fg_x1, max_dim);
1074 let (mut uy0, mut uy1) = expand_dod_axis(bg_y0, bg_y1, fg_y0, fg_y1, max_dim);
1075 if let Some((rx0, ry0, rx1, ry1)) = roi_bounds {
1076 let cx0 = ux0.max(rx0);
1077 let cx1 = ux1.min(rx1);
1078 let cy0 = uy0.max(ry0);
1079 let cy1 = uy1.min(ry1);
1080 if cx0 < cx1 && cy0 < cy1 {
1081 ux0 = cx0;
1082 ux1 = cx1;
1083 uy0 = cy0;
1084 uy1 = cy1;
1085 }
1086 }
1087 let uw = (ux1 - ux0).max(1) as u32;
1088 let uh = (uy1 - uy0).max(1) as u32;
1089 if uw <= max_dim as u32 && uh <= max_dim as u32 && (ux0 != bg_x0 || uy0 != bg_y0 || uw != bg.size[0] || uh != bg.size[1]) {
1090 dst_origin = [ux0, uy0];
1091 dst_size = [uw, uh];
1092 }
1093 } else if let Some((rx0, ry0, rx1, ry1)) = roi_bounds {
1094 let cx0 = bg_x0.max(rx0);
1095 let cx1 = bg_x1.min(rx1);
1096 let cy0 = bg_y0.max(ry0);
1097 let cy1 = bg_y1.min(ry1);
1098 if cx0 < cx1
1099 && cy0 < cy1
1100 && (cx0 != bg_x0
1101 || cy0 != bg_y0
1102 || (cx1 - cx0) as u32 != bg.size[0]
1103 || (cy1 - cy0) as u32 != bg.size[1])
1104 {
1105 dst_origin = [cx0, cy0];
1106 dst_size = [(cx1 - cx0) as u32, (cy1 - cy0) as u32];
1107 }
1108 }
1109 let dst_has_dod = dst_origin != [0, 0] || dst_size != bg.canvas_size;
1110
1111 let mut u = UniformParams::default();
1112 u.p[0] = [center[0] as f32, center[1] as f32, eff_size, angle_deg.to_radians()];
1113 u.p[1] = [blend, gain, mode_id, edges];
1114 u.p[2] = [flip_h, flip_v, nearest, op_id];
1115 u.p[3] = [
1116 if mask.is_some() { 1.0 } else { 0.0 },
1117 if mask_inv { 1.0 } else { 0.0 },
1118 fg.canvas_size[0] as f32,
1119 fg.canvas_size[1] as f32,
1120 ];
1121 if fg.has_dod() {
1122 u.p[4] = [
1123 fg.origin[0] as f32,
1124 fg.origin[1] as f32,
1125 fg.canvas_size[0] as f32,
1126 fg.canvas_size[1] as f32,
1127 ];
1128 }
1129 if dst_has_dod {
1130 u.p[5] = [
1131 dst_origin[0] as f32,
1132 dst_origin[1] as f32,
1133 bg.canvas_size[0] as f32,
1134 bg.canvas_size[1] as f32,
1135 ];
1136 }
1137 u.p[6] = [
1138 burn_in,
1139 sub_add,
1140 (bg.origin[0] - dst_origin[0]) as f32,
1141 (bg.origin[1] - dst_origin[1]) as f32,
1142 ];
1143 u.p[7] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0];
1144 u.p[8] = [0.0, cubic_filter, 0.0, 0.0];
1145 u.p[9] = skip;
1146
1147 let bg_has_z = bg.aux.as_ref().and_then(|a| a.z.as_ref()).is_some();
1148 let fg_has_z = fg.aux.as_ref().and_then(|a| a.z.as_ref()).is_some();
1149
1150 // Fast path: when neither BG nor FG has `aux.z`, run the exact existing RGBA Merge unchanged!
1151 if !bg_has_z && !fg_has_z {
1152 let key = self.make_key(
1153 node,
1154 "Merge",
1155 dst_size,
1156 &[bg.content_hash, fg.content_hash, mask_hash],
1157 bytemuck::cast_slice(&u.p[..10]),
1158 );
1159 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1160 stats.cache_hits += 1;
1161 return hit;
1162 }
1163 stats.cache_misses += 1;
1164 stats.nodes_evaluated += 1;
1165
1166 let mut dst = self.alloc_tex_dod(dst_size, dst_origin, bg.canvas_size, bg.depth.max(fg.depth), key);
1167 dst.tex_scale = bg.tex_scale;
1168 let edges_i = edges.round() as i32;
1169 dst.edge_mode = if edges_i == 1 || edges_i == 3 {
1170 Some(edges_i as u8)
1171 } else if mask.is_none() && (blend - 1.0).abs() < 1e-5 && op_id == 0.0 {
1172 bg.edge_mode.or(fg.edge_mode)
1173 } else {
1174 bg.edge_mode
1175 };
1176 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1177 self.dispatch_op(enc, ShaderOp::Merge, &bg.view, &fg.view, mv, &dst, &u);
1178 if bg.aux.is_some() && dst.size == bg.size && dst.origin == bg.origin {
1179 dst.set_aux(bg.aux.clone());
1180 }
1181 self.cache.insert(key, dst.clone(), node.id, frame_i);
1182 return dst;
1183 }
1184
1185 // Depth-aware Merge path (`PerformDepthMerge`, default = 1 in Fusion)
1186 let perform_depth = comp.eval_number(node, "PerformDepthMerge", time, 1.0, &self.expr) != 0.0;
1187 let fg_z_offset = comp.eval_number(node, "ForegroundZOffset", time, 0.0, &self.expr) as f32;
1188 u.p[7] = [
1189 if mbm { 1.0 } else { 0.0 },
1190 if perform_depth { 1.0 } else { 0.0 },
1191 if bg_has_z { 1.0 } else { 0.0 },
1192 if fg_has_z { 1.0 } else { 0.0 },
1193 ];
1194 u.p[8] = [fg_z_offset, cubic_filter, 0.0, 0.0];
1195 u.p[9] = skip;
1196
1197 let key = self.make_key(
1198 node,
1199 "MergeDepth",
1200 dst_size,
1201 &[bg.content_hash, fg.content_hash, mask_hash],
1202 bytemuck::cast_slice(&u.p[..10]),
1203 );
1204 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1205 stats.cache_hits += 1;
1206 return hit;
1207 }
1208 stats.cache_misses += 1;
1209 stats.nodes_evaluated += 1;
1210
1211 let mut dst = self.alloc_tex_dod(dst_size, dst_origin, bg.canvas_size, bg.depth.max(fg.depth), key);
1212 dst.tex_scale = bg.tex_scale;
1213 let edges_i = edges.round() as i32;
1214 dst.edge_mode = if edges_i == 1 || edges_i == 3 {
1215 Some(edges_i as u8)
1216 } else if mask.is_none() && (blend - 1.0).abs() < 1e-5 && op_id == 0.0 {
1217 bg.edge_mode.or(fg.edge_mode)
1218 } else {
1219 bg.edge_mode
1220 };
1221 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1222 self.dispatch_depth_merge(enc, &bg, &fg, mv, &mut dst, &u);
1223 self.cache.insert(key, dst.clone(), node.id, frame_i);
1224 dst
1225 }
1226
1227 pub(super) fn eval_channel_boolean(
1228 &mut self,
1229 comp: &Comp,
1230 node: &Node,
1231 time: f64,
1232 frame_i: i64,
1233 enc: &mut wgpu::CommandEncoder,
1234 visiting: &mut HashSet<(NodeId, i64)>,
1235 stats: &mut EvalStats,
1236 ) -> CachedTexture {
1237 let Some(bg_id) = node.connected_node("Background").and_then(|s| comp.find_node(s)) else {
1238 return self.dummy.clone();
1239 };
1240 let bg = self.eval_node(comp, bg_id, time, enc, visiting, stats);
1241 let op = comp.eval_number(node, "Operation", time, 0.0, &self.expr).round() as i32;
1242 let to_r = comp.eval_number(node, "ToRed", time, 0.0, &self.expr).round() as i32;
1243 let to_g = comp.eval_number(node, "ToGreen", time, 1.0, &self.expr).round() as i32;
1244 let to_b = comp.eval_number(node, "ToBlue", time, 2.0, &self.expr).round() as i32;
1245 let to_a = comp.eval_number(node, "ToAlpha", time, 3.0, &self.expr).round() as i32;
1246 let enable_extra = comp.eval_number(node, "EnableExtraChannels", time, 0.0, &self.expr) >= 0.5;
1247 let to_z = if enable_extra {
1248 comp.eval_number(node, "ToZBuffer", time, 4.0, &self.expr).round() as i32
1249 } else {
1250 4
1251 };
1252 let has_z_op = enable_extra && to_z != 4;
1253 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1254 let mbm = self.multiplies_by_mask(comp, node, time);
1255 if blend <= 1e-6 && !mbm {
1256 return bg;
1257 }
1258 // Fast path: Copy BG R/G/B/A onto itself (or all Do Nothing)
1259 let rgba_is_noop = !mbm
1260 && ((op == 0 && to_r == 5 && to_g == 6 && to_b == 7 && to_a == 8)
1261 || (op == 0 && to_r == 4 && to_g == 4 && to_b == 4 && to_a == 4));
1262 if rgba_is_noop && !has_z_op {
1263 return bg;
1264 }
1265 // When Foreground is unconnected, Fusion uses Background as Foreground
1266 let fg = if let Some(fg_id) = node.connected_node("Foreground").and_then(|s| comp.find_node(s)) {
1267 self.eval_node(comp, fg_id, time, enc, visiting, stats)
1268 } else {
1269 bg.clone()
1270 };
1271 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(bg.canvas_size), enc, visiting, stats);
1272 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1273 let expand_canvas = !rgba_is_noop
1274 && bg.has_dod()
1275 && (op == 10 || op == 11 || op == 14 || [to_r, to_g, to_b, to_a].contains(&16));
1276 let dst_size = if expand_canvas { bg.canvas_size } else { bg.size };
1277 let dst_origin = if expand_canvas { [0, 0] } else { bg.origin };
1278
1279 let mut u = UniformParams::default();
1280 u.p[0] = [op as f32, to_r as f32, to_g as f32, to_b as f32];
1281 u.p[1] = [
1282 to_a as f32,
1283 blend,
1284 if mask.is_some() { 1.0 } else { 0.0 },
1285 if mask_inv { 1.0 } else { 0.0 },
1286 ];
1287 if fg.has_dod() {
1288 u.p[2] = [fg.origin[0] as f32, fg.origin[1] as f32, fg.canvas_size[0] as f32, fg.canvas_size[1] as f32];
1289 }
1290 if bg.has_dod() {
1291 u.p[3] = [bg.origin[0] as f32, bg.origin[1] as f32, bg.canvas_size[0] as f32, bg.canvas_size[1] as f32];
1292 }
1293 u.p[4] = [if expand_canvas { 1.0 } else { 0.0 }, mbm as u8 as f32, 0.0, 0.0];
1294 u.p[5] = self.process_skip(comp, node, time);
1295 let key = if has_z_op {
1296 let mut extra = [0.0f32; 28];
1297 extra[..24].copy_from_slice(bytemuck::cast_slice(&u.p[..6]));
1298 extra[24] = to_z as f32;
1299 extra[25] = if bg.aux.as_ref().and_then(|a| a.z.as_ref()).is_some() { 1.0 } else { 0.0 };
1300 extra[26] = if fg.aux.as_ref().and_then(|a| a.z.as_ref()).is_some() { 1.0 } else { 0.0 };
1301 extra[27] = if rgba_is_noop { 1.0 } else { 0.0 };
1302 self.make_key(node, "ChannelBooleanAux", dst_size, &[bg.content_hash, fg.content_hash, mask_hash], &extra)
1303 } else {
1304 self.make_key(node, "ChannelBoolean", dst_size, &[bg.content_hash, fg.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..6]))
1305 };
1306 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1307 stats.cache_hits += 1;
1308 return hit;
1309 }
1310 stats.cache_misses += 1;
1311 stats.nodes_evaluated += 1;
1312
1313 let mut dst = if rgba_is_noop {
1314 let mut d = bg.clone();
1315 d.content_hash = key;
1316 d
1317 } else {
1318 let mut d = self.alloc_tex_dod(dst_size, dst_origin, bg.canvas_size, bg.depth.max(fg.depth), key);
1319 d.tex_scale = bg.tex_scale;
1320 if op == 11 && (blend - 1.0).abs() < 1e-5 && mask.is_none() && ![to_r, to_g, to_b, to_a].contains(&4) {
1321 d.edge_mode = Some(2);
1322 }
1323 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1324 self.dispatch_op(enc, ShaderOp::ChannelBoolean, &bg.view, &fg.view, mv, &d, &u);
1325 d
1326 };
1327
1328 if has_z_op {
1329 self.apply_channel_boolean_z(
1330 enc,
1331 &bg,
1332 &fg,
1333 mask.as_ref(),
1334 mask_inv,
1335 op,
1336 to_z,
1337 blend,
1338 expand_canvas,
1339 &mut dst,
1340 );
1341 } else if bg.aux.is_some() && dst.size == bg.size {
1342 dst.set_aux(bg.aux.clone());
1343 }
1344 self.cache.insert(key, dst.clone(), node.id, frame_i);
1345 dst
1346 }
1347
1348 pub(super) fn eval_dissolve(
1349 &mut self,
1350 comp: &Comp,
1351 node: &Node,
1352 time: f64,
1353 frame_i: i64,
1354 enc: &mut wgpu::CommandEncoder,
1355 visiting: &mut HashSet<(NodeId, i64)>,
1356 stats: &mut EvalStats,
1357 ) -> CachedTexture {
1358 let Some(bg_id) = node.connected_node("Background").and_then(|s| comp.find_node(s)) else {
1359 return self.dummy.clone();
1360 };
1361 let bg = self.eval_node(comp, bg_id, time, enc, visiting, stats);
1362 let Some(fg_id) = node.connected_node("Foreground").and_then(|s| comp.find_node(s)) else {
1363 return bg;
1364 };
1365 let fg = self.eval_node(comp, fg_id, time, enc, visiting, stats);
1366 let mix_v = comp.eval_number(node, "Mix", time, 1.0, &self.expr).clamp(0.0, 1.0) as f32;
1367 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1368 let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
1369 let proc_r = comp.eval_number(node, "ProcessRed", time, 1.0, &self.expr) > 0.5;
1370 let proc_g = comp.eval_number(node, "ProcessGreen", time, 1.0, &self.expr) > 0.5;
1371 let proc_b = comp.eval_number(node, "ProcessBlue", time, 1.0, &self.expr) > 0.5;
1372 let proc_a = comp.eval_number(node, "ProcessAlpha", time, 1.0, &self.expr) > 0.5;
1373 let has_mask = node.connected_node("EffectMask").is_some();
1374 if (blend <= 1e-6 || mix_v <= 1e-6 || (!proc_r && !proc_g && !proc_b && !proc_a))
1375 && !(mbm && has_mask)
1376 {
1377 return bg;
1378 }
1379 // Fusion Dissolve passes Foreground straight through when Mix=1, Blend=1, and no EffectMask is attached.
1380 if mix_v >= 1.0 - 1e-6 && blend >= 1.0 - 1e-6 && !has_mask {
1381 return fg;
1382 }
1383 let (bg, fg) = (self.crop_to_canvas(enc, bg), self.crop_to_canvas(enc, fg));
1384 let op = match node.static_str("Operation").unwrap_or("DFTDissolve") {
1385 "DFTAddDissolve" => 1.0_f32,
1386 "DFTErode" => 2.0,
1387 "DFTRandom" => 3.0,
1388 "DFTRandomNoise" => 4.0,
1389 "DFTAlphaMerge" => 5.0,
1390 "DFTLumaRamp" => 6.0,
1391 "DFTWipe" => 7.0,
1392 _ => 0.0, // DFTDissolve
1393 };
1394 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(bg.canvas_size), enc, visiting, stats);
1395 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1396 let mut u = UniformParams::default();
1397 u.p[0] = [mix_v, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
1398 // Only DFTRandomNoise changes frame to frame; zeroing the seed elsewhere lets static dissolves hit the cache.
1399 let seed = if op == 4.0 { frame_i as f32 } else { 0.0 };
1400 u.p[1] = [if mbm { 1.0 } else { 0.0 }, op, seed, 0.0];
1401 u.p[2] = [
1402 if proc_r { 1.0 } else { 0.0 },
1403 if proc_g { 1.0 } else { 0.0 },
1404 if proc_b { 1.0 } else { 0.0 },
1405 if proc_a { 1.0 } else { 0.0 },
1406 ];
1407 let key = self.make_key(node, "Dissolve", bg.size, &[bg.content_hash, fg.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3]));
1408 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1409 stats.cache_hits += 1;
1410 return hit;
1411 }
1412 stats.cache_misses += 1;
1413 stats.nodes_evaluated += 1;
1414 let mut dst = self.alloc_tex_dod(bg.size, bg.origin, bg.canvas_size, bg.depth.max(fg.depth), key);
1415 dst.tex_scale = bg.tex_scale;
1416 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1417 self.dispatch_op(enc, ShaderOp::Dissolve, &bg.view, &fg.view, mv, &dst, &u);
1418 self.cache.insert(key, dst.clone(), node.id, frame_i);
1419 dst
1420 }
1421
1422 pub(super) fn eval_shadow(
1423 &mut self,
1424 comp: &Comp,
1425 node: &Node,
1426 time: f64,
1427 frame_i: i64,
1428 enc: &mut wgpu::CommandEncoder,
1429 visiting: &mut HashSet<(NodeId, i64)>,
1430 stats: &mut EvalStats,
1431 ) -> CachedTexture {
1432 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1433 return self.dummy.clone();
1434 };
1435 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1436 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1437 let mbm = self.multiplies_by_mask(comp, node, time);
1438 if blend <= 1e-6 && !mbm {
1439 return src;
1440 }
1441 let src = self.crop_to_canvas(enc, src);
1442 let offset = comp.eval_point(node, "ShadowOffset", time, [0.5, 0.5], &self.expr);
1443 let soft = comp.eval_number(node, "Softness", time, 0.0, &self.expr).max(0.0) as f32;
1444 let light_dist = comp.eval_number(node, "LightDistance", time, 1.0, &self.expr) as f32;
1445 let sh_r = comp.eval_number(node, "Red", time, 0.0, &self.expr) as f32;
1446 let sh_g = comp.eval_number(node, "Green", time, 0.0, &self.expr) as f32;
1447 let sh_b = comp.eval_number(node, "Blue", time, 0.0, &self.expr) as f32;
1448 let sh_a = comp.eval_number(node, "Alpha", time, 1.0, &self.expr) as f32;
1449 let shadow_only = if comp.eval_number(node, "OutputMode", time, 0.0, &self.expr) > 0.5 { 1.0 } else { 0.0 };
1450 let skip = self.process_skip(comp, node, time);
1451 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1452 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1453
1454 let key = self.make_key(
1455 node,
1456 "Shadow",
1457 src.size,
1458 &[src.content_hash, mask_hash],
1459 &[offset[0] as f32, offset[1] as f32, soft, light_dist, sh_r, sh_g, sh_b, sh_a, shadow_only, blend, if mask_inv { 1.0 } else { 0.0 }, mbm as u8 as f32, skip[0], skip[1], skip[2], skip[3]],
1460 );
1461 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1462 stats.cache_hits += 1;
1463 return hit;
1464 }
1465 stats.cache_misses += 1;
1466 stats.nodes_evaluated += 1;
1467
1468 // 1. Shift source by ShadowOffset (Fusion snaps shadow offset via floor in top-down coords) and apply LightDistance scale.
1469 let sw = src.size[0].max(1) as f64;
1470 let sh = src.size[1].max(1) as f64;
1471 let off_x_px = ((offset[0] - 0.5) * sw).floor() as f32;
1472 let off_y_up_px = -((-(offset[1] - 0.5) * sh).floor()) as f32;
1473 let q_off_x = off_x_px / sw as f32 + 0.5;
1474 let q_off_y = off_y_up_px / sh as f32 + 0.5;
1475 let dist_scale = if (light_dist - 1.0).abs() > 1e-4 {
1476 1.0 / light_dist.max(1e-4)
1477 } else {
1478 1.0
1479 };
1480 let shifted = if (q_off_x - 0.5).abs() > 1e-5 || (q_off_y - 0.5).abs() > 1e-5 || (dist_scale - 1.0).abs() > 1e-4 {
1481 let tmp = self.alloc_tex(src.size, src.depth, 0);
1482 let mut ux = UniformParams::default();
1483 ux.p[0] = [q_off_x, q_off_y, 0.5, 0.5];
1484 ux.p[1] = [dist_scale, dist_scale, 0.0, 0.0];
1485 ux.p[2] = [0.0, 0.0, 1.0, 0.0];
1486 self.dispatch_op(enc, ShaderOp::Transform, &src.view, &self.dummy.view, &self.dummy.view, &tmp, &ux);
1487 tmp
1488 } else {
1489 src.clone()
1490 };
1491
1492 // 2. Gaussian blur shifted alpha by Softness * width * 1.14 (clamped to border edges)
1493 let soft_px = soft * src.size[0] as f32 * 1.14;
1494 let sh_tex = if soft_px >= 0.25 {
1495 let t1 = self.alloc_tex(src.size, src.depth, 0);
1496 let t2 = self.alloc_tex(src.size, src.depth, 0);
1497 let mut uh = UniformParams::default();
1498 uh.p[0] = [1.0, 0.0, soft_px, 0.0];
1499 uh.p[1] = [1.0, 0.0, 0.0, 1.0];
1500 self.dispatch_op(enc, ShaderOp::BlurH, &shifted.view, &self.dummy.view, &self.dummy.view, &t1, &uh);
1501 let mut uv = UniformParams::default();
1502 uv.p[0] = [0.0, 1.0, soft_px, 0.0];
1503 uv.p[1] = [1.0, 0.0, 0.0, 1.0];
1504 self.dispatch_op(enc, ShaderOp::BlurV, &t1.view, &self.dummy.view, &self.dummy.view, &t2, &uv);
1505 t2
1506 } else {
1507 shifted
1508 };
1509
1510 // 3. Composite original OVER shadow (or Shadow Only)
1511 let dst = self.alloc_tex_like(&src, src.depth, key);
1512 let mut us = UniformParams::default();
1513 us.p[0] = [sh_r, sh_g, sh_b, sh_a];
1514 us.p[1] = [shadow_only, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
1515 us.p[2] = skip;
1516 us.p[3][0] = mbm as u8 as f32;
1517 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1518 self.dispatch_op(enc, ShaderOp::ShadowComp, &src.view, &sh_tex.view, mv, &dst, &us);
1519 self.cache.insert(key, dst.clone(), node.id, frame_i);
1520 dst
1521 }
1522
1523}
1524
1525#[cfg(test)]
1526mod tests {
1527 use super::{Comp, Engine};
1528
1529 fn eval_node_px(comp_src: &str, node_name: &str) -> (Vec<u8>, u32, u32) {
1530 let comp = Comp::from_fusion_str(comp_src).expect("parse comp");
1531 let id = comp.find_node(node_name).expect("find node");
1532 let mut engine = Engine::new_headless().expect("headless engine");
1533 let (tex, _) = engine.evaluate(&comp, id, 0.0);
1534 let px = engine.readback_rgba(&tex).expect("readback");
1535 (px, tex.size[0], tex.size[1])
1536 }
1537
1538 fn px_at(px: &[u8], w: u32, x: u32, y: u32) -> [u8; 4] {
1539 let i = ((y * w + x) * 4) as usize;
1540 [px[i], px[i + 1], px[i + 2], px[i + 3]]
1541 }
1542
1543 #[test]
1544 fn background_gradients_use_pixel_aspect_space() {
1545 // 16:9 canvas: diagonal Linear gradient normal must be perpendicular to the
1546 // Start->End vector in pixel space (not skewed UV space), and Radial gradient
1547 // distance must be circular in pixels rather than elliptical in UV.
1548 let linear_comp = r#"{
1549 Tools = ordered() {
1550 BgLin = Background {
1551 Inputs = {
1552 Width = Input { Value = 320, },
1553 Height = Input { Value = 180, },
1554 Type = Input { Value = FuID { "Gradient" }, },
1555 Start = Input { Value = { 0.0, 0.0 }, },
1556 End = Input { Value = { 1.0, 1.0 }, },
1557 Gradient = Input {
1558 Value = Gradient {
1559 Colors = {
1560 [0] = { 0, 0, 0, 1, },
1561 [1] = { 1, 0, 0, 1, },
1562 },
1563 },
1564 },
1565 },
1566 },
1567 }
1568 }"#;
1569 let (px, w, _) = eval_node_px(linear_comp, "BgLin");
1570 // At pixel (x=160, y=90) -> exact midpoint t=0.5 (~128).
1571 // At pixel (x=240, y=0) -> top-right? No, top-down y_img=0 => fu.y ~ 1.0, fu.x ~ 0.75:
1572 // in pixel space pos=(240,180), end=(320,180):
1573 // dot((240,180), (320,180)) / (320^2 + 180^2) = 109200 / 134800 = 0.810 -> ~207 (vs UV 0.875 -> 223).
1574 let mid = px_at(&px, w, 160, 90);
1575 assert!((mid[0] as i32 - 128).abs() <= 2, "mid={mid:?}");
1576 let off = px_at(&px, w, 240, 0);
1577 assert!((off[0] as i32 - 207).abs() <= 3, "expected ~207 in pixel space, got {off:?}");
1578
1579 let radial_comp = r#"{
1580 Tools = ordered() {
1581 BgRad = Background {
1582 Inputs = {
1583 Width = Input { Value = 320, },
1584 Height = Input { Value = 180, },
1585 Type = Input { Value = FuID { "Gradient" }, },
1586 GradientType = Input { Value = FuID { "Radial" }, },
1587 Start = Input { Value = { 0.5, 0.5 }, },
1588 End = Input { Value = { 1.0, 0.5 }, },
1589 Gradient = Input {
1590 Value = Gradient {
1591 Colors = {
1592 [0] = { 0, 0, 0, 1, },
1593 [1] = { 1, 0, 0, 1, },
1594 },
1595 },
1596 },
1597 },
1598 },
1599 }
1600 }"#;
1601 let (rpx, rw, _) = eval_node_px(radial_comp, "BgRad");
1602 // Radius = 160 px horizontally. At 80 px right of center (240, 90) AND 80 px
1603 // vertically from center (160, 10): both must be t=0.5 (~128) for circular radial.
1604 let horiz = px_at(&rpx, rw, 240, 90);
1605 let vert = px_at(&rpx, rw, 160, 10);
1606 assert!((horiz[0] as i32 - 128).abs() <= 3, "horiz={horiz:?}");
1607 assert!((vert[0] as i32 - 128).abs() <= 3, "vert={vert:?} (circular radial failed)");
1608 }
1609
1610 #[test]
1611 fn merge_linear_dodge_and_hsl_luma_modes() {
1612 // LinearDodge must scale semi-transparent fg by Gain=0.5 just like Normal over bg.
1613 let ld_comp = r#"{
1614 Tools = ordered() {
1615 Bg = Background {
1616 Inputs = {
1617 Width = Input { Value = 16, },
1618 Height = Input { Value = 16, },
1619 TopLeftRed = Input { Value = 0.4, },
1620 TopLeftGreen = Input { Value = 0.2, },
1621 TopLeftBlue = Input { Value = 0.1, },
1622 TopLeftAlpha = Input { Value = 1.0, },
1623 },
1624 },
1625 Fg = Background {
1626 Inputs = {
1627 Width = Input { Value = 16, },
1628 Height = Input { Value = 16, },
1629 TopLeftRed = Input { Value = 0.2, },
1630 TopLeftGreen = Input { Value = 0.3, },
1631 TopLeftBlue = Input { Value = 0.4, },
1632 TopLeftAlpha = Input { Value = 0.5, },
1633 },
1634 },
1635 M = Merge {
1636 Inputs = {
1637 Background = Input { SourceOp = "Bg", Source = "Output", },
1638 Foreground = Input { SourceOp = "Fg", Source = "Output", },
1639 ApplyMode = Input { Value = FuID { "LinearDodge" }, },
1640 Gain = Input { Value = 0.5, },
1641 },
1642 },
1643 }
1644 }"#;
1645 let (ld_px, ld_w, _) = eval_node_px(ld_comp, "M");
1646 let p = px_at(&ld_px, ld_w, 8, 8);
1647 // Background outputs fg=(0.2, 0.3, 0.4, 0.5); LinearDodge scales by Gain=0.5 directly ->
1648 // bg (0.4, 0.2, 0.1) + fg * 0.5 (0.1, 0.15, 0.2) = (0.50, 0.35, 0.30) -> (128, 90, 77).
1649 assert!((p[0] as i32 - 128).abs() <= 2, "LinearDodge R={p:?}");
1650 assert!((p[1] as i32 - 90).abs() <= 2, "LinearDodge G={p:?}");
1651 assert!((p[2] as i32 - 77).abs() <= 2, "LinearDodge B={p:?}");
1652
1653 // Geometric with fg=(0,0,0,1) over opaque bg must evaluate to 0, not > 0.
1654 let geom_comp = r#"{
1655 Tools = ordered() {
1656 Bg = Background {
1657 Inputs = {
1658 Width = Input { Value = 16, },
1659 Height = Input { Value = 16, },
1660 TopLeftRed = Input { Value = 0.8, },
1661 TopLeftGreen = Input { Value = 0.5, },
1662 TopLeftBlue = Input { Value = 0.2, },
1663 },
1664 },
1665 Fg = Background {
1666 Inputs = {
1667 Width = Input { Value = 16, },
1668 Height = Input { Value = 16, },
1669 TopLeftRed = Input { Value = 0.0, },
1670 TopLeftGreen = Input { Value = 0.0, },
1671 TopLeftBlue = Input { Value = 0.0, },
1672 },
1673 },
1674 M = Merge {
1675 Inputs = {
1676 Background = Input { SourceOp = "Bg", Source = "Output", },
1677 Foreground = Input { SourceOp = "Fg", Source = "Output", },
1678 ApplyMode = Input { Value = FuID { "Geometric" }, },
1679 },
1680 },
1681 }
1682 }"#;
1683 let (g_px, g_w, _) = eval_node_px(geom_comp, "M");
1684 let gp = px_at(&g_px, g_w, 8, 8);
1685 assert_eq!([gp[0], gp[1], gp[2]], [0, 0, 0]);
1686
1687 // Luminosity must transfer fg Rec.601 luma to bg without W3C clip_color desaturation.
1688 // bg = (0.0, 0.4, 0.8) [lum = 0.3264], fg = (0.9, 0.9, 0.9) [lum = 0.9]
1689 // bg + (0.9 - 0.3264) = (0.5736, 0.9736, 1.3736 -> clamped 1.0) -> (~146, ~248, 255)
1690 let lum_comp = r#"{
1691 Tools = ordered() {
1692 Bg = Background {
1693 Inputs = {
1694 Width = Input { Value = 16, },
1695 Height = Input { Value = 16, },
1696 TopLeftRed = Input { Value = 0.0, },
1697 TopLeftGreen = Input { Value = 0.4, },
1698 TopLeftBlue = Input { Value = 0.8, },
1699 },
1700 },
1701 Fg = Background {
1702 Inputs = {
1703 Width = Input { Value = 16, },
1704 Height = Input { Value = 16, },
1705 TopLeftRed = Input { Value = 0.9, },
1706 TopLeftGreen = Input { Value = 0.9, },
1707 TopLeftBlue = Input { Value = 0.9, },
1708 },
1709 },
1710 M = Merge {
1711 Inputs = {
1712 Background = Input { SourceOp = "Bg", Source = "Output", },
1713 Foreground = Input { SourceOp = "Fg", Source = "Output", },
1714 ApplyMode = Input { Value = FuID { "Luminosity" }, },
1715 },
1716 },
1717 }
1718 }"#;
1719 let (l_px, l_w, _) = eval_node_px(lum_comp, "M");
1720 let lp = px_at(&l_px, l_w, 8, 8);
1721 assert!((lp[0] as i32 - 146).abs() <= 3, "Luminosity={lp:?}");
1722 assert!((lp[1] as i32 - 248).abs() <= 3, "Luminosity={lp:?}");
1723 assert_eq!(lp[2], 255);
1724 }
1725
1726 #[test]
1727 fn merge_darker_and_lighter_color_respect_semi_transparent_bg() {
1728 // DarkerColor over semi-transparent bg=(0.2,0.2,0.2,0.5) with fg=(0.8,0.8,0.8,1.0):
1729 // over_rgb = 0.8 > bg.rgb = 0.2, so bg wins and produces bg.rgb + fg.rgb*(1-bg.a) = 0.6 (~153).
1730 let comp = r#"{
1731 Tools = ordered() {
1732 Bg = Background {
1733 Inputs = {
1734 Width = Input { Value = 16, },
1735 Height = Input { Value = 16, },
1736 TopLeftRed = Input { Value = 0.2, },
1737 TopLeftGreen = Input { Value = 0.2, },
1738 TopLeftBlue = Input { Value = 0.2, },
1739 TopLeftAlpha = Input { Value = 0.5, },
1740 },
1741 },
1742 Fg = Background {
1743 Inputs = {
1744 Width = Input { Value = 16, },
1745 Height = Input { Value = 16, },
1746 TopLeftRed = Input { Value = 0.8, },
1747 TopLeftGreen = Input { Value = 0.8, },
1748 TopLeftBlue = Input { Value = 0.8, },
1749 TopLeftAlpha = Input { Value = 1.0, },
1750 },
1751 },
1752 MDark = Merge {
1753 Inputs = {
1754 Background = Input { SourceOp = "Bg", Source = "Output", },
1755 Foreground = Input { SourceOp = "Fg", Source = "Output", },
1756 ApplyMode = Input { Value = FuID { "Darker Color" }, },
1757 },
1758 },
1759 }
1760 }"#;
1761 let (px, w, _) = eval_node_px(comp, "MDark");
1762 let p = px_at(&px, w, 8, 8);
1763 assert!((p[0] as i32 - 153).abs() <= 2, "DarkerColor={p:?}");
1764 assert_eq!(p[3], 255);
1765 }
1766
1767 #[test]
1768 fn merge_vivid_light_and_under_gain_parity() {
1769 let comp = r#"{
1770 Tools = ordered() {
1771 TransBg = Background {
1772 Inputs = {
1773 Width = Input { Value = 16, },
1774 Height = Input { Value = 16, },
1775 TopLeftAlpha = Input { Value = 0.0, },
1776 },
1777 },
1778 SemiBg = Background {
1779 Inputs = {
1780 Width = Input { Value = 16, },
1781 Height = Input { Value = 16, },
1782 TopLeftRed = Input { Value = 0.2, },
1783 TopLeftGreen = Input { Value = 0.3, },
1784 TopLeftBlue = Input { Value = 0.1, },
1785 TopLeftAlpha = Input { Value = 0.5, },
1786 },
1787 },
1788 Fg = Background {
1789 Inputs = {
1790 Width = Input { Value = 16, },
1791 Height = Input { Value = 16, },
1792 TopLeftRed = Input { Value = 0.64, },
1793 TopLeftGreen = Input { Value = 0.24, },
1794 TopLeftBlue = Input { Value = 0.48, },
1795 TopLeftAlpha = Input { Value = 0.8, },
1796 },
1797 },
1798 VividTrans = Merge {
1799 Inputs = {
1800 Background = Input { SourceOp = "TransBg", Source = "Output", },
1801 Foreground = Input { SourceOp = "Fg", Source = "Output", },
1802 ApplyMode = Input { Value = FuID { "VividLight" }, },
1803 Operator = Input { Value = FuID { "Under" }, },
1804 Gain = Input { Value = 0.74, },
1805 },
1806 },
1807 VividSemi = Merge {
1808 Inputs = {
1809 Background = Input { SourceOp = "SemiBg", Source = "Output", },
1810 Foreground = Input { SourceOp = "Fg", Source = "Output", },
1811 ApplyMode = Input { Value = FuID { "VividLight" }, },
1812 Operator = Input { Value = FuID { "Under" }, },
1813 Gain = Input { Value = 0.74, },
1814 },
1815 },
1816 NormalUnder = Merge {
1817 Inputs = {
1818 Background = Input { SourceOp = "SemiBg", Source = "Output", },
1819 Foreground = Input { SourceOp = "Fg", Source = "Output", },
1820 Operator = Input { Value = FuID { "Under" }, },
1821 Gain = Input { Value = 0.74, },
1822 },
1823 },
1824 ScreenGain = Merge {
1825 Inputs = {
1826 Background = Input { SourceOp = "SemiBg", Source = "Output", },
1827 Foreground = Input { SourceOp = "Fg", Source = "Output", },
1828 ApplyMode = Input { Value = FuID { "Screen" }, },
1829 Gain = Input { Value = 0.74, },
1830 },
1831 },
1832 HypotGain = Merge {
1833 Inputs = {
1834 Background = Input { SourceOp = "SemiBg", Source = "Output", },
1835 Foreground = Input { SourceOp = "Fg", Source = "Output", },
1836 ApplyMode = Input { Value = FuID { "Hypotenuse" }, },
1837 Gain = Input { Value = 0.74, },
1838 },
1839 },
1840 GeomGain = Merge {
1841 Inputs = {
1842 Background = Input { SourceOp = "SemiBg", Source = "Output", },
1843 Foreground = Input { SourceOp = "Fg", Source = "Output", },
1844 ApplyMode = Input { Value = FuID { "Geometric" }, },
1845 Gain = Input { Value = 0.74, },
1846 },
1847 },
1848 }
1849 }"#;
1850 // VividLight over transparent BG evaluates to (0,0,0) with alpha = fg.a * gain (~151).
1851 let (vt_px, vt_w, _) = eval_node_px(comp, "VividTrans");
1852 let vt = px_at(&vt_px, vt_w, 8, 8);
1853 assert_eq!([vt[0], vt[1], vt[2]], [0, 0, 0]);
1854 assert!((vt[3] as i32 - 151).abs() <= 2, "VividTrans alpha={vt:?}");
1855
1856 // VividLight over semi-transparent BG=(0.2,0.3,0.1,0.5) with Gain=0.74 -> ~(96, 31, 30, 203).
1857 let (vs_px, vs_w, _) = eval_node_px(comp, "VividSemi");
1858 let vs = px_at(&vs_px, vs_w, 8, 8);
1859 assert!((vs[0] as i32 - 96).abs() <= 2, "VividSemi={vs:?}");
1860 assert!((vs[1] as i32 - 31).abs() <= 2, "VividSemi={vs:?}");
1861 assert!((vs[2] as i32 - 30).abs() <= 2, "VividSemi={vs:?}");
1862 assert!((vs[3] as i32 - 203).abs() <= 2, "VividSemi alpha={vs:?}");
1863
1864 // Normal Under scales fg alpha by Gain=0.74 -> (133, 107, 87, 203).
1865 let (nu_px, nu_w, _) = eval_node_px(comp, "NormalUnder");
1866 let nu = px_at(&nu_px, nu_w, 8, 8);
1867 assert!((nu[0] as i32 - 133).abs() <= 2, "NormalUnder={nu:?}");
1868 assert!((nu[3] as i32 - 203).abs() <= 2, "NormalUnder alpha={nu:?}");
1869
1870 // Screen scales alpha by fg.a * gain (~203).
1871 let (sc_px, sc_w, _) = eval_node_px(comp, "ScreenGain");
1872 let sc = px_at(&sc_px, sc_w, 8, 8);
1873 assert!((sc[0] as i32 - 147).abs() <= 2, "ScreenGain={sc:?}");
1874 assert!((sc[3] as i32 - 203).abs() <= 2, "ScreenGain alpha={sc:?}");
1875
1876 // Hypotenuse alpha = sqrt(0.5^2 + 0.592^2) ~ 0.775 (~198).
1877 let (hy_px, hy_w, _) = eval_node_px(comp, "HypotGain");
1878 let hy = px_at(&hy_px, hy_w, 8, 8);
1879 assert!((hy[3] as i32 - 198).abs() <= 2, "HypotGain alpha={hy:?}");
1880
1881 // Geometric alpha = 2*0.5*0.592 / (0.5 + 0.592) ~ 0.542 (~138).
1882 let (ge_px, ge_w, _) = eval_node_px(comp, "GeomGain");
1883 let ge = px_at(&ge_px, ge_w, 8, 8);
1884 assert!((ge[3] as i32 - 138).abs() <= 2, "GeomGain alpha={ge:?}");
1885 }
1886
1887 #[test]
1888 fn channel_boolean_negative_preserves_unclamped_hdr() {
1889 let comp = r#"{
1890 Tools = ordered() {
1891 HdrBg = Background {
1892 Inputs = {
1893 Width = Input { Value = 16, },
1894 Height = Input { Value = 16, },
1895 Depth = Input { Value = 3, },
1896 TopLeftRed = Input { Value = 0.25, },
1897 TopLeftGreen = Input { Value = 0.75, },
1898 TopLeftBlue = Input { Value = 1.5, },
1899 TopLeftAlpha = Input { Value = 1.0, },
1900 },
1901 },
1902 CbNeg = ChannelBoolean {
1903 Inputs = {
1904 Background = Input { SourceOp = "HdrBg", Source = "Output", },
1905 Foreground = Input { SourceOp = "HdrBg", Source = "Output", },
1906 Operation = Input { Value = 10, },
1907 ToRed = Input { Value = 0, },
1908 ToGreen = Input { Value = 1, },
1909 ToBlue = Input { Value = 2, },
1910 ToAlpha = Input { Value = 3, },
1911 },
1912 },
1913 Lift = BrightnessContrast {
1914 Inputs = {
1915 Input = Input { SourceOp = "CbNeg", Source = "Output", },
1916 Brightness = Input { Value = 0.6, },
1917 },
1918 },
1919 }
1920 }"#;
1921 // Negative(1.5) = -0.5 in Depth=3; +0.6 brightness yields 0.1 (~26), not 0.6 (~153).
1922 let (px, w, _) = eval_node_px(comp, "Lift");
1923 let p = px_at(&px, w, 8, 8);
1924 assert_eq!(p[0], 255);
1925 assert!((p[1] as i32 - 217).abs() <= 2, "CB Negative G={p:?}");
1926 assert!((p[2] as i32 - 26).abs() <= 2, "CB Negative HDR B={p:?}");
1927 }
1928
1929 #[test]
1930 fn background_empty_fuid_corner_defaults_angle_reflect_and_multistop() {
1931 let comp = r#"{
1932 Tools = ordered() {
1933 EmptyType = Background {
1934 Inputs = {
1935 Width = Input { Value = 16, },
1936 Height = Input { Value = 16, },
1937 Type = Input { Value = FuID {}, },
1938 TopLeftRed = Input { Value = 0.661, },
1939 TopLeftAlpha = Input { Value = 1.0, },
1940 },
1941 },
1942 Horiz = Background {
1943 Inputs = {
1944 Width = Input { Value = 64, },
1945 Height = Input { Value = 16, },
1946 Type = Input { Value = FuID { "Horizontal" }, },
1947 TopLeftRed = Input { Value = 0.8, },
1948 TopLeftGreen = Input { Value = 0.4, },
1949 TopLeftBlue = Input { Value = 0.2, },
1950 },
1951 },
1952 AngleGrad = Background {
1953 Inputs = {
1954 Width = Input { Value = 320, },
1955 Height = Input { Value = 180, },
1956 Type = Input { Value = FuID { "Gradient" }, },
1957 GradientType = Input { Value = FuID { "Angle" }, },
1958 Start = Input { Value = { 0.5, 0.5 }, },
1959 End = Input { Value = { 0.8, 0.6 }, },
1960 Gradient = Input {
1961 Value = Gradient {
1962 Colors = {
1963 [0] = { 1, 0, 0, 1, },
1964 [1] = { 0, 1, 0, 1, },
1965 },
1966 },
1967 },
1968 },
1969 },
1970 ReflectGrad = Background {
1971 Inputs = {
1972 Width = Input { Value = 320, },
1973 Height = Input { Value = 180, },
1974 Type = Input { Value = FuID { "Gradient" }, },
1975 GradientType = Input { Value = FuID { "Reflect" }, },
1976 Start = Input { Value = { 0.5, 0.5 }, },
1977 End = Input { Value = { 0.8, 0.5 }, },
1978 Gradient = Input {
1979 Value = Gradient {
1980 Colors = {
1981 [0] = { 1, 0, 0, 1, },
1982 [1] = { 0, 1, 0, 1, },
1983 },
1984 },
1985 },
1986 },
1987 },
1988 MultiStop = Background {
1989 Inputs = {
1990 Width = Input { Value = 320, },
1991 Height = Input { Value = 16, },
1992 Type = Input { Value = FuID { "Gradient" }, },
1993 Start = Input { Value = { 0.0, 0.5 }, },
1994 End = Input { Value = { 1.0, 0.5 }, },
1995 Gradient = Input {
1996 Value = Gradient {
1997 Colors = {
1998 [0] = { 1, 0, 0, 1, },
1999 [0.25] = { 0, 1, 0, 1, },
2000 [0.75] = { 0, 0, 1, 1, },
2001 [1] = { 1, 1, 0, 1, },
2002 },
2003 },
2004 },
2005 },
2006 },
2007 }
2008 }"#;
2009 let (epx, ew, _) = eval_node_px(comp, "EmptyType");
2010 assert_eq!(px_at(&epx, ew, 8, 8), [0, 0, 0, 0]);
2011
2012 // Omitted TopRight defaults to (0,0,0,1), so midpoint x=32 is ~(102, 51, 25, 255).
2013 let (hpx, hw, _) = eval_node_px(comp, "Horiz");
2014 let hm = px_at(&hpx, hw, 32, 8);
2015 assert!((hm[0] as i32 - 102).abs() <= 4, "Horiz mid={hm:?}");
2016 assert_eq!(hm[3], 255);
2017
2018 // Angle gradient: CCW from End=(0.8, 0.6) around Start=(0.5, 0.5) in pixel space.
2019 let (apx, aw, _) = eval_node_px(comp, "AngleGrad");
2020 let a_top = px_at(&apx, aw, 160, 10); // t ~ 0.219 -> R~199, G~56
2021 assert!((a_top[0] as i32 - 199).abs() <= 3, "Angle top={a_top:?}");
2022 assert!((a_top[1] as i32 - 56).abs() <= 3, "Angle top={a_top:?}");
2023
2024 // Reflect gradient: symmetric around x=0.5 (x=10 and x=310 both saturate to green).
2025 let (rpx, rw, _) = eval_node_px(comp, "ReflectGrad");
2026 assert_eq!(px_at(&rpx, rw, 10, 90), [0, 255, 0, 255]);
2027 assert_eq!(px_at(&rpx, rw, 310, 90), [0, 255, 0, 255]);
2028 let r_mid = px_at(&rpx, rw, 160, 90);
2029 assert!(r_mid[0] >= 250 && r_mid[1] <= 5, "Reflect center={r_mid:?}");
2030
2031 // Multi-stop Linear: t=0.25 -> green (x=80), t=0.5 -> cyan-ish (0, 128, 128), t=0.75 -> blue (x=240).
2032 let (mpx, mw, _) = eval_node_px(comp, "MultiStop");
2033 let m25 = px_at(&mpx, mw, 80, 8);
2034 let m50 = px_at(&mpx, mw, 160, 8);
2035 let m75 = px_at(&mpx, mw, 240, 8);
2036 assert!(m25[1] >= 250 && m25[0] <= 5, "MultiStop 0.25={m25:?}");
2037 assert!((m50[1] as i32 - 128).abs() <= 4 && (m50[2] as i32 - 128).abs() <= 4, "MultiStop 0.5={m50:?}");
2038 assert!(m75[2] >= 250 && m75[0] <= 5, "MultiStop 0.75={m75:?}");
2039 }
2040
2041 #[test]
2042 fn channel_boolean_and_or_xor_signed_add_and_solid_border() {
2043 let comp = r#"{
2044 Tools = ordered() {
2045 Bg = Background {
2046 Inputs = {
2047 Width = Input { Value = 32, },
2048 Height = Input { Value = 32, },
2049 TopLeftRed = Input { Value = 0.7, },
2050 TopLeftGreen = Input { Value = 0.5, },
2051 TopLeftBlue = Input { Value = 0.3, },
2052 TopLeftAlpha = Input { Value = 0.8, },
2053 },
2054 },
2055 Fg = Background {
2056 Inputs = {
2057 Width = Input { Value = 32, },
2058 Height = Input { Value = 32, },
2059 TopLeftRed = Input { Value = 0.2, },
2060 TopLeftGreen = Input { Value = 0.4, },
2061 TopLeftBlue = Input { Value = 0.8, },
2062 TopLeftAlpha = Input { Value = 0.5, },
2063 },
2064 },
2065 CbAnd = ChannelBoolean { Inputs = { Operation = Input { Value = 3, }, Background = Input { SourceOp = "Bg", Source = "Output", }, Foreground = Input { SourceOp = "Fg", Source = "Output", }, }, },
2066 CbOr = ChannelBoolean { Inputs = { Operation = Input { Value = 4, }, Background = Input { SourceOp = "Bg", Source = "Output", }, Foreground = Input { SourceOp = "Fg", Source = "Output", }, }, },
2067 CbXor = ChannelBoolean { Inputs = { Operation = Input { Value = 5, }, Background = Input { SourceOp = "Bg", Source = "Output", }, Foreground = Input { SourceOp = "Fg", Source = "Output", }, }, },
2068 CbSAdd = ChannelBoolean { Inputs = { Operation = Input { Value = 14, }, Background = Input { SourceOp = "Bg", Source = "Output", }, Foreground = Input { SourceOp = "Fg", Source = "Output", }, }, },
2069 CbSolid = ChannelBoolean { Inputs = { Operation = Input { Value = 11, }, Background = Input { SourceOp = "Bg", Source = "Output", }, }, },
2070 SolidZoom = Transform { Inputs = { Size = Input { Value = 0.5, }, Input = Input { SourceOp = "CbSolid", Source = "Output", }, }, },
2071 }
2072 }"#;
2073 let (p3, w, _) = eval_node_px(comp, "CbAnd");
2074 assert!((px_at(&p3, w, 16, 16)[0] as i32 - 36).abs() <= 2, "And={:?}", px_at(&p3, w, 16, 16));
2075 let (p4, _, _) = eval_node_px(comp, "CbOr");
2076 assert!((px_at(&p4, w, 16, 16)[0] as i32 - 194).abs() <= 2, "Or={:?}", px_at(&p4, w, 16, 16));
2077 let (p5, _, _) = eval_node_px(comp, "CbXor");
2078 assert!((px_at(&p5, w, 16, 16)[0] as i32 - 158).abs() <= 2, "Xor={:?}", px_at(&p5, w, 16, 16));
2079 let (p14, _, _) = eval_node_px(comp, "CbSAdd");
2080 assert!((px_at(&p14, w, 16, 16)[2] as i32 - 153).abs() <= 2, "SignedAdd={:?}", px_at(&p14, w, 16, 16));
2081 // Solid (op=11) infinite white border stays (255,255,255,255) outside zoomed region.
2082 let (psz, _, _) = eval_node_px(comp, "SolidZoom");
2083 assert_eq!(px_at(&psz, w, 2, 2), [255, 255, 255, 255]);
2084 }
2085
2086 #[test]
2087 fn merge_inherits_flattened_transform_wrap_edge_mode() {
2088 let comp = r#"{
2089 Tools = ordered() {
2090 Black = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftAlpha = Input { Value = 1, }, }, },
2091 Dot = Background {
2092 Inputs = {
2093 Width = Input { Value = 64, },
2094 Height = Input { Value = 64, },
2095 TopLeftRed = Input { Value = 1, },
2096 TopLeftAlpha = Input { Value = 1, },
2097 EffectMask = Input { SourceOp = "R", Source = "Mask", },
2098 },
2099 },
2100 R = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 0.5, }, Height = Input { Value = 0.5, }, }, },
2101 XfFlat = Transform {
2102 Inputs = {
2103 Size = Input { Value = 0.25, },
2104 Edges = Input { Value = 1, },
2105 FlattenTransform = Input { Value = 1, },
2106 Input = Input { SourceOp = "Dot", Source = "Output", },
2107 },
2108 },
2109 M = Merge {
2110 Inputs = {
2111 Background = Input { SourceOp = "Black", Source = "Output", },
2112 Foreground = Input { SourceOp = "XfFlat", Source = "Output", },
2113 Center = Input { Value = { 0.2, 0.5 }, },
2114 },
2115 },
2116 }
2117 }"#;
2118 let (px, w, _) = eval_node_px(comp, "M");
2119 // Right side (x=60, y=32) wraps into tiled red instead of clipping to black.
2120 assert!(px_at(&px, w, 60, 32)[0] > 200, "expected wrapped red at x=60, got {:?}", px_at(&px, w, 60, 32));
2121 }
2122
2123 #[test]
2124 fn edge_mode_inheritance_walks_passthroughs_and_gates_on_blend_and_non_transform() {
2125 let comp = r#"{
2126 Tools = ordered() {
2127 Black = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftAlpha = Input { Value = 1, }, }, },
2128 R = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 0.5, }, Height = Input { Value = 0.5, }, }, },
2129 Dot = Background {
2130 Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, EffectMask = Input { SourceOp = "R", Source = "Mask", }, },
2131 },
2132 XfFlat = Transform {
2133 Inputs = { Size = Input { Value = 0.25, }, Edges = Input { Value = 1, }, FlattenTransform = Input { Value = 1, }, Input = Input { SourceOp = "Dot", Source = "Output", }, },
2134 },
2135 Router = PipeRouter { Inputs = { Input = Input { SourceOp = "XfFlat", Source = "Output", }, }, },
2136 MWrap = Merge { Inputs = { Background = Input { SourceOp = "Black", Source = "Output", }, Foreground = Input { SourceOp = "Router", Source = "Output", }, Center = Input { Value = { 0.2, 0.5 }, }, }, },
2137 Cg = ColorGain { Inputs = { GainRed = Input { Value = 1.0, }, Input = Input { SourceOp = "XfFlat", Source = "Output", }, }, },
2138 MNoWrap = Merge { Inputs = { Background = Input { SourceOp = "Black", Source = "Output", }, Foreground = Input { SourceOp = "Cg", Source = "Output", }, Center = Input { Value = { 0.2, 0.5 }, }, }, },
2139 MPartial = Merge { Inputs = { Background = Input { SourceOp = "Black", Source = "Output", }, Foreground = Input { SourceOp = "XfFlat", Source = "Output", }, Blend = Input { Value = 0.5, }, }, },
2140 XfAfterPartial = Transform { Inputs = { Size = Input { Value = 0.5, }, Input = Input { SourceOp = "MPartial", Source = "Output", }, }, },
2141 CbSolidHalf = ChannelBoolean { Inputs = { Operation = Input { Value = 11, }, Blend = Input { Value = 0.5, }, Background = Input { SourceOp = "Black", Source = "Output", }, }, },
2142 XfAfterCbHalf = Transform { Inputs = { Size = Input { Value = 0.5, }, Input = Input { SourceOp = "CbSolidHalf", Source = "Output", }, }, },
2143 ShrinkBg = SetDomain { Inputs = { Mode = Input { Value = FuID { "Set" }, }, Left = Input { Value = 0.25, }, Right = Input { Value = 0.75, }, Bottom = Input { Value = 0.25, }, Top = Input { Value = 0.75, }, Input = Input { SourceOp = "Black", Source = "Output", }, }, },
2144 White64 = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, },
2145 CbSAddExpand = ChannelBoolean { Inputs = { Operation = Input { Value = 14, }, Background = Input { SourceOp = "ShrinkBg", Source = "Output", }, Foreground = Input { SourceOp = "White64", Source = "Output", }, }, },
2146 }
2147 }"#;
2148 let (pw, w, _) = eval_node_px(comp, "MWrap");
2149 assert!(px_at(&pw, w, 60, 32)[0] > 200, "PipeRouter should preserve FlattenTransform wrap: {:?}", px_at(&pw, w, 60, 32));
2150 let (pnw, _, _) = eval_node_px(comp, "MNoWrap");
2151 assert!(px_at(&pnw, w, 60, 32)[0] < 10, "non-Transform must not leak wrap: {:?}", px_at(&pnw, w, 60, 32));
2152 let (pp, _, _) = eval_node_px(comp, "XfAfterPartial");
2153 assert_eq!(px_at(&pp, w, 2, 2), [0, 0, 0, 255], "partial-blend Merge should keep bg Canvas edge_mode");
2154 let (pcb, _, _) = eval_node_px(comp, "XfAfterCbHalf");
2155 assert_eq!(px_at(&pcb, w, 2, 2), [0, 0, 0, 0], "partial-blend Solid CB should not leave white border");
2156 let (psa, _, _) = eval_node_px(comp, "CbSAddExpand");
2157 assert!((px_at(&psa, w, 2, 2)[0] as i32 - 128).abs() <= 2, "Signed Add expands shrunk DoD to canvas: {:?}", px_at(&psa, w, 2, 2));
2158 }
2159
2160 #[test]
2161 fn dissolve_mix_default_erode_and_channel_toggles() {
2162 let comp = r#"{
2163 Tools = ordered() {
2164 Bg = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, TopLeftRed = Input { Value = 0.2, }, TopLeftGreen = Input { Value = 0.4, }, TopLeftBlue = Input { Value = 0.8, }, TopLeftAlpha = Input { Value = 1.0, }, }, },
2165 Fg = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, TopLeftRed = Input { Value = 0.8, }, TopLeftGreen = Input { Value = 0.2, }, TopLeftBlue = Input { Value = 0.2, }, TopLeftAlpha = Input { Value = 1.0, }, }, },
2166 Def = Dissolve { Inputs = { Background = Input { SourceOp = "Bg", Source = "Output", }, Foreground = Input { SourceOp = "Fg", Source = "Output", }, }, },
2167 DarkBg = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, TopLeftRed = Input { Value = 0.1, }, TopLeftGreen = Input { Value = 0.1, }, TopLeftBlue = Input { Value = 0.1, }, TopLeftAlpha = Input { Value = 1.0, }, }, },
2168 Erode = Dissolve {
2169 Inputs = {
2170 Operation = Input { Value = FuID { "DFTErode" }, },
2171 Mix = Input { Value = 0.5, },
2172 Background = Input { SourceOp = "DarkBg", Source = "Output", },
2173 Foreground = Input { SourceOp = "Fg", Source = "Output", },
2174 },
2175 },
2176 NoRed = Dissolve {
2177 Inputs = {
2178 Mix = Input { Value = 0.5, },
2179 ProcessRed = Input { Value = 0, },
2180 Background = Input { SourceOp = "Bg", Source = "Output", },
2181 Foreground = Input { SourceOp = "Fg", Source = "Output", },
2182 },
2183 },
2184 }
2185 }"#;
2186 let (pd, w, _) = eval_node_px(comp, "Def");
2187 assert_eq!(px_at(&pd, w, 16, 16), [204, 51, 51, 255], "Dissolve default Mix=1.0 outputs Foreground");
2188 let (pe, _, _) = eval_node_px(comp, "Erode");
2189 let e = px_at(&pe, w, 16, 16);
2190 assert_eq!(e, [102, 26, 26, 128], "DFTErode erodes dark Background below threshold: {:?}", e);
2191 let (pnr, _, _) = eval_node_px(comp, "NoRed");
2192 let nr = px_at(&pnr, w, 16, 16);
2193 assert_eq!(nr[0], 51, "ProcessRed=0 keeps Background red: {:?}", nr);
2194 assert!((nr[2] as i32 - 128).abs() <= 2, "ProcessBlue=1 blends red/blue: {:?}", nr);
2195 }
2196
2197 #[test]
2198 fn static_dissolve_hits_the_cache_on_later_frames() {
2199 let comp_src = r#"{
2200 Tools = ordered() {
2201 Bg = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, TopLeftRed = Input { Value = 0.2, }, TopLeftAlpha = Input { Value = 1.0, }, }, },
2202 Fg = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, TopLeftGreen = Input { Value = 0.8, }, TopLeftAlpha = Input { Value = 1.0, }, }, },
2203 Static = Dissolve { Inputs = { Mix = Input { Value = 0.5, }, Background = Input { SourceOp = "Bg", Source = "Output", }, Foreground = Input { SourceOp = "Fg", Source = "Output", }, }, },
2204 Noisy = Dissolve { Inputs = { Mix = Input { Value = 0.5, }, Operation = Input { Value = FuID { "DFTRandomNoise" }, }, Background = Input { SourceOp = "Bg", Source = "Output", }, Foreground = Input { SourceOp = "Fg", Source = "Output", }, }, },
2205 NoGreen = Dissolve { Inputs = { ProcessGreen = Input { Value = 0, }, Background = Input { SourceOp = "Bg", Source = "Output", }, Foreground = Input { SourceOp = "Fg", Source = "Output", }, }, },
2206 }
2207 }"#;
2208 let comp = Comp::from_fusion_str(comp_src).expect("parse comp");
2209 let mut engine = Engine::new_headless().expect("headless engine");
2210 let id = comp.find_node("Static").unwrap();
2211 engine.evaluate(&comp, id, 0.0);
2212 let (_, stats) = engine.evaluate(&comp, id, 1.0);
2213 assert_eq!(stats.nodes_evaluated, 0, "Dissolve with no per-frame noise reuses its cached result");
2214 let noisy = comp.find_node("Noisy").unwrap();
2215 engine.evaluate(&comp, noisy, 0.0);
2216 let (_, stats) = engine.evaluate(&comp, noisy, 1.0);
2217 assert_eq!(stats.nodes_evaluated, 1, "DFTRandomNoise re-seeds every frame");
2218
2219 // Fusion ignores the channel toggles once Mix=1 and Blend=1, so Foreground passes through whole.
2220 let (px, w, _) = eval_node_px(comp_src, "NoGreen");
2221 assert_eq!(px_at(&px, w, 16, 16)[1], 204, "ProcessGreen=0 still outputs Foreground green at Mix=1, Blend=1");
2222 }
2223
2224 #[test]
2225 fn expand_dod_axis_allows_one_sided_extension_up_to_max_dim() {
2226 assert_eq!(super::expand_dod_axis(0, 1920, 4400.0, 6324.0, 8192), (0, 6326));
2227 assert_eq!(super::expand_dod_axis(-1000, 1920, -6000.0, 6000.0, 8192), (-3902, 4290));
2228 }
2229
2230 #[test]
2231 fn downstream_roi_bounds_clips_pixelwise_merge_and_preserves_spatial_dod() {
2232 let comp_src = r#"{
2233 Tools = ordered() {
2234 Bg = Background {
2235 Inputs = {
2236 Width = Input { Value = 64, },
2237 Height = Input { Value = 64, },
2238 TopLeftAlpha = Input { Value = 1.0, },
2239 },
2240 },
2241 HugeFg = Background {
2242 Inputs = {
2243 Width = Input { Value = 256, },
2244 Height = Input { Value = 256, },
2245 TopLeftRed = Input { Value = 1.0, },
2246 TopLeftAlpha = Input { Value = 1.0, },
2247 },
2248 },
2249 MergePixel = Merge {
2250 Inputs = {
2251 Background = Input { SourceOp = "Bg", Source = "Output", },
2252 Foreground = Input { SourceOp = "HugeFg", Source = "Output", },
2253 Size = Input { Value = 2.0, },
2254 },
2255 },
2256 Cc = ColorCorrector {
2257 Inputs = {
2258 Input = Input { SourceOp = "MergePixel", Source = "Output", },
2259 },
2260 },
2261 DbFrame = DirectionalBlur {
2262 Inputs = {
2263 Input = Input { SourceOp = "Cc", Source = "Output", },
2264 Length = Input { Value = 0.05, },
2265 },
2266 },
2267 MergeXf = Merge {
2268 Inputs = {
2269 Background = Input { SourceOp = "Bg", Source = "Output", },
2270 Foreground = Input { SourceOp = "HugeFg", Source = "Output", },
2271 Size = Input { Value = 1.0, },
2272 },
2273 },
2274 XfOut = Transform {
2275 Inputs = {
2276 Size = Input { Value = 0.25, },
2277 Input = Input { SourceOp = "MergeXf", Source = "Output", },
2278 },
2279 },
2280 MergeCrop = Merge {
2281 Inputs = {
2282 Background = Input { SourceOp = "Bg", Source = "Output", },
2283 Foreground = Input { SourceOp = "HugeFg", Source = "Output", },
2284 Size = Input { Value = 1.0, },
2285 },
2286 },
2287 CropOut = Crop {
2288 Inputs = {
2289 XOffset = Input { Value = -32, },
2290 YOffset = Input { Value = -32, },
2291 XSize = Input { Value = 64, },
2292 YSize = Input { Value = 64, },
2293 Input = Input { SourceOp = "MergeCrop", Source = "Output", },
2294 },
2295 },
2296 }
2297 }"#;
2298 let comp = Comp::from_fusion_str(comp_src).expect("parse roi comp");
2299 let mut eng = Engine::new_headless().expect("headless engine");
2300 let mut enc = eng.device.create_command_encoder(&Default::default());
2301 let mut visiting = std::collections::HashSet::new();
2302 let mut stats = super::EvalStats::default();
2303
2304 // Pixelwise + Frame-clipped DirectionalBlur downstream -> MergePixel stays tightly at 64x64.
2305 let mp_id = comp.find_node("MergePixel").unwrap();
2306 let mp_tex = eng.eval_node(&comp, mp_id, 0.0, &mut enc, &mut visiting, &mut stats);
2307 assert_eq!(mp_tex.origin, [0, 0]);
2308 assert_eq!(mp_tex.size, [64, 64]);
2309
2310 // Transform zooming out (Size=0.25) downstream -> MergeXf expands its DoD cleanly.
2311 let mxf_id = comp.find_node("MergeXf").unwrap();
2312 let mxf_tex = eng.eval_node(&comp, mxf_id, 0.0, &mut enc, &mut visiting, &mut stats);
2313 assert!(mxf_tex.size[0] > 64 && mxf_tex.size[1] > 64, "expected expanded DoD for zoom-out Transform, got {:?}", mxf_tex.size);
2314
2315 // Crop reading outside canvas -> MergeCrop bails out and preserves full DoD.
2316 let mc_id = comp.find_node("MergeCrop").unwrap();
2317 let mc_tex = eng.eval_node(&comp, mc_id, 0.0, &mut enc, &mut visiting, &mut stats);
2318 assert_eq!(mc_tex.size, [260, 260]);
2319 eng.queue.submit(Some(enc.finish()));
2320 eng.frame_memo.clear();
2321 eng.frame_consumers.clear();
2322 eng.frame_roi_memo.clear();
2323
2324 // Corner of XfOut must show HugeFg's red from outside the 64x64 BG canvas.
2325 let (xf_tex, _) = eng.evaluate(&comp, comp.find_node("XfOut").unwrap(), 0.0);
2326 let xf_px = eng.readback_rgba(&xf_tex).unwrap();
2327 assert!(px_at(&xf_px, xf_tex.size[0], 10, 10)[0] > 200, "zoom-out Transform corner must sample expanded DoD");
2328
2329 // CropOut reading [-32..32] must also sample HugeFg's red from outside the 64x64 BG canvas.
2330 let (cr_tex, _) = eng.evaluate(&comp, comp.find_node("CropOut").unwrap(), 0.0);
2331 let cr_px = eng.readback_rgba(&cr_tex).unwrap();
2332 assert!(px_at(&cr_px, cr_tex.size[0], 8, 8)[0] > 200, "Crop at negative offset must sample expanded DoD");
2333 }
2334
2335 #[test]
2336 fn directly_evaluated_merge_upstream_of_zoomed_in_transform_renders_full_canvas() {
2337 let comp_src = r#"{
2338 Tools = ordered() {
2339 Bg = Background {
2340 Inputs = {
2341 Width = Input { Value = 64, },
2342 Height = Input { Value = 64, },
2343 TopLeftRed = Input { Value = 1.0, },
2344 TopLeftAlpha = Input { Value = 1.0, },
2345 },
2346 },
2347 Fg = Background {
2348 Inputs = {
2349 Width = Input { Value = 64, },
2350 Height = Input { Value = 64, },
2351 TopLeftGreen = Input { Value = 1.0, },
2352 TopLeftAlpha = Input { Value = 1.0, },
2353 },
2354 },
2355 M = Merge {
2356 Inputs = {
2357 Background = Input { SourceOp = "Bg", Source = "Output", },
2358 Foreground = Input { SourceOp = "Fg", Source = "Output", },
2359 },
2360 },
2361 ZoomIn = Transform {
2362 Inputs = {
2363 Size = Input { Value = 2.0, },
2364 Input = Input { SourceOp = "M", Source = "Output", },
2365 },
2366 },
2367 }
2368 }"#;
2369 let comp = Comp::from_fusion_str(comp_src).expect("parse zoom-in comp");
2370 let mut eng = Engine::new_headless().expect("headless engine");
2371 let (m_tex, _) = eng.evaluate(&comp, comp.find_node("M").unwrap(), 0.0);
2372 assert_eq!(m_tex.size, [64, 64]);
2373 let m_px = eng.readback_rgba(&m_tex).unwrap();
2374 assert_eq!(px_at(&m_px, 64, 2, 2), [0, 255, 0, 255], "corner of directly-evaluated Merge must not be cropped by downstream ZoomIn");
2375 assert_eq!(px_at(&m_px, 64, 61, 61), [0, 255, 0, 255]);
2376
2377 let (z_tex, _) = eng.evaluate(&comp, comp.find_node("ZoomIn").unwrap(), 0.0);
2378 assert_eq!(z_tex.size, [64, 64]);
2379 let z_px = eng.readback_rgba(&z_tex).unwrap();
2380 assert_eq!(px_at(&z_px, 64, 32, 32), [0, 255, 0, 255]);
2381 }
2382
2383 #[test]
2384 fn camera_shake_and_xf_chroma_preserve_upstream_dod_when_active() {
2385 let comp_src = r#"{
2386 Tools = ordered() {
2387 Bg = Background {
2388 Inputs = {
2389 Width = Input { Value = 64, },
2390 Height = Input { Value = 64, },
2391 TopLeftAlpha = Input { Value = 1.0, },
2392 },
2393 },
2394 HugeFg = Background {
2395 Inputs = {
2396 Width = Input { Value = 256, },
2397 Height = Input { Value = 256, },
2398 TopLeftRed = Input { Value = 1.0, },
2399 TopLeftAlpha = Input { Value = 1.0, },
2400 },
2401 },
2402 MShake = Merge {
2403 Inputs = {
2404 Background = Input { SourceOp = "Bg", Source = "Output", },
2405 Foreground = Input { SourceOp = "HugeFg", Source = "Output", },
2406 },
2407 },
2408 Shake = CameraShake {
2409 Inputs = {
2410 Input = Input { SourceOp = "MShake", Source = "Output", },
2411 },
2412 },
2413 MChroma = Merge {
2414 Inputs = {
2415 Background = Input { SourceOp = "Bg", Source = "Output", },
2416 Foreground = Input { SourceOp = "HugeFg", Source = "Output", },
2417 },
2418 },
2419 Chroma = Fuse.XfChroma {
2420 Inputs = {
2421 Input = Input { SourceOp = "MChroma", Source = "Output", },
2422 },
2423 },
2424 }
2425 }"#;
2426 let comp = Comp::from_fusion_str(comp_src).expect("parse dod consumers comp");
2427 let mut eng = Engine::new_headless().expect("headless engine");
2428 let mut enc = eng.device.create_command_encoder(&Default::default());
2429 let mut visiting = std::collections::HashSet::new();
2430 let mut stats = super::EvalStats::default();
2431
2432 let ms_tex = eng.eval_node(&comp, comp.find_node("MShake").unwrap(), 0.0, &mut enc, &mut visiting, &mut stats);
2433 assert_eq!(ms_tex.size, [260, 260], "CameraShake must preserve full upstream DoD");
2434 let mc_tex = eng.eval_node(&comp, comp.find_node("MChroma").unwrap(), 0.0, &mut enc, &mut visiting, &mut stats);
2435 assert_eq!(mc_tex.size, [260, 260], "Fuse.XfChroma must preserve full upstream DoD");
2436 eng.queue.submit(Some(enc.finish()));
2437 }
2438
2439 #[test]
2440 fn merge_conjoint_disjoint_mask_stencil_and_process_channels() {
2441 // BG = premult (0.4, 0.2, 0.8, 0.8), FG = premult (0.6, 0.3, 0.0, 0.6)
2442 // - Conjoint: k = 1 - 0.6/0.8 = 0.25 -> (0.7, 0.35, 0.2, 0.8) = (179, 89, 51, 204)
2443 // - Disjoint: k = min(1, (1 - 0.6)/0.8) = 0.5 -> (0.8, 0.4, 0.4, 1.0) = (204, 102, 102, 255)
2444 // - Mask: bg * fg.a = (0.24, 0.12, 0.48, 0.48) = (61, 31, 122, 122)
2445 // - Stencil: bg * (1 - fg.a) = (0.16, 0.08, 0.32, 0.32) = (41, 20, 82, 82)
2446 // - ProcessBlue=0, ProcessAlpha=0 on Conjoint keeps BG blue (204) and BG alpha (204)
2447 let comp_src = r#"{
2448 Tools = ordered() {
2449 Bg = Background {
2450 Inputs = {
2451 Width = Input { Value = 16, }, Height = Input { Value = 16, },
2452 TopLeftRed = Input { Value = 0.4, },
2453 TopLeftGreen = Input { Value = 0.2, },
2454 TopLeftBlue = Input { Value = 0.8, },
2455 TopLeftAlpha = Input { Value = 0.8, },
2456 },
2457 },
2458 Fg = Background {
2459 Inputs = {
2460 Width = Input { Value = 16, }, Height = Input { Value = 16, },
2461 TopLeftRed = Input { Value = 0.6, },
2462 TopLeftGreen = Input { Value = 0.3, },
2463 TopLeftBlue = Input { Value = 0.0, },
2464 TopLeftAlpha = Input { Value = 0.6, },
2465 },
2466 },
2467 MConj = Merge {
2468 Inputs = {
2469 Operator = Input { Value = FuID { "Conjoint" }, },
2470 Background = Input { SourceOp = "Bg", Source = "Output", },
2471 Foreground = Input { SourceOp = "Fg", Source = "Output", },
2472 },
2473 },
2474 MDisj = Merge {
2475 Inputs = {
2476 Operator = Input { Value = FuID { "Disjoint" }, },
2477 Background = Input { SourceOp = "Bg", Source = "Output", },
2478 Foreground = Input { SourceOp = "Fg", Source = "Output", },
2479 },
2480 },
2481 MMask = Merge {
2482 Inputs = {
2483 Operator = Input { Value = FuID { "Mask" }, },
2484 Background = Input { SourceOp = "Bg", Source = "Output", },
2485 Foreground = Input { SourceOp = "Fg", Source = "Output", },
2486 },
2487 },
2488 MSten = Merge {
2489 Inputs = {
2490 Operator = Input { Value = FuID { "Stencil" }, },
2491 Background = Input { SourceOp = "Bg", Source = "Output", },
2492 Foreground = Input { SourceOp = "Fg", Source = "Output", },
2493 },
2494 },
2495 MProc = Merge {
2496 Inputs = {
2497 Operator = Input { Value = FuID { "Conjoint" }, },
2498 ProcessBlue = Input { Value = 0, },
2499 ProcessAlpha = Input { Value = 0, },
2500 Background = Input { SourceOp = "Bg", Source = "Output", },
2501 Foreground = Input { SourceOp = "Fg", Source = "Output", },
2502 },
2503 },
2504 }
2505 }"#;
2506 let comp = Comp::from_fusion_str(comp_src).expect("parse merge ops comp");
2507 let Ok(mut eng) = Engine::new_headless() else { return };
2508 let px_of = |eng: &mut Engine, name: &str| -> [u8; 4] {
2509 let (tex, _) = eng.evaluate(&comp, comp.find_node(name).unwrap(), 0.0);
2510 let px = eng.readback_rgba(&tex).unwrap();
2511 [px[0], px[1], px[2], px[3]]
2512 };
2513 let close = |got: [u8; 4], want: [u8; 4], label: &str| {
2514 for c in 0..4 {
2515 assert!(got[c].abs_diff(want[c]) <= 2, "{label} ch {c}: got {got:?}, want {want:?}");
2516 }
2517 };
2518 close(px_of(&mut eng, "MConj"), [179, 89, 51, 204], "Conjoint");
2519 close(px_of(&mut eng, "MDisj"), [204, 102, 102, 255], "Disjoint");
2520 close(px_of(&mut eng, "MMask"), [61, 31, 122, 122], "Mask");
2521 close(px_of(&mut eng, "MSten"), [41, 20, 82, 82], "Stencil");
2522 close(px_of(&mut eng, "MProc"), [179, 89, 204, 204], "Conjoint+ProcessBlue/Alpha=0");
2523 }
2524
2525 #[test]
2526 fn merge_round_half_to_even_and_shadow_quant_parity() {
2527 let comp_src = r#"{
2528 Tools = ordered() {
2529 Bg = Background {
2530 Inputs = {
2531 Width = Input { Value = 16, }, Height = Input { Value = 16, },
2532 TopLeftRed = Input { Value = 0, }, TopLeftGreen = Input { Value = 0, },
2533 TopLeftBlue = Input { Value = 0, }, TopLeftAlpha = Input { Value = 1, },
2534 },
2535 },
2536 Fg = Background {
2537 Inputs = {
2538 Width = Input { Value = 16, }, Height = Input { Value = 16, },
2539 TopLeftRed = Input { Value = 0.3019607843, }, TopLeftAlpha = Input { Value = 1, },
2540 },
2541 },
2542 FgRect = RectangleMask {
2543 Inputs = {
2544 MaskWidth = Input { Value = 16, }, MaskHeight = Input { Value = 16, },
2545 Width = Input { Value = 0.5, }, Height = Input { Value = 0.5, },
2546 },
2547 },
2548 FgMasked = Background {
2549 Inputs = {
2550 Width = Input { Value = 16, }, Height = Input { Value = 16, },
2551 EffectMask = Input { SourceOp = "FgRect", Source = "Mask", },
2552 TopLeftRed = Input { Value = 0.3019607843, }, TopLeftAlpha = Input { Value = 1, },
2553 },
2554 },
2555 M = Merge {
2556 Inputs = {
2557 Blend = Input { Value = 0.5, },
2558 FilterMethod = Input { Value = 4, },
2559 Background = Input { SourceOp = "Bg", Source = "Output", },
2560 Foreground = Input { SourceOp = "Fg", Source = "Output", },
2561 },
2562 },
2563 Sh = Shadow {
2564 Inputs = {
2565 Input = Input { SourceOp = "FgMasked", Source = "Output", },
2566 Red = Input { Value = 0.5, },
2567 Green = Input { Value = 0.55121, },
2568 Blue = Input { Value = 0.5, },
2569 LightDistance = Input { Value = 0.5, },
2570 ShadowOffset = Input { Value = { 0.5, 0.5 }, },
2571 Softness = Input { Value = 0.0, },
2572 },
2573 },
2574 }
2575 }"#;
2576 let comp = Comp::from_fusion_str(comp_src).expect("parse merge/shadow parity comp");
2577 let Ok(mut eng) = Engine::new_headless() else { return };
2578 let (mt, _) = eng.evaluate(&comp, comp.find_node("M").unwrap(), 0.0);
2579 let mpx = eng.readback_rgba(&mt).unwrap();
2580 let c = (8 * 16 + 8) * 4;
2581 // 0.3019607843 * 255 = 77 -> blend 0.5 against 0 -> 38.5 -> round-to-even 38 or 39;
2582 // verify cubic + blend outputs exact bounded interior without drift.
2583 assert!((mpx[c] as i32 - 39).abs() <= 1, "merge cubic blend red={}", mpx[c]);
2584
2585 let (st, _) = eng.evaluate(&comp, comp.find_node("Sh").unwrap(), 0.0);
2586 let spx = eng.readback_rgba(&st).unwrap();
2587 // Outside FgMasked [4..12]^2, scaled shadow reaches (1,1) with alpha>0 and Green/Red matching Green=0.55121.
2588 let s = (1 * 16 + 1) * 4;
2589 assert!(spx[s + 3] > 200, "expected shadow at corner (1,1), got {:?}", &spx[s..s + 4]);
2590 assert!(spx[s + 1] >= spx[s], "Shadow Green=0.55121 > Red=0.5: {:?}", &spx[s..s + 4]);
2591 }
2592}