authoravatarclover caruso<git@paperclover.net>2026-12-01 21:58:17-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 22:07:29-08:00
log11dff3d99e505db517ac8cca162d72a8506a55ef
tree5f4fcc82dec07c1a6d3fd6ee175d50e8a4656fd0
parent56052a3327a40509f74214405211941b01f80e37
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

refactor(engine): recover poisoned internal locks in optflow/scene3d and split eval/transform.rs


6 files changed, 1953 insertions(+), 1916 deletions(-)

crates/engine/src/eval/transform.rs+4-1833
......@@ -1,48 +1,9 @@
11use super::*;
22
3/// Deterministic LuaJIT 2.x TW223 PRNG (`math.randomseed` + `math.random`) matching
4/// Fusion `Duplicate.fuse` `RandomSeed` jitter draws.
5struct LuaJitPrng {
6 u: [u64; 4],
7}
8
9impl LuaJitPrng {
10 fn new(seed: f64) -> Self {
11 let mut r: u32 = 0x1109_0601;
12 let mut d = seed;
13 let mut u = [0u64; 4];
14 for slot in &mut u {
15 let m = 1u64 << (r & 255);
16 r >>= 8;
17 d = d * std::f64::consts::PI + std::f64::consts::E;
18 let bits = d.to_bits();
19 *slot = if bits < m { bits + m } else { bits };
20 }
21 let mut rng = Self { u };
22 for _ in 0..10 {
23 rng.next_u64();
24 }
25 rng
26 }
27
28 fn next_u64(&mut self) -> u64 {
29 let step = |z: u64, s1: u32, s2: u32, sh: u32, s3: u32| -> u64 {
30 let mask = u64::MAX << sh;
31 (((z << s1) ^ z) >> s2) ^ ((z & mask) << s3)
32 };
33 self.u[0] = step(self.u[0], 31, 45, 1, 18);
34 self.u[1] = step(self.u[1], 19, 30, 6, 28);
35 self.u[2] = step(self.u[2], 24, 48, 9, 7);
36 self.u[3] = step(self.u[3], 21, 39, 17, 8);
37 self.u[0] ^ self.u[1] ^ self.u[2] ^ self.u[3]
38 }
39
40 fn next_signed(&mut self) -> f32 {
41 let bits = (self.next_u64() & 0x000f_ffff_ffff_ffff) | 0x3ff0_0000_0000_0000;
42 let u01 = f64::from_bits(bits) - 1.0;
43 (2.0 * u01 - 1.0) as f32
44 }
45}
3mod dve;
4mod warps_fuses;
5#[cfg(test)]
6mod tests;
467
478/// Follows bypassed nodes and routers upstream to the node that actually produces the image.
489pub(super) fn unwrap_passthrough(comp: &Comp, start_id: NodeId) -> NodeId {
......@@ -899,1794 +860,4 @@ impl Engine {
899860 ["ProcessRed", "ProcessGreen", "ProcessBlue", "ProcessAlpha"]
900861 .map(|c| if comp.eval_number(node, c, time, 1.0, &self.expr) > 0.5 { 0.0 } else { 1.0 })
901862 }
902
903 pub(super) fn eval_displace(
904 &mut self,
905 comp: &Comp,
906 node: &Node,
907 time: f64,
908 frame_i: i64,
909 enc: &mut wgpu::CommandEncoder,
910 visiting: &mut HashSet<(NodeId, i64)>,
911 stats: &mut EvalStats,
912 ) -> CachedTexture {
913 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
914 return self.dummy.clone();
915 };
916 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
917 let fg_id = node.connected_node("Foreground").and_then(|s| comp.find_node(s));
918 if fg_id.is_none() && !self.multiplies_by_mask(comp, node, time) {
919 return src;
920 }
921 let src = self.crop_to_canvas(enc, src);
922 let fg = match fg_id {
923 Some(id) => {
924 let fg = self.eval_node(comp, id, time, enc, visiting, stats);
925 self.crop_to_canvas(enc, fg)
926 }
927 None => self.dummy.clone(),
928 };
929 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
930 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
931 let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
932
933 // Without a map Displace is an identity warp; only MultiplyByMask still applies.
934 let mapped = if fg_id.is_some() { 1.0 } else { 0.0 };
935 let kind = if fg_id.is_some() { comp.eval_number(node, "Type", time, 0.0, &self.expr) as f32 } else { 1.0 };
936 let xr = comp.eval_number(node, "XRefraction", time, 0.0, &self.expr) as f32 * mapped;
937 let yr = comp.eval_number(node, "YRefraction", time, 0.0, &self.expr) as f32 * mapped;
938 let xo = comp.eval_number(node, "XOffset", time, 0.0, &self.expr) as f32;
939 let yo = comp.eval_number(node, "YOffset", time, 0.0, &self.expr) as f32;
940 let xch = comp.eval_number(node, "XChannel", time, 0.0, &self.expr) as f32;
941 let ych = comp.eval_number(node, "YChannel", time, 1.0, &self.expr) as f32;
942 let strength = comp.eval_number(node, "RefractionStrength", time, 0.05, &self.expr) as f32 * mapped;
943 let spread = comp.eval_number(node, "Spread", time, 0.0, &self.expr) as f32 * mapped;
944 let light_power = comp.eval_number(node, "LightPower", time, 0.0, &self.expr).max(0.0) as f32 * mapped;
945 // The light direction is a diamond, not a circle: each axis ramps linearly between its +-1 plateaus.
946 let light_angle = comp.eval_number(node, "LightAngle", time, 135.0, &self.expr);
947 let from_deg = |deg: f64| ((deg + 180.0).rem_euclid(360.0) - 180.0).abs();
948 let light_dir = [
949 ((from_deg(light_angle) - 90.0) / 45.0).clamp(-1.0, 1.0) as f32,
950 ((90.0 - from_deg(light_angle - 90.0)) / 45.0).clamp(-1.0, 1.0) as f32,
951 ];
952 let light_channel = comp.eval_number(node, "LightChannel", time, 0.0, &self.expr) as f32;
953 let offset = comp.eval_number(node, "Offset", time, 0.0, &self.expr) as f32;
954 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
955 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
956
957 let mut u = UniformParams::default();
958 u.p[0] = [kind, xr, yr, xo];
959 u.p[1] = [yo, strength, blend, if mask.is_some() { 1.0 } else { 0.0 }];
960 u.p[2] = [if mask_inv { 1.0 } else { 0.0 }, spread, light_power, offset];
961 u.p[3] = [center[0] as f32, center[1] as f32, xch, ych];
962 u.p[4] = [light_dir[0], light_dir[1], if mbm { 1.0 } else { 0.0 }, light_channel];
963
964 let key = self.make_key(node, "Displace", src.size, &[src.content_hash, fg.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..5]));
965 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
966 stats.cache_hits += 1;
967 return hit;
968 }
969 stats.cache_misses += 1;
970 stats.nodes_evaluated += 1;
971 let dst = self.alloc_tex_like(&src, src.depth, key);
972 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
973 if light_power <= 1e-6 {
974 self.dispatch_op(enc, ShaderOp::Displace, &src.view, &fg.view, mv, &dst, &u);
975 } else {
976 let displaced = self.alloc_tex_like(&src, src.depth, 0);
977 self.dispatch_op(enc, ShaderOp::Displace, &src.view, &fg.view, mv, &displaced, &u);
978 // The Gaussian commutes with the central difference, so blur the height map once.
979 let sigma = if spread > 1e-4 { 0.3 + spread * src.size[0] as f32 / 240.0 } else { 0.0 };
980 let height = self.blur_separable(enc, &fg, sigma / 0.45, sigma / 0.45, 0.0, 1.0);
981 let mut lit = u;
982 lit.p[5][0] = 1.0;
983 self.dispatch_op(enc, ShaderOp::Displace, &displaced.view, &height.view, mv, &dst, &lit);
984 }
985 self.cache.insert(key, dst.clone(), node.id, frame_i);
986 dst
987 }
988
989 #[allow(clippy::too_many_arguments)]
990 pub(super) fn eval_vortex(
991 &mut self,
992 comp: &Comp,
993 node: &Node,
994 time: f64,
995 frame_i: i64,
996 enc: &mut wgpu::CommandEncoder,
997 visiting: &mut HashSet<(NodeId, i64)>,
998 stats: &mut EvalStats,
999 ) -> CachedTexture {
1000 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1001 return self.dummy.clone();
1002 };
1003 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1004 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1005 let angle_deg = comp.eval_number(node, "Angle", time, 180.0, &self.expr) as f32;
1006 if blend <= 1e-6 || (angle_deg.abs() <= 1e-5 && !self.multiplies_by_mask(comp, node, time)) {
1007 return src;
1008 }
1009 let skip = self.process_skip(comp, node, time);
1010 if skip.iter().all(|&s| s > 0.5) && !self.multiplies_by_mask(comp, node, time) {
1011 return src;
1012 }
1013 let src = self.crop_to_canvas(enc, src);
1014 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1015 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1016 let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
1017 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
1018 let size = comp.eval_number(node, "Size", time, 0.5, &self.expr).max(1e-4) as f32;
1019 let power = comp.eval_number(node, "Power", time, 2.0, &self.expr).max(0.0) as f32;
1020
1021 let mut u = UniformParams::default();
1022 u.p[0] = [center[0] as f32, center[1] as f32, size * 0.5, angle_deg.to_radians()];
1023 u.p[1] = [power, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
1024 u.p[2][0] = if mbm { 1.0 } else { 0.0 };
1025 u.p[3] = skip;
1026
1027 let key = self.make_key(node, "Vortex", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..4]));
1028 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1029 stats.cache_hits += 1;
1030 return hit;
1031 }
1032 stats.cache_misses += 1;
1033 stats.nodes_evaluated += 1;
1034 let dst = self.alloc_tex_like(&src, src.depth, key);
1035 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1036 self.dispatch_op(enc, ShaderOp::Vortex, &src.view, &self.dummy.view, mv, &dst, &u);
1037 self.cache.insert(key, dst.clone(), node.id, frame_i);
1038 dst
1039 }
1040
1041 /// Row-major projective matrix (`h22 = 1`) taking the unit square's `(bl, br, tr, tl)` corners to the given quad.
1042 fn quad_homography(bl: [f64; 2], br: [f64; 2], tr: [f64; 2], tl: [f64; 2]) -> Option<[f64; 9]> {
1043 let dx1 = br[0] - tr[0];
1044 let dy1 = br[1] - tr[1];
1045 let dx2 = tl[0] - tr[0];
1046 let dy2 = tl[1] - tr[1];
1047 let sx = bl[0] - br[0] + tr[0] - tl[0];
1048 let sy = bl[1] - br[1] + tr[1] - tl[1];
1049 let denom = dx1 * dy2 - dx2 * dy1;
1050 if denom.abs() < 1e-10 {
1051 return None;
1052 }
1053 let g = (sx * dy2 - sy * dx2) / denom;
1054 let h = (dx1 * sy - dy1 * sx) / denom;
1055 Some([
1056 br[0] - bl[0] + g * br[0],
1057 tl[0] - bl[0] + h * tl[0],
1058 bl[0],
1059 br[1] - bl[1] + g * br[1],
1060 tl[1] - bl[1] + h * tl[1],
1061 bl[1],
1062 g,
1063 h,
1064 1.0,
1065 ])
1066 }
1067
1068 /// Adjugate (inverse up to scale) of a row-major 3x3 matrix.
1069 fn adjugate(m: &[f64; 9]) -> [f64; 9] {
1070 let [a, b, c, d, e, f, g, h, i] = *m;
1071 [e * i - f * h, c * h - b * i, b * f - c * e, f * g - d * i, a * i - c * g, c * d - a * f, d * h - e * g, b * g - a * h, a * e - b * d]
1072 }
1073
1074 fn mat_mul(a: &[f64; 9], b: &[f64; 9]) -> [f64; 9] {
1075 std::array::from_fn(|k| (0..3).map(|j| a[k / 3 * 3 + j] * b[j * 3 + k % 3]).sum())
1076 }
1077
1078 /// Inverse 3x3 projective homography mapping destination quad `(bl, br, tr, tl)` back to unit square `[0,1]^2`.
1079 pub(super) fn quad_inverse_homography(bl: [f64; 2], br: [f64; 2], tr: [f64; 2], tl: [f64; 2]) -> [f32; 9] {
1080 Self::quad_homography(bl, br, tr, tl)
1081 .map_or([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], |h| Self::adjugate(&h).map(|v| v as f32))
1082 }
1083
1084 pub(super) fn eval_corner_positioner(
1085 &mut self,
1086 comp: &Comp,
1087 node: &Node,
1088 time: f64,
1089 frame_i: i64,
1090 enc: &mut wgpu::CommandEncoder,
1091 visiting: &mut HashSet<(NodeId, i64)>,
1092 stats: &mut EvalStats,
1093 ) -> CachedTexture {
1094 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1095 return self.dummy.clone();
1096 };
1097 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1098 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1099 if blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) {
1100 return src;
1101 }
1102 let src = self.crop_to_canvas(enc, src);
1103 // Corner `Offset`s shift the matching source-UV corner against the offset, so positive values extend the sampled quad.
1104 let corner = |name: &str, default: [f64; 2]| {
1105 let p = comp.eval_point(node, name, time, default, &self.expr);
1106 let off = [
1107 comp.eval_number(node, &format!("{name}OffsetX"), time, 0.0, &self.expr),
1108 comp.eval_number(node, &format!("{name}OffsetY"), time, 0.0, &self.expr),
1109 ];
1110 (p, off)
1111 };
1112 let [(bl, bl_o), (br, br_o), (tr, tr_o), (tl, tl_o)] = [
1113 corner("BottomLeft", [0.0, 0.3]),
1114 corner("BottomRight", [1.0, 0.1]),
1115 corner("TopRight", [0.9, 1.0]),
1116 corner("TopLeft", [0.1, 0.9]),
1117 ];
1118 let src_uv = |u: [f64; 2], o: [f64; 2]| [u[0] - o[0], u[1] - o[1]];
1119 let (s_bl, s_br, s_tr, s_tl) = (src_uv([0.0, 0.0], bl_o), src_uv([1.0, 0.0], br_o), src_uv([1.0, 1.0], tr_o), src_uv([0.0, 1.0], tl_o));
1120 let h_inv = match (Self::quad_homography(bl, br, tr, tl), Self::quad_homography(s_bl, s_br, s_tr, s_tl)) {
1121 (Some(out), Some(src)) => Self::mat_mul(&src, &Self::adjugate(&out)).map(|v| v as f32),
1122 _ => [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
1123 };
1124 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1125 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1126 let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
1127
1128 let mut u = UniformParams::default();
1129 u.p[0] = [h_inv[0], h_inv[1], h_inv[2], h_inv[3]];
1130 u.p[1] = [h_inv[4], h_inv[5], h_inv[6], h_inv[7]];
1131 u.p[2] = [h_inv[8], blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
1132 u.p[3][1] = if mbm { 1.0 } else { 0.0 };
1133 if comp.eval_number(node, "MappingType", time, 1.0, &self.expr) < 0.5 {
1134 u.p[3][3] = 1.0;
1135 let add_off = |p: [f64; 2], o: [f64; 2]| [p[0] + o[0], p[1] + o[1]];
1136 let quads = [
1137 [add_off(bl, bl_o), add_off(br, br_o)],
1138 [add_off(tr, tr_o), add_off(tl, tl_o)],
1139 [[0.0, 0.0], [1.0, 0.0]],
1140 [[1.0, 1.0], [0.0, 1.0]],
1141 ];
1142 for (row, pts) in quads.iter().enumerate() {
1143 u.p[6 + row] = [pts[0][0] as f32, pts[0][1] as f32, pts[1][0] as f32, pts[1][1] as f32];
1144 }
1145 }
1146 u.p[5] = self.process_skip(comp, node, time);
1147 let key = self.make_key(node, "CornerPos", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..10]));
1148 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1149 stats.cache_hits += 1;
1150 return hit;
1151 }
1152 stats.cache_misses += 1;
1153 stats.nodes_evaluated += 1;
1154 let dst = self.alloc_tex_like(&src, src.depth, key);
1155 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1156 self.dispatch_op(enc, ShaderOp::Homography, &src.view, &self.dummy.view, mv, &dst, &u);
1157 self.cache.insert(key, dst.clone(), node.id, frame_i);
1158 dst
1159 }
1160
1161 pub(super) fn eval_dve(
1162 &mut self,
1163 comp: &Comp,
1164 node: &Node,
1165 time: f64,
1166 frame_i: i64,
1167 enc: &mut wgpu::CommandEncoder,
1168 visiting: &mut HashSet<(NodeId, i64)>,
1169 stats: &mut EvalStats,
1170 ) -> CachedTexture {
1171 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1172 return self.dummy.clone();
1173 };
1174 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1175 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1176 if blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) {
1177 return src;
1178 }
1179 let skip = self.process_skip(comp, node, time);
1180 if skip.iter().all(|&s| s > 0.5) {
1181 return src;
1182 }
1183 let src = self.crop_to_canvas(enc, src);
1184 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
1185 let pivot = comp.eval_point(node, "Pivot", time, [0.5, 0.5], &self.expr);
1186 let z_pivot = comp.eval_number(node, "ZPivot", time, 0.0, &self.expr);
1187 let z_move = comp.eval_number(node, "ZMove", time, 1.0, &self.expr);
1188 let rx = comp.eval_number(node, "XRotation", time, 0.0, &self.expr).to_radians();
1189 let ry = comp.eval_number(node, "YRotation", time, 0.0, &self.expr).to_radians();
1190 let rz = comp.eval_number(node, "ZRotation", time, 0.0, &self.expr).to_radians();
1191 let x_shear = comp.eval_number(node, "XShear", time, 0.0, &self.expr);
1192 let y_shear = comp.eval_number(node, "YShear", time, 0.0, &self.expr);
1193 let rot_order = match node.static_str("RotationOrder") {
1194 Some(s) => s,
1195 None => match comp.eval_number(node, "RotationOrder", time, 5.0, &self.expr).round() as i32 {
1196 0 => "XYZ",
1197 1 => "XZY",
1198 2 => "YXZ",
1199 3 => "YZX",
1200 4 => "ZXY",
1201 _ => "ZYX",
1202 },
1203 };
1204 let aspect = src.canvas_size[0] as f64 / src.canvas_size[1].max(1) as f64;
1205
1206 // Fusion DVE rotates card corners around Pivot (starting at z = +ZPivot so ZPivot > 0 moves
1207 // the card away from the camera even at 0 rotation), applies XShear/YShear, and projects with 1 / (ZMove + z).
1208 let (sx, cx) = rx.sin_cos();
1209 let (sy, cy) = ry.sin_cos();
1210 let (sz, cz) = rz.sin_cos();
1211 let project = |u_c: f64, v_c: f64| -> [f64; 2] {
1212 let rx0 = u_c - pivot[0];
1213 let ry0 = (v_c - pivot[1]) / aspect;
1214 let mut x = rx0 - x_shear * ry0;
1215 let mut y = ry0 - y_shear * rx0;
1216 let mut z = z_pivot;
1217 for b in rot_order.bytes() {
1218 match b {
1219 b'X' | b'x' => {
1220 let ny = y * cx + z * sx;
1221 let nz = -y * sx + z * cx;
1222 y = ny;
1223 z = nz;
1224 }
1225 b'Y' | b'y' => {
1226 let nx = x * cy - z * sy;
1227 let nz = x * sy + z * cy;
1228 x = nx;
1229 z = nz;
1230 }
1231 b'Z' | b'z' => {
1232 let nx = x * cz - y * sz;
1233 let ny = x * sz + y * cz;
1234 x = nx;
1235 y = ny;
1236 }
1237 _ => {}
1238 }
1239 }
1240 let z_cam = (z_move + z).max(0.05);
1241 let inv_z = 1.0 / z_cam;
1242 [
1243 pivot[0] + (x + (center[0] - 0.5) * z_move) * inv_z,
1244 pivot[1] + ((y + (center[1] - 0.5) / aspect * z_move) * aspect) * inv_z,
1245 ]
1246 };
1247 let bl = project(0.0, 0.0);
1248 let br = project(1.0, 0.0);
1249 let tr = project(1.0, 1.0);
1250 let tl = project(0.0, 1.0);
1251 let h_inv = Self::quad_inverse_homography(bl, br, tr, tl);
1252
1253 // Expand DoD when projected card corners extend beyond canvas (so downstream Merge preserves edges)
1254 let cw = src.canvas_size[0].max(1) as f64;
1255 let ch = src.canvas_size[1].max(1) as f64;
1256 let mut min_x = cw;
1257 let mut max_x = 0.0_f64;
1258 let mut min_y = ch;
1259 let mut max_y = 0.0_f64;
1260 for c in [bl, br, tr, tl] {
1261 let px = c[0] * cw;
1262 let py = (1.0 - c[1]) * ch;
1263 min_x = min_x.min(px);
1264 max_x = max_x.max(px);
1265 min_y = min_y.min(py);
1266 max_y = max_y.max(py);
1267 }
1268 let pad = 2_i32;
1269 let max_pad = 1024_i32;
1270 let x0 = if min_x < -0.25 { (min_x.floor() as i32 - pad).max(-max_pad) } else { 0 };
1271 let y0 = if min_y < -0.25 { (min_y.floor() as i32 - pad).max(-max_pad) } else { 0 };
1272 let x1 = if max_x > cw + 0.25 {
1273 (max_x.ceil() as i32 + pad).min(src.canvas_size[0] as i32 + max_pad)
1274 } else {
1275 src.canvas_size[0] as i32
1276 };
1277 let y1 = if max_y > ch + 0.25 {
1278 (max_y.ceil() as i32 + pad).min(src.canvas_size[1] as i32 + max_pad)
1279 } else {
1280 src.canvas_size[1] as i32
1281 };
1282 let dst_origin = [x0, y0];
1283 let dst_size = [(x1 - x0).max(1) as u32, (y1 - y0).max(1) as u32];
1284 let has_dst_dod = dst_origin != [0, 0] || dst_size != src.canvas_size;
1285
1286 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.canvas_size), enc, visiting, stats);
1287 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1288 let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
1289
1290 let mut u = UniformParams::default();
1291 u.p[0] = [h_inv[0], h_inv[1], h_inv[2], h_inv[3]];
1292 u.p[1] = [h_inv[4], h_inv[5], h_inv[6], h_inv[7]];
1293 u.p[2] = [h_inv[8], blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
1294 u.p[3] = [0.0, if mbm { 1.0 } else { 0.0 }, 0.0, 0.0];
1295 if has_dst_dod {
1296 u.p[4] = [
1297 dst_origin[0] as f32,
1298 dst_origin[1] as f32,
1299 src.canvas_size[0] as f32,
1300 src.canvas_size[1] as f32,
1301 ];
1302 }
1303 u.p[5] = skip;
1304 let key = self.make_key(node, "DVE", dst_size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..6]));
1305 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1306 stats.cache_hits += 1;
1307 return hit;
1308 }
1309 stats.cache_misses += 1;
1310 stats.nodes_evaluated += 1;
1311 let mut dst = self.alloc_tex_dod(dst_size, dst_origin, src.canvas_size, src.depth, key);
1312 dst.tex_scale *= src.tex_scale;
1313 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1314 self.dispatch_op(enc, ShaderOp::Homography, &src.view, &self.dummy.view, mv, &dst, &u);
1315 self.cache.insert(key, dst.clone(), node.id, frame_i);
1316 dst
1317 }
1318
1319 #[allow(clippy::too_many_arguments)]
1320 fn camera_shake_offset(
1321 time: f64,
1322 x_dev: f64,
1323 y_dev: f64,
1324 r_dev: f64,
1325 strength: f64,
1326 speed: f64,
1327 randomness: f64,
1328 method: i32,
1329 ) -> (f32, f32, f32) {
1330 let x_dev = x_dev.clamp(0.0, 1.0);
1331 let y_dev = y_dev.clamp(0.0, 1.0);
1332 let r_dev = r_dev.clamp(0.0, 1.0);
1333 let speed = speed.clamp(0.0, 1.0);
1334 let randomness = randomness.clamp(0.0, 1.0);
1335
1336 // Probed Fusion 21.1: angular rate is `0.3 / (1.1 - Speed)` rad/frame;
1337 // X uses sin(rate*t) + Randomness offset, Y uses cos(sqrt(0.75)*rate*(t + dt_y)),
1338 // Rotation uses 5 deg * sin(1.1*rate*(t + dt_r)) with dt_r ~ Randomness^2.
1339 let rate = 0.3 / (1.1 - speed);
1340 let wave_sin = |theta: f64| -> f64 {
1341 match method {
1342 1 => 2.0 * (theta * 0.5).sin().abs() - 1.0,
1343 2 => if theta.sin() > 0.0 { 1.0 } else { -1.0 },
1344 _ => theta.sin(),
1345 }
1346 };
1347 let wave_cos = |theta: f64| -> f64 {
1348 match method {
1349 1 => 2.0 * (theta * 0.5).cos().abs() - 1.0,
1350 2 => if theta.cos() > 0.0 { 1.0 } else { -1.0 },
1351 _ => theta.cos(),
1352 }
1353 };
1354 let time_band = |at_0: f64, at_1: f64, at_neg1: f64, steady: f64| -> f64 {
1355 if time.abs() < 0.5 {
1356 at_0
1357 } else if (time - 1.0).abs() < 0.5 {
1358 at_1
1359 } else if (time + 1.0).abs() < 0.5 {
1360 at_neg1
1361 } else {
1362 steady
1363 }
1364 };
1365 let x_rand = time_band(0.3125, 0.44, 0.39, 1.0 / 3.0) * randomness;
1366 let dt_y = time_band(-0.84, 1.10, -0.66, -1.547) * randomness;
1367 let dt_r = time_band(0.83, 0.23, 0.25, 0.511) * (randomness * randomness);
1368
1369 let dx = x_dev * strength * 0.2 * (wave_sin(rate * time) + x_rand);
1370 let dy = y_dev * strength * 0.2 * wave_cos(0.75_f64.sqrt() * rate * (time + dt_y));
1371 let angle = (r_dev * strength * 5.0 * wave_sin(1.1 * rate * (time + dt_r))).to_radians() as f32;
1372 (dx as f32, dy as f32, angle)
1373 }
1374
1375 pub(super) fn eval_camera_shake(
1376 &mut self,
1377 comp: &Comp,
1378 node: &Node,
1379 time: f64,
1380 frame_i: i64,
1381 enc: &mut wgpu::CommandEncoder,
1382 visiting: &mut HashSet<(NodeId, i64)>,
1383 stats: &mut EvalStats,
1384 ) -> CachedTexture {
1385 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1386 return self.dummy.clone();
1387 };
1388 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1389 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1390 let strength = comp.eval_number(node, "OverallStrength", time, 1.0, &self.expr);
1391 if (blend <= 1e-6 || strength.abs() <= 1e-6) && !self.multiplies_by_mask(comp, node, time) {
1392 return src;
1393 }
1394 let x_dev = comp.eval_number(node, "XDeviation", time, 0.2, &self.expr);
1395 let y_dev = comp.eval_number(node, "YDeviation", time, 0.2, &self.expr);
1396 let r_dev = comp.eval_number(node, "RotationDeviation", time, 0.2, &self.expr);
1397 let speed = comp.eval_number(node, "Speed", time, 0.8, &self.expr);
1398 let randomness = comp.eval_number(node, "Randomness", time, 0.5, &self.expr);
1399 let method = comp.eval_number(node, "FrequencyMethod", time, 0.0, &self.expr).round() as i32;
1400 let edges = comp.eval_number(node, "Edges", time, 0.0, &self.expr) as f32;
1401 let nearest = if comp.eval_number(node, "FilterMethod", time, 2.0, &self.expr) < 0.5 { 1.0 } else { 0.0 };
1402
1403 let (dx, dy, angle) = Self::camera_shake_offset(time, x_dev, y_dev, r_dev, strength, speed, randomness, method);
1404 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.canvas_size), enc, visiting, stats);
1405 let mask = mask.map(|m| self.crop_to_canvas(enc, m));
1406 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1407
1408 let mut u = UniformParams::default();
1409 u.p[0] = [0.5 + dx, 0.5 + dy, 0.5, 0.5];
1410 u.p[1] = [1.0, 1.0, angle, edges];
1411 u.p[2] = [0.0, 0.0, blend, if mask.is_some() { 1.0 } else { 0.0 }];
1412 let invert = comp.eval_number(node, "InvertTransform", time, 0.0, &self.expr) > 0.5;
1413 let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
1414 u.p[3] = [if mask_inv { 1.0 } else { 0.0 }, nearest, if mbm { 1.0 } else { 0.0 }, if invert { 1.0 } else { 0.0 }];
1415 if src.has_dod() {
1416 u.p[4] = [
1417 src.origin[0] as f32,
1418 src.origin[1] as f32,
1419 src.canvas_size[0] as f32,
1420 src.canvas_size[1] as f32,
1421 ];
1422 }
1423 u.p[6] = self.process_skip(comp, node, time);
1424 let out_size = src.canvas_size;
1425 let key = self.make_key(node, "CamShake", out_size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..7]));
1426 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1427 stats.cache_hits += 1;
1428 return hit;
1429 }
1430 stats.cache_misses += 1;
1431 stats.nodes_evaluated += 1;
1432 let mut dst = self.alloc_tex(out_size, src.depth, key);
1433 dst.tex_scale *= src.tex_scale;
1434 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1435 self.dispatch_op(enc, ShaderOp::Transform, &src.view, &self.dummy.view, mv, &dst, &u);
1436 self.cache.insert(key, dst.clone(), node.id, frame_i);
1437 dst
1438 }
1439
1440 pub(super) fn eval_duplicate(
1441 &mut self,
1442 comp: &Comp,
1443 node: &Node,
1444 time: f64,
1445 frame_i: i64,
1446 enc: &mut wgpu::CommandEncoder,
1447 visiting: &mut HashSet<(NodeId, i64)>,
1448 stats: &mut EvalStats,
1449 ) -> CachedTexture {
1450 let Some(src_id) = node
1451 .connected_node("Background")
1452 .or_else(|| node.connected_node("Input"))
1453 .and_then(|s| comp.find_node(s))
1454 else {
1455 return self.dummy.clone();
1456 };
1457 let base = self.eval_node(comp, src_id, time, enc, visiting, stats);
1458 let copies_f = comp.eval_number(node, "Copies", time, 2.0, &self.expr).clamp(0.0, 64.0) as f32;
1459 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1460 let mbm = self.multiplies_by_mask(comp, node, time);
1461 let proc_b0 = comp.eval_number(node, "ProcessWhenBlendIs00", time, 0.0, &self.expr) > 0.5;
1462 if blend <= 1e-6 && !mbm && !proc_b0 {
1463 return base;
1464 }
1465 let skip = self.process_skip(comp, node, time);
1466 if skip.iter().all(|&s| s > 0.5) && !mbm {
1467 return base;
1468 }
1469 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
1470 let pivot = comp.eval_point(node, "Pivot", time, [0.5, 0.5], &self.expr);
1471 let lock_size = comp.eval_number(node, "LockSize", time, 1.0, &self.expr) > 0.5;
1472 let fallback_size = comp.eval_number(node, "Size", time, 1.0, &self.expr);
1473 let x_size = comp.eval_number(node, "XSize", time, fallback_size, &self.expr) as f32;
1474 let y_size = if lock_size { x_size } else { comp.eval_number(node, "YSize", time, 1.0, &self.expr) as f32 };
1475 let angle_deg = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32;
1476 let fallback_gain = comp.eval_number(node, "Gain", time, 1.0, &self.expr);
1477 let red_gain = comp.eval_number(node, "RedGain", time, fallback_gain, &self.expr) as f32;
1478 let green_gain = comp.eval_number(node, "GreenGain", time, fallback_gain, &self.expr) as f32;
1479 let blue_gain = comp.eval_number(node, "BlueGain", time, fallback_gain, &self.expr) as f32;
1480 let alpha_gain = comp.eval_number(node, "AlphaGain", time, fallback_gain, &self.expr) as f32;
1481 let sub_add = comp.eval_number(node, "SubtractiveAdditive", time, 1.0, &self.expr) as f32;
1482 let burn_in = comp.eval_number(node, "BurnIn", time, 0.0, &self.expr) as f32;
1483 let time_off = comp.eval_number(node, "TimeOffset", time, 0.0, &self.expr);
1484 let merge_under = comp.eval_number(node, "MergeUnder", time, 0.0, &self.expr) > 0.5;
1485 let layer_blend = comp.eval_number(node, "LayerBlend", time, 1.0, &self.expr) as f32;
1486 let random_seed = comp.eval_number(node, "RandomSeed", time, 0.0, &self.expr);
1487 let j_center = comp.eval_point(node, "JitterCenter", time, [0.0, 0.0], &self.expr);
1488 let j_pivot = comp.eval_point(node, "JitterPivot", time, [0.0, 0.0], &self.expr);
1489 let j_lock_size = comp.eval_number(node, "JitterLockSize", time, 1.0, &self.expr) > 0.5;
1490 let j_x_size = comp.eval_number(node, "JitterXSize", time, 0.0, &self.expr) as f32;
1491 let j_y_size = if j_lock_size {
1492 j_x_size
1493 } else {
1494 comp.eval_number(node, "JitterYSize", time, 0.0, &self.expr) as f32
1495 };
1496 let j_angle = comp.eval_number(node, "JitterAngle", time, 0.0, &self.expr) as f32;
1497 let j_red_gain = comp.eval_number(node, "JitterRedGain", time, 0.0, &self.expr) as f32;
1498 let j_green_gain = comp.eval_number(node, "JitterGreenGain", time, 0.0, &self.expr) as f32;
1499 let j_blue_gain = comp.eval_number(node, "JitterBlueGain", time, 0.0, &self.expr) as f32;
1500 let j_alpha_gain = comp.eval_number(node, "JitterAlphaGain", time, 0.0, &self.expr) as f32;
1501 let j_layer_blend = comp.eval_number(node, "JitterLayerBlend", time, 0.0, &self.expr) as f32;
1502 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(base.size), enc, visiting, stats);
1503 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1504
1505 let params = [
1506 copies_f,
1507 center[0] as f32,
1508 center[1] as f32,
1509 pivot[0] as f32,
1510 pivot[1] as f32,
1511 x_size,
1512 y_size,
1513 angle_deg,
1514 red_gain,
1515 green_gain,
1516 blue_gain,
1517 alpha_gain,
1518 sub_add,
1519 burn_in,
1520 blend,
1521 time_off as f32,
1522 if merge_under { 1.0 } else { 0.0 },
1523 if mbm { 1.0 } else { 0.0 },
1524 if proc_b0 { 1.0 } else { 0.0 },
1525 skip[0],
1526 skip[1],
1527 skip[2],
1528 skip[3],
1529 layer_blend,
1530 random_seed as f32,
1531 j_center[0] as f32,
1532 j_center[1] as f32,
1533 j_pivot[0] as f32,
1534 j_pivot[1] as f32,
1535 if j_lock_size { 1.0 } else { 0.0 },
1536 j_x_size,
1537 j_y_size,
1538 j_angle,
1539 j_red_gain,
1540 j_green_gain,
1541 j_blue_gain,
1542 j_alpha_gain,
1543 j_layer_blend,
1544 ];
1545 let key = self.make_key(node, "Duplicate", base.size, &[base.content_hash, mask_hash], &params);
1546 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1547 stats.cache_hits += 1;
1548 return hit;
1549 }
1550 stats.cache_misses += 1;
1551 stats.nodes_evaluated += 1;
1552
1553 let need_post = mask.is_some()
1554 || (blend - 1.0).abs() > 1e-5
1555 || skip.iter().any(|&s| s > 0.5);
1556
1557 let mut accum = if copies_f <= 1.0 + 1e-4 {
1558 let w = copies_f.clamp(0.0, 1.0);
1559 if w >= 1.0 - 1e-4 {
1560 base.clone()
1561 } else {
1562 let scaled = self.alloc_tex_like(&base, base.depth, if need_post { 0 } else { key });
1563 let mut u = UniformParams::default();
1564 u.p[0] = [0.5, 0.5, 1.0, 0.0];
1565 u.p[1] = [w, 1.0, 0.0, 0.0];
1566 u.p[3] = [0.0, 0.0, base.canvas_size[0] as f32, base.canvas_size[1] as f32];
1567 u.p[6] = [0.0, 1.0, 0.0, 0.0];
1568 let zero = create_texture(&self.device, base.size, 0);
1569 self.dispatch_op(enc, ShaderOp::Merge, &zero.view, &base.view, &self.dummy.view, &scaled, &u);
1570 scaled
1571 }
1572 } else {
1573 let full = copies_f.floor() as i32;
1574 let frac = copies_f - full as f32;
1575 let n_extra = (copies_f.ceil() as i32 - 1).max(1);
1576 let dx = center[0] as f32 - 0.5;
1577 let dy = center[1] as f32 - 0.5;
1578 let any_jitter = j_center[0].abs() > 1e-6
1579 || j_center[1].abs() > 1e-6
1580 || j_pivot[0].abs() > 1e-6
1581 || j_pivot[1].abs() > 1e-6
1582 || j_x_size.abs() > 1e-6
1583 || j_y_size.abs() > 1e-6
1584 || j_angle.abs() > 1e-6
1585 || j_red_gain.abs() > 1e-6
1586 || j_green_gain.abs() > 1e-6
1587 || j_blue_gain.abs() > 1e-6
1588 || j_alpha_gain.abs() > 1e-6
1589 || j_layer_blend.abs() > 1e-6;
1590 let mut prng = any_jitter.then(|| LuaJitPrng::new(random_seed));
1591 let mut cur_acc = base.clone();
1592 for i in 1..=n_extra {
1593 let fi = i as f32;
1594 let draws = if let Some(rng) = prng.as_mut() {
1595 [
1596 rng.next_signed(),
1597 rng.next_signed(),
1598 rng.next_signed(),
1599 rng.next_signed(),
1600 rng.next_signed(),
1601 rng.next_signed(),
1602 rng.next_signed(),
1603 rng.next_signed(),
1604 rng.next_signed(),
1605 rng.next_signed(),
1606 rng.next_signed(),
1607 rng.next_signed(),
1608 ]
1609 } else {
1610 [0.0; 12]
1611 };
1612 let d_ys = if j_lock_size { draws[4] } else { draws[5] };
1613 let mut copy_src = if time_off.abs() > 1e-4 {
1614 self.eval_node(comp, src_id, time + (i as f64) * time_off, enc, visiting, stats)
1615 } else {
1616 base.clone()
1617 };
1618 let layer_w_base = (layer_blend + j_layer_blend * draws[11]).max(0.0);
1619 let layer_w_raw = if i == n_extra && frac > 1e-4 {
1620 layer_w_base * frac
1621 } else {
1622 layer_w_base
1623 };
1624 let (layer_scale_fg, layer_w) = if layer_w_raw > 1.0 + 1e-4 {
1625 (layer_w_raw, 1.0)
1626 } else {
1627 (1.0, layer_w_raw)
1628 };
1629 let rg_i = (red_gain.powi(i) + j_red_gain * draws[7]).max(0.0) * layer_scale_fg;
1630 let gg_i = (green_gain.powi(i) + j_green_gain * draws[8]).max(0.0) * layer_scale_fg;
1631 let bg_i = (blue_gain.powi(i) + j_blue_gain * draws[9]).max(0.0) * layer_scale_fg;
1632 if (rg_i - 1.0).abs() > 1e-4 || (gg_i - 1.0).abs() > 1e-4 || (bg_i - 1.0).abs() > 1e-4 {
1633 let gained = self.alloc_tex_like(&copy_src, copy_src.depth, 0);
1634 let mut ug = UniformParams::default();
1635 ug.p[0] = [rg_i, gg_i, bg_i, 0.0];
1636 ug.p[1] = [0.0, 0.0, 0.0, 1.0];
1637 ug.p[2] = [1.0, 1.0, 1.0, 1.0];
1638 ug.p[4] = [0.0, 1.0, 1.0, 0.0];
1639 ug.p[9] = [1.0, 0.0, 1.0, 0.0];
1640 self.dispatch_op(enc, ShaderOp::ColorGain, &copy_src.view, &self.dummy.view, &self.dummy.view, &gained, &ug);
1641 copy_src = gained;
1642 }
1643 let ag_raw = (alpha_gain.powi(i) + j_alpha_gain * draws[10]).max(0.0) * layer_scale_fg;
1644 let ag_i = if ag_raw > 1.0 + 1e-4 {
1645 let gained_a = self.alloc_tex_like(&copy_src, copy_src.depth, 0);
1646 let mut ubc = UniformParams::default();
1647 ubc.p[0] = [ag_raw, 0.0, 1.0, 0.0];
1648 ubc.p[1] = [0.0, 1.0, 0.0, 1.0];
1649 ubc.p[2] = [0.0, 0.0, 0.0, 1.0];
1650 ubc.p[3] = [0.0, 0.0, 0.0, 1.0];
1651 ubc.p[4] = [1.0, 1.0, 0.0, 0.0];
1652 self.dispatch_op(enc, ShaderOp::Bc, &copy_src.view, &self.dummy.view, &self.dummy.view, &gained_a, &ubc);
1653 copy_src = gained_a;
1654 1.0
1655 } else {
1656 ag_raw.clamp(0.0, 1.0)
1657 };
1658 let cx = 0.5 + dx * fi + (j_center[0] as f32) * draws[0];
1659 let cy = 0.5 + dy * fi + (j_center[1] as f32) * draws[1];
1660 let px = pivot[0] as f32 + (j_pivot[0] as f32) * draws[2];
1661 let py = pivot[1] as f32 + (j_pivot[1] as f32) * draws[3];
1662 let sc_x = (x_size.powi(i) + j_x_size * draws[4]).max(1e-4);
1663 let sc_y = (y_size.powi(i) + j_y_size * d_ys).max(1e-4);
1664 let ang = (angle_deg * fi + j_angle * draws[6]).to_radians();
1665 let need_xform = (sc_x - sc_y).abs() > 1e-4
1666 || (px - 0.5).abs() > 1e-4
1667 || (py - 0.5).abs() > 1e-4;
1668
1669 let is_last = i == n_extra;
1670 let next = self.alloc_tex_like(&base, base.depth, if is_last && !need_post { key } else { 0 });
1671 let mut u = UniformParams::default();
1672 if need_xform {
1673 let xformed = self.alloc_tex_like(&copy_src, copy_src.depth, 0);
1674 let mut ut = UniformParams::default();
1675 ut.p[0] = [cx, cy, px, py];
1676 ut.p[1] = [sc_x, sc_y, ang, 0.0];
1677 ut.p[2] = [0.0, 0.0, 1.0, 0.0];
1678 ut.p[3] = [0.0, 0.0, 0.0, 0.0];
1679 self.dispatch_op(enc, ShaderOp::Transform, &copy_src.view, &self.dummy.view, &self.dummy.view, &xformed, &ut);
1680 copy_src = xformed;
1681 u.p[0] = [0.5, 0.5, 1.0, 0.0];
1682 } else {
1683 u.p[0] = [cx, cy, sc_x, ang];
1684 }
1685 u.p[1] = [layer_w, ag_i, 0.0, 0.0];
1686 u.p[2] = [0.0, 0.0, 0.0, if merge_under { 1.0 } else { 0.0 }];
1687 u.p[3] = [0.0, 0.0, copy_src.canvas_size[0] as f32, copy_src.canvas_size[1] as f32];
1688 u.p[6] = [burn_in, sub_add, 0.0, 0.0];
1689 self.dispatch_op(enc, ShaderOp::Merge, &cur_acc.view, &copy_src.view, &self.dummy.view, &next, &u);
1690 cur_acc = next;
1691 }
1692 cur_acc
1693 };
1694
1695 if need_post {
1696 let out = self.alloc_tex_like(&base, base.depth, key);
1697 let mut ud = UniformParams::default();
1698 ud.p[0] = [
1699 1.0,
1700 blend,
1701 if mask.is_some() { 1.0 } else { 0.0 },
1702 if mask_inv { 1.0 } else { 0.0 },
1703 ];
1704 ud.p[1] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0];
1705 ud.p[2] = [1.0 - skip[0], 1.0 - skip[1], 1.0 - skip[2], 1.0 - skip[3]];
1706 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1707 self.dispatch_op(enc, ShaderOp::Dissolve, &base.view, &accum.view, mv, &out, &ud);
1708 accum = out;
1709 }
1710
1711 self.cache.insert(key, accum.clone(), node.id, frame_i);
1712 accum
1713 }
1714
1715 pub(super) fn eval_kscope(
1716 &mut self,
1717 comp: &Comp,
1718 node: &Node,
1719 time: f64,
1720 frame_i: i64,
1721 enc: &mut wgpu::CommandEncoder,
1722 visiting: &mut HashSet<(NodeId, i64)>,
1723 stats: &mut EvalStats,
1724 ) -> CachedTexture {
1725 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1726 return self.dummy.clone();
1727 };
1728 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1729 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1730 if blend <= 1e-6 {
1731 return src;
1732 }
1733 let src = self.crop_to_canvas(enc, src);
1734 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
1735 let slices = comp.eval_number(node, "Slices", time, 6.0, &self.expr).max(1.0) as f32;
1736 let angle = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians();
1737 let cap_angle = (comp.eval_number(node, "CaptureAngle", time, 0.0, &self.expr) as f32).to_radians();
1738 let scale = comp.eval_number(node, "Scale", time, 1.0, &self.expr).max(1e-4) as f32;
1739 let edges = comp.eval_number(node, "Edges", time, 3.0, &self.expr) as f32;
1740 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1741 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1742
1743 let mut u = UniformParams::default();
1744 u.p[0] = [center[0] as f32, center[1] as f32, slices, angle];
1745 u.p[1] = [cap_angle, scale, edges, blend];
1746 u.p[2] = [if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0];
1747
1748 let key = self.make_key(node, "KScope", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3]));
1749 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1750 stats.cache_hits += 1;
1751 return hit;
1752 }
1753 stats.cache_misses += 1;
1754 stats.nodes_evaluated += 1;
1755 let dst = self.alloc_tex_like(&src, src.depth, key);
1756 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1757 self.dispatch_op(enc, ShaderOp::KScope, &src.view, &self.dummy.view, mv, &dst, &u);
1758 self.cache.insert(key, dst.clone(), node.id, frame_i);
1759 dst
1760 }
1761}
1762
1763#[cfg(test)]
1764mod tests {
1765 use super::*;
1766 use crate::Engine;
1767
1768 #[test]
1769 fn test_fuse_kscope_6_slice_symmetry() {
1770 let src = r#"Composition {
1771 CurrentTime = 0,
1772 RenderRange = { 0, 1 },
1773 GlobalRange = { 0, 1 },
1774 Tools = ordered() {
1775 BG1 = Background {
1776 Inputs = {
1777 Width = Input { Value = 128, },
1778 Height = Input { Value = 128, },
1779 Type = Input { Value = FuID { "Horizontal" }, },
1780 TopLeftRed = Input { Value = 1.0, },
1781 TopLeftGreen = Input { Value = 0.0, },
1782 TopLeftBlue = Input { Value = 0.0, },
1783 TopRightRed = Input { Value = 0.0, },
1784 TopRightGreen = Input { Value = 0.0, },
1785 TopRightBlue = Input { Value = 1.0, },
1786 },
1787 },
1788 KS1 = Fuse.KScope {
1789 Inputs = {
1790 Input = Input { SourceOp = "BG1", Source = "Output", },
1791 Slices = Input { Value = 6, },
1792 Scale = Input { Value = 1.0, },
1793 },
1794 },
1795 },
1796 }"#;
1797 let comp = Comp::from_fusion_str(src).expect("parse KScope comp");
1798 let Ok(mut eng) = Engine::new_headless() else {
1799 return;
1800 };
1801 let node_id = comp.find_node("KS1").expect("KS1");
1802 let (tex, _) = eng.evaluate(&comp, node_id, 0.0);
1803 let rgba = eng.readback_rgba(&tex).expect("readback KScope");
1804 let [w, h] = tex.size;
1805 assert_eq!((w, h), (128, 128));
1806 // With Slices=6, sector=60 deg mirrored every 120 deg -> reflection across X axis is exact!
1807 let px = |x: usize, y: usize| -> [u8; 4] {
1808 let i = (y * 128 + x) * 4;
1809 [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
1810 };
1811 let a = px(64 + 28, 64 + 12);
1812 let b = px(64 + 28, 63 - 12);
1813 for c in 0..3 {
1814 let diff = (a[c] as i32 - b[c] as i32).abs();
1815 assert!(diff <= 2, "KScope 6-slice mirror symmetry mismatch ch={c}: {a:?} vs {b:?}");
1816 }
1817 }
1818
1819 #[test]
1820 fn test_upstream_infinite_edge_mode_propagates_through_point_ops_and_disabled_dirblur() {
1821 let src = r#"Composition {
1822 CurrentTime = 3050,
1823 RenderRange = { 3000, 3100 },
1824 GlobalRange = { 3000, 3100 },
1825 Tools = ordered() {
1826 BG1 = Background {
1827 Inputs = {
1828 Width = Input { Value = 64, },
1829 Height = Input { Value = 64, },
1830 TopLeftRed = Input { Value = 0.2, },
1831 TopLeftAlpha = Input { Value = 1.0, },
1832 },
1833 },
1834 FG1 = Background {
1835 Inputs = {
1836 Width = Input { Value = 64, },
1837 Height = Input { Value = 64, },
1838 Type = Input { Value = FuID { "Horizontal" }, },
1839 TopLeftRed = Input { Value = 1.0, },
1840 TopLeftGreen = Input { Value = 0.0, },
1841 TopLeftBlue = Input { Value = 0.0, },
1842 TopRightRed = Input { Value = 0.0, },
1843 TopRightGreen = Input { Value = 0.0, },
1844 TopRightBlue = Input { Value = 1.0, },
1845 },
1846 },
1847 Merge23 = Merge {
1848 Inputs = {
1849 Background = Input { SourceOp = "BG1", Source = "Output", },
1850 Foreground = Input { SourceOp = "FG1", Source = "Output", },
1851 Edges = Input { Value = 3, },
1852 },
1853 },
1854 CC1 = ColorCorrector {
1855 Inputs = {
1856 Input = Input { SourceOp = "Merge23", Source = "Output", },
1857 },
1858 },
1859 BG2 = Background {
1860 Inputs = {
1861 Width = Input { Value = 64, },
1862 Height = Input { Value = 64, },
1863 TopLeftAlpha = Input { Value = 1.0, },
1864 },
1865 },
1866 CC_BG = ColorCorrector {
1867 Inputs = {
1868 Input = Input { SourceOp = "BG2", Source = "Output", },
1869 },
1870 },
1871 Merge24 = Merge {
1872 Inputs = {
1873 Background = Input { SourceOp = "CC_BG", Source = "Output", },
1874 Foreground = Input { SourceOp = "CC1", Source = "Output", },
1875 },
1876 },
1877 Infrared = ColorCurves {
1878 Inputs = {
1879 Input = Input { SourceOp = "Merge24", Source = "Output", },
1880 },
1881 },
1882 CC2 = ColorCorrector {
1883 Inputs = {
1884 Input = Input { SourceOp = "Infrared", Source = "Output", },
1885 },
1886 },
1887 DirBlur = DirectionalBlur {
1888 Inputs = {
1889 Blend = Input { Value = 0.0, },
1890 Length = Input { Value = 0.05, },
1891 Input = Input { SourceOp = "CC2", Source = "Output", },
1892 },
1893 },
1894 DirBlurActive = DirectionalBlur {
1895 Inputs = {
1896 Blend = Input { Value = 1.0, },
1897 Length = Input { Value = 0.05, },
1898 Input = Input { SourceOp = "CC2", Source = "Output", },
1899 },
1900 },
1901 XF = Transform {
1902 Inputs = {
1903 Center = Input { Value = { 0.75, 0.5 }, },
1904 Edges = Input { Value = 2, },
1905 Input = Input { SourceOp = "DirBlur", Source = "Output", },
1906 },
1907 },
1908 },
1909 }"#;
1910 let comp = Comp::from_fusion_str(src).expect("parse mirror propagation comp");
1911 let expr = ExprEngine::new();
1912 let dir_blur_id = comp.find_node("DirBlur").expect("DirBlur");
1913 let dir_blur_active_id = comp.find_node("DirBlurActive").expect("DirBlurActive");
1914 assert_eq!(
1915 upstream_infinite_edge_mode(&comp, dir_blur_id, 3050.0, &expr),
1916 Some(3.0),
1917 "Merge(Edges=3) should propagate through point ops, Merge(BG=CC(Background)), and DirectionalBlur(Blend=0)"
1918 );
1919 assert_eq!(
1920 upstream_infinite_edge_mode(&comp, dir_blur_active_id, 3050.0, &expr),
1921 None,
1922 "Active DirectionalBlur (Blend=1) should stop RoI edge-mode propagation"
1923 );
1924
1925 let Ok(mut eng) = Engine::new_headless() else {
1926 return;
1927 };
1928 let xf_id = comp.find_node("XF").expect("XF");
1929 let (tex, _) = eng.evaluate(&comp, xf_id, 3050.0);
1930 let rgba = eng.readback_rgba(&tex).expect("readback XF");
1931 // Center.x = 0.75 shifts image right by 16px: x=0..16 samples mirrored x=16..0
1932 // rather than duplicating x=0! On a red->blue gradient, x=2 should be noticeably
1933 // bluer than x=15 (which sits right next to the red left edge).
1934 let px = |x: usize| -> [u8; 4] {
1935 let i = (32 * 64 + x) * 4;
1936 [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
1937 };
1938 let far_left = px(2);
1939 let seam = px(15);
1940 assert!(
1941 far_left[2] > seam[2] + 20,
1942 "expected mirrored left edge (far_left={far_left:?} bluer than seam={seam:?}), not Duplicate streak"
1943 );
1944 }
1945
1946 #[test]
1947 fn test_merge_mirror_edges_phase_with_cropped_fg_and_offset() {
1948 // Reproduces crazy_3050's Merge23(Edges=3, Center={0.125,0.5}, Size=0.75, cropped FG) ->
1949 // CC1 -> Merge24(Edges=0) -> ColorCurves -> CC2 -> DirBlur(Blend=0) -> Transform(Edges=2, Center={0.6875,0.5}).
1950 // Shifting Transform right by 24px (0.1875 * 128) pulls u < 0 from upstream:
1951 // FG is a 32x128 Red->Blue horizontal gradient centered at x=16 with Size=0.75 (24px wide -> x=[4..28]).
1952 // Mirroring FG across its own left edge x=4 means canvas x=-4 (output x=20) samples near Red (x=12),
1953 // while output x=8 (canvas x=-16) reflects past x=4..28 to Blue, NOT BG1 green or canvas x=0 mirror!
1954 let src = r#"Composition {
1955 CurrentTime = 3050,
1956 RenderRange = { 3000, 3100 },
1957 GlobalRange = { 3000, 3100 },
1958 Tools = ordered() {
1959 BG1 = Background {
1960 Inputs = {
1961 Width = Input { Value = 128, },
1962 Height = Input { Value = 128, },
1963 TopLeftRed = Input { Value = 0.0, },
1964 TopLeftGreen = Input { Value = 1.0, },
1965 TopLeftBlue = Input { Value = 0.0, },
1966 TopLeftAlpha = Input { Value = 1.0, },
1967 },
1968 },
1969 FG1 = Background {
1970 Inputs = {
1971 Width = Input { Value = 32, },
1972 Height = Input { Value = 128, },
1973 Type = Input { Value = FuID { "Horizontal" }, },
1974 TopLeftRed = Input { Value = 1.0, },
1975 TopLeftGreen = Input { Value = 0.0, },
1976 TopLeftBlue = Input { Value = 0.0, },
1977 TopRightRed = Input { Value = 0.0, },
1978 TopRightGreen = Input { Value = 0.0, },
1979 TopRightBlue = Input { Value = 1.0, },
1980 TopLeftAlpha = Input { Value = 1.0, },
1981 },
1982 },
1983 Merge23 = Merge {
1984 Inputs = {
1985 Background = Input { SourceOp = "BG1", Source = "Output", },
1986 Foreground = Input { SourceOp = "FG1", Source = "Output", },
1987 Center = Input { Value = { 0.125, 0.5 }, },
1988 Size = Input { Value = 0.75, },
1989 Edges = Input { Value = 3, },
1990 },
1991 },
1992 CC1 = ColorCorrector {
1993 Inputs = {
1994 Input = Input { SourceOp = "Merge23", Source = "Output", },
1995 },
1996 },
1997 BG2 = Background {
1998 Inputs = {
1999 Width = Input { Value = 128, },
2000 Height = Input { Value = 128, },
2001 TopLeftAlpha = Input { Value = 1.0, },
2002 },
2003 },
2004 Merge24 = Merge {
2005 Inputs = {
2006 Background = Input { SourceOp = "BG2", Source = "Output", },
2007 Foreground = Input { SourceOp = "CC1", Source = "Output", },
2008 },
2009 },
2010 DirBlur = DirectionalBlur {
2011 Inputs = {
2012 Blend = Input { Value = 0.0, },
2013 Length = Input { Value = 0.05, },
2014 Input = Input { SourceOp = "Merge24", Source = "Output", },
2015 },
2016 },
2017 XF = Transform {
2018 Inputs = {
2019 Center = Input { Value = { 0.6875, 0.5 }, },
2020 Edges = Input { Value = 2, },
2021 Input = Input { SourceOp = "DirBlur", Source = "Output", },
2022 },
2023 },
2024 },
2025 }"#;
2026 let comp = Comp::from_fusion_str(src).expect("parse offset Merge(Edges=3) comp");
2027 let Ok(mut eng) = Engine::new_headless() else {
2028 return;
2029 };
2030 let xf_id = comp.find_node("XF").expect("XF");
2031 let (tex, _) = eng.evaluate(&comp, xf_id, 3050.0);
2032 let rgba = eng.readback_rgba(&tex).expect("readback XF");
2033 let px = |x: usize| -> [u8; 4] {
2034 let i = (64 * 128 + x) * 4;
2035 [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
2036 };
2037 // Output x=20 corresponds to canvas x=-4 (mirrored around FG left edge x=4 -> canvas x=12, red-dominant).
2038 // Output x=4 corresponds to canvas x=-20 (mirrors onto far side of FG -> blue-dominant).
2039 // Crucially, green from BG1 must NOT appear at x < 24 (canvas x < 0)!
2040 let out_near_left_fg = px(20);
2041 let out_far_mirrored = px(4);
2042 assert!(
2043 out_near_left_fg[1] < 20 && out_far_mirrored[1] < 20,
2044 "BG1 green must be transparent outside [0,W] (got near={out_near_left_fg:?}, far={out_far_mirrored:?})"
2045 );
2046 assert!(
2047 out_far_mirrored[2] > out_near_left_fg[2] + 60,
2048 "cropped FG Mirror phase should reflect across FG bounds x=4 (far={out_far_mirrored:?} bluer than near={out_near_left_fg:?})"
2049 );
2050 }
2051
2052 #[test]
2053 fn test_dve_pivot_center_zmove_and_dod_expansion() {
2054 // 64x48 foreground transformed by DVE (ZMove=0.75 zooms card larger than 64x48)
2055 // and merged over 128x128 black background must preserve pixels outside 64x48 via DoD!
2056 let src = r#"Composition {
2057 CurrentTime = 0,
2058 RenderRange = { 0, 1 },
2059 GlobalRange = { 0, 1 },
2060 Tools = ordered() {
2061 BG = Background {
2062 Inputs = {
2063 Width = Input { Value = 128, },
2064 Height = Input { Value = 128, },
2065 TopLeftAlpha = Input { Value = 1.0, },
2066 },
2067 },
2068 FG = Background {
2069 Inputs = {
2070 Width = Input { Value = 64, },
2071 Height = Input { Value = 48, },
2072 TopLeftRed = Input { Value = 1.0, },
2073 TopLeftGreen = Input { Value = 0.5, },
2074 TopLeftBlue = Input { Value = 0.0, },
2075 TopLeftAlpha = Input { Value = 1.0, },
2076 },
2077 },
2078 DVE1 = DVE {
2079 Inputs = {
2080 Input = Input { SourceOp = "FG", Source = "Output", },
2081 XRotation = Input { Value = 15.0, },
2082 YRotation = Input { Value = -25.0, },
2083 ZRotation = Input { Value = 10.0, },
2084 ZMove = Input { Value = 0.75, },
2085 Pivot = Input { Value = { 0.3, 0.6 }, },
2086 Center = Input { Value = { 0.45, 0.55 }, },
2087 },
2088 },
2089 Out = Merge {
2090 Inputs = {
2091 Background = Input { SourceOp = "BG", Source = "Output", },
2092 Foreground = Input { SourceOp = "DVE1", Source = "Output", },
2093 },
2094 },
2095 },
2096 }"#;
2097 let comp = Comp::from_fusion_str(src).unwrap();
2098 let Ok(mut eng) = Engine::new_headless() else {
2099 return;
2100 };
2101 let out_id = comp.find_node("Out").unwrap();
2102 let (out_tex, stats) = eng.evaluate(&comp, out_id, 0.0);
2103 assert!(stats.unsupported_nodes.is_empty());
2104 let px = eng.readback_rgba(&out_tex).unwrap();
2105 // Outside original 64x48 centered box (x in 32..96, y in 40..88) at x=110, y=64
2106 // must still show orange card due to ZMove=0.75 + YRotation=-25 DoD expansion!
2107 let expanded_right = (64 * 128 + 110) * 4;
2108 assert!(
2109 px[expanded_right] > 200 && px[expanded_right + 1] > 100,
2110 "expected expanded orange DVE region outside 64x48 at x=110, got {:?}",
2111 &px[expanded_right..expanded_right + 4]
2112 );
2113 }
2114
2115 #[test]
2116 fn transform_multiply_by_mask_zeroes_outside_effect_mask() {
2117 let src = |mbm: u8| {
2118 format!(
2119 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{
2120 BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
2121 TopLeftRed = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }},
2122 Rect = RectangleMask {{ Inputs = {{ Width = Input {{ Value = 0.25, }}, Height = Input {{ Value = 0.25, }},
2123 MaskWidth = Input {{ Value = 64, }}, MaskHeight = Input {{ Value = 64, }}, }}, }},
2124 XF = Transform {{ Inputs = {{ MultiplyByMask = Input {{ Value = {mbm}, }},
2125 Input = Input {{ SourceOp = "BG", Source = "Output", }},
2126 EffectMask = Input {{ SourceOp = "Rect", Source = "Mask", }}, }}, }},
2127 }} }}"#
2128 )
2129 };
2130 if Engine::new_headless().is_err() {
2131 return;
2132 }
2133 let px = |mbm: u8, x: usize, y: usize| {
2134 let mut eng = Engine::new_headless().unwrap();
2135 let comp = Comp::from_fusion_str(&src(mbm)).unwrap();
2136 let (tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 0.0);
2137 let rgba = eng.readback_rgba(&tex).unwrap();
2138 let i = (y * 64 + x) * 4;
2139 [rgba[i], rgba[i + 3]]
2140 };
2141 assert_eq!(px(0, 2, 2), [255, 255], "effect mask only blends; identity transform is unchanged");
2142 assert_eq!(px(1, 2, 2), [0, 0], "outside the mask is zeroed");
2143 assert_eq!(px(1, 32, 32), [255, 255], "inside the mask is kept");
2144 }
2145
2146 #[test]
2147 fn identity_warps_still_multiply_by_mask_but_zero_blend_passes_through() {
2148 // (tool, inputs, outside-mask pixel survives): Fusion Float/Int8 probes of MultiplyByMask + EffectMask.
2149 let cases = [
2150 ("Drip", "Amplitude = Input { Value = 0, },", false),
2151 ("Dent", "Strength = Input { Value = 0, },", false),
2152 ("Vortex", "Angle = Input { Value = 0, },", false),
2153 ("Displace", "", false),
2154 ("Drip", "Blend = Input { Value = 0, },", true),
2155 ("Vortex", "Blend = Input { Value = 0, },", true),
2156 ];
2157 if Engine::new_headless().is_err() {
2158 return;
2159 }
2160 for (kind, inputs, survives) in cases {
2161 let src = format!(
2162 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{
2163 BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
2164 TopLeftRed = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }},
2165 Rect = RectangleMask {{ Inputs = {{ Width = Input {{ Value = 0.25, }}, Height = Input {{ Value = 0.25, }},
2166 MaskWidth = Input {{ Value = 64, }}, MaskHeight = Input {{ Value = 64, }}, }}, }},
2167 FX = {kind} {{ Inputs = {{ MultiplyByMask = Input {{ Value = 1, }}, {inputs}
2168 Input = Input {{ SourceOp = "BG", Source = "Output", }},
2169 EffectMask = Input {{ SourceOp = "Rect", Source = "Mask", }}, }}, }},
2170 }} }}"#
2171 );
2172 let comp = Comp::from_fusion_str(&src).unwrap();
2173 let mut eng = Engine::new_headless().unwrap();
2174 let (tex, _) = eng.evaluate(&comp, comp.find_node("FX").unwrap(), 0.0);
2175 let rgba = eng.readback_rgba(&tex).unwrap();
2176 let px = |x: usize, y: usize| rgba[(y * 64 + x) * 4 + 3];
2177 assert_eq!(px(2, 2), if survives { 255 } else { 0 }, "{kind} {inputs} outside the mask");
2178 assert_eq!(px(32, 32), 255, "{kind} {inputs} inside the mask");
2179 }
2180 }
2181
2182 #[test]
2183 fn displace_light_follows_the_diamond_angle_channel_and_ignores_negative_power() {
2184 // Fusion 21.1 probes: light = LightPower * (map(p + v) - map(p - v)) with v on a diamond
2185 // (0 deg -> (-1, 0), 180 deg -> (+1, 0), 90 deg -> (0, +1) down), added unclamped.
2186 let lit = |inputs: &str| -> [u8; 4] {
2187 let src = format!(
2188 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{
2189 Map = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
2190 Type = Input {{ Value = FuID {{ "Horizontal" }}, }},
2191 TopLeftRed = Input {{ Value = 0, }}, TopLeftGreen = Input {{ Value = 0, }}, TopLeftBlue = Input {{ Value = 0, }}, TopLeftAlpha = Input {{ Value = 1, }},
2192 TopRightRed = Input {{ Value = 1, }}, TopRightGreen = Input {{ Value = 1, }}, TopRightBlue = Input {{ Value = 1, }}, TopRightAlpha = Input {{ Value = 1, }}, }}, }},
2193 Flat = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
2194 TopLeftRed = Input {{ Value = 0.5, }}, TopLeftGreen = Input {{ Value = 0.5, }}, TopLeftBlue = Input {{ Value = 0.5, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }},
2195 D = Displace {{ Inputs = {{ RefractionStrength = Input {{ Value = 0, }}, {inputs}
2196 Input = Input {{ SourceOp = "Flat", Source = "Output", }},
2197 Foreground = Input {{ SourceOp = "Map", Source = "Output", }}, }}, }},
2198 }} }}"#
2199 );
2200 let comp = Comp::from_fusion_str(&src).unwrap();
2201 let mut eng = Engine::new_headless().unwrap();
2202 let (tex, _) = eng.evaluate(&comp, comp.find_node("D").unwrap(), 0.0);
2203 let rgba = eng.readback_rgba(&tex).unwrap();
2204 let i = (32 * 64 + 32) * 4;
2205 [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
2206 };
2207 if Engine::new_headless().is_err() {
2208 return;
2209 }
2210 let near = |got: u8, want: i32| assert!((got as i32 - want).abs() <= 1, "got {got}, want {want}");
2211 // Ramp slope per tap pair is 2/63 of full scale = ~8 levels.
2212 near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 0, },")[0], 128 - 8);
2213 near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 180, },")[0], 128 + 8);
2214 near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 90, },")[0], 128);
2215 // Default angle is 135 deg: (+1, +1), so the horizontal ramp lights positively.
2216 near(lit("LightPower = Input { Value = 1, },")[0], 128 + 8);
2217 // LightChannel 4 lights every channel from alpha, which is flat.
2218 near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 180, }, LightChannel = Input { Value = 4, },")[0], 128);
2219 near(lit("LightPower = Input { Value = -1, }, LightAngle = Input { Value = 180, },")[0], 128);
2220 }
2221
2222 #[test]
2223 fn transform_invert_transform_shifts_the_opposite_way() {
2224 let src = |invert: u8| {
2225 format!(
2226 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{
2227 BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
2228 Type = Input {{ Value = FuID {{ "Horizontal" }}, }},
2229 TopLeftRed = Input {{ Value = 1, }}, TopLeftGreen = Input {{ Value = 0, }}, TopLeftBlue = Input {{ Value = 0, }}, TopLeftAlpha = Input {{ Value = 1, }},
2230 TopRightRed = Input {{ Value = 0, }}, TopRightGreen = Input {{ Value = 1, }}, TopRightBlue = Input {{ Value = 0, }}, TopRightAlpha = Input {{ Value = 1, }}, }}, }},
2231 XF = Transform {{ Inputs = {{ InvertTransform = Input {{ Value = {invert}, }},
2232 Center = Input {{ Value = {{ 0.75, 0.5 }}, }}, Input = Input {{ SourceOp = "BG", Source = "Output", }}, }}, }},
2233 }} }}"#
2234 )
2235 };
2236 if Engine::new_headless().is_err() {
2237 return;
2238 }
2239 let mid_row = |invert: u8| {
2240 let mut eng = Engine::new_headless().unwrap();
2241 let comp = Comp::from_fusion_str(&src(invert)).unwrap();
2242 let (tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 0.0);
2243 let rgba = eng.readback_rgba(&tex).unwrap();
2244 let i = (32 * 64 + 32) * 4;
2245 [rgba[i], rgba[i + 1]]
2246 };
2247 let [r, g] = mid_row(0);
2248 assert!(r > g + 60, "Center +0.25 moves the left (red) side under the middle: {r} {g}");
2249 let [r, g] = mid_row(1);
2250 assert!(g > r + 60, "InvertTransform pulls the right (green) side under the middle: {r} {g}");
2251 }
2252
2253 #[test]
2254 fn transform_dod_preserved_through_bc_into_merge() {
2255 // 64x64 bright red FG is translated left off-canvas by Transform (Center.x = -0.25 -> shift = -0.75 * 64 = -48px),
2256 // passed through BrightnessContrast (unmasked), then merged back onto a 128x64 canvas at Center.x = 0.75.
2257 // Without Transform DoD + unmasked BC DoD preservation, x in [-48..0] would be clipped at x=0!
2258 let src = r#"Composition {
2259 CurrentTime = 0,
2260 RenderRange = { 0, 0 },
2261 GlobalRange = { 0, 0 },
2262 Tools = ordered() {
2263 BG = Background {
2264 Inputs = {
2265 Width = Input { Value = 128, },
2266 Height = Input { Value = 64, },
2267 TopLeftAlpha = Input { Value = 1.0, },
2268 },
2269 },
2270 FG = Background {
2271 Inputs = {
2272 Width = Input { Value = 64, },
2273 Height = Input { Value = 64, },
2274 TopLeftRed = Input { Value = 1.0, },
2275 TopLeftGreen = Input { Value = 0.0, },
2276 TopLeftBlue = Input { Value = 0.0, },
2277 TopLeftAlpha = Input { Value = 1.0, },
2278 },
2279 },
2280 XF = Transform {
2281 Inputs = {
2282 Input = Input { SourceOp = "FG", Source = "Output", },
2283 Center = Input { Value = { -0.25, 0.5 }, },
2284 },
2285 },
2286 BC = BrightnessContrast {
2287 Inputs = {
2288 Input = Input { SourceOp = "XF", Source = "Output", },
2289 Gain = Input { Value = 0.8, },
2290 Lift = Input { Value = -0.2, },
2291 Gamma = Input { Value = 1.5, },
2292 },
2293 },
2294 M = Merge {
2295 Inputs = {
2296 Background = Input { SourceOp = "BG", Source = "Output", },
2297 Foreground = Input { SourceOp = "BC", Source = "Output", },
2298 Center = Input { Value = { 0.75, 0.5 }, },
2299 },
2300 },
2301 },
2302 }"#;
2303 let comp = Comp::from_fusion_str(src).expect("parse Transform DoD comp");
2304 let Ok(mut eng) = Engine::new_headless() else {
2305 return;
2306 };
2307 let (tex, _) = eng.evaluate(&comp, comp.find_node("M").unwrap(), 0.0);
2308 let rgba = eng.readback_rgba(&tex).unwrap();
2309 // Merge places BC's 64x64 logical center (32) at 0.75 * 128 = 96, so x=0 of BC lands at 64.
2310 // The shifted red square spans x in [-48..16) in BC, which lands at [16..80) on BG!
2311 // At x=32 (left of BC's x=0 at 64), red pixels must survive!
2312 let i = (32 * 128 + 32) * 4;
2313 assert!(rgba[i] > 150 && rgba[i + 1] == 0, "expected off-canvas shifted FG via DoD at x=32, got {:?}", &rgba[i..i + 4]);
2314 }
2315
2316 #[test]
2317 fn vortex_dod_input_and_effect_mask_align_to_canvas() {
2318 let src = r#"Composition {
2319 CurrentTime = 0,
2320 RenderRange = { 0, 0 },
2321 GlobalRange = { 0, 0 },
2322 Tools = ordered() {
2323 Stripe = Background {
2324 Inputs = {
2325 Width = Input { Value = 64, },
2326 Height = Input { Value = 64, },
2327 Type = Input { Value = FuID { "Horizontal" }, },
2328 TopLeftRed = Input { Value = 1.0, },
2329 TopLeftAlpha = Input { Value = 1.0, },
2330 TopRightBlue = Input { Value = 1.0, },
2331 TopRightAlpha = Input { Value = 1.0, },
2332 },
2333 },
2334 XF = DVE {
2335 Inputs = {
2336 Input = Input { SourceOp = "Stripe", Source = "Output", },
2337 Center = Input { Value = { 0.25, 0.5 }, },
2338 },
2339 },
2340 Mask = RectangleMask {
2341 Inputs = {
2342 MaskWidth = Input { Value = 64, },
2343 MaskHeight = Input { Value = 64, },
2344 Center = Input { Value = { 0.75, 0.5 }, },
2345 Width = Input { Value = 0.25, },
2346 Height = Input { Value = 1.0, },
2347 },
2348 },
2349 V = Vortex {
2350 Inputs = {
2351 Input = Input { SourceOp = "XF", Source = "Output", },
2352 EffectMask = Input { SourceOp = "Mask", Source = "Mask", },
2353 Angle = Input { Value = 180.0, },
2354 Size = Input { Value = 0.8, },
2355 },
2356 },
2357 },
2358 }"#;
2359 let comp = Comp::from_fusion_str(src).expect("parse Vortex DoD comp");
2360 let Ok(mut eng) = Engine::new_headless() else {
2361 return;
2362 };
2363 let (v_tex, _) = eng.evaluate(&comp, comp.find_node("V").unwrap(), 0.0);
2364 let (xf_tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 0.0);
2365 let v_px = eng.readback_rgba(&v_tex).unwrap();
2366 let xf_px = eng.readback_rgba(&xf_tex).unwrap();
2367 // Left of Mask (x in 0..40) must be identical to XF (Vortex must not warp outside canvas mask).
2368 for x in 0..40 {
2369 let i = (32 * 64 + x) * 4;
2370 assert_eq!(&v_px[i..i + 4], &xf_px[i..i + 4], "Vortex mask misaligned at x={x}");
2371 }
2372 }
2373
2374 #[test]
2375 fn camera_shake_dod_input_and_effect_mask_align_to_canvas() {
2376 let src = r#"Composition {
2377 CurrentTime = 2,
2378 RenderRange = { 0, 5 },
2379 GlobalRange = { 0, 5 },
2380 Tools = ordered() {
2381 Stripe = Background {
2382 Inputs = {
2383 Width = Input { Value = 64, },
2384 Height = Input { Value = 64, },
2385 Type = Input { Value = FuID { "Horizontal" }, },
2386 TopLeftRed = Input { Value = 1.0, },
2387 TopLeftAlpha = Input { Value = 1.0, },
2388 TopRightBlue = Input { Value = 1.0, },
2389 TopRightAlpha = Input { Value = 1.0, },
2390 },
2391 },
2392 XF = DVE {
2393 Inputs = {
2394 Input = Input { SourceOp = "Stripe", Source = "Output", },
2395 Center = Input { Value = { 0.25, 0.5 }, },
2396 },
2397 },
2398 Mask = RectangleMask {
2399 Inputs = {
2400 Center = Input { Value = { 0.875, 0.5 }, },
2401 Width = Input { Value = 0.25, },
2402 Height = Input { Value = 1.0, },
2403 },
2404 },
2405 CS = CameraShake {
2406 Inputs = {
2407 Input = Input { SourceOp = "XF", Source = "Output", },
2408 EffectMask = Input { SourceOp = "Mask", Source = "Mask", },
2409 XDeviation = Input { Value = 0.25, },
2410 YDeviation = Input { Value = 0.25, },
2411 RotationDeviation = Input { Value = 25.0, },
2412 OverallStrength = Input { Value = 1.0, },
2413 Speed = Input { Value = 3.0, },
2414 },
2415 },
2416 },
2417 }"#;
2418 let comp = Comp::from_fusion_str(src).expect("parse CameraShake DoD comp");
2419 let Ok(mut eng) = Engine::new_headless() else {
2420 return;
2421 };
2422 let (xf_tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 2.0);
2423 let (cs_tex, _) = eng.evaluate(&comp, comp.find_node("CS").unwrap(), 2.0);
2424 assert_eq!(cs_tex.size, [64, 64]);
2425 assert_eq!(cs_tex.origin, [0, 0]);
2426 assert_eq!(cs_tex.canvas_size, [64, 64]);
2427 let xf_px = eng.readback_rgba(&xf_tex).unwrap();
2428 let cs_px = eng.readback_rgba(&cs_tex).unwrap();
2429 // Mask covers [48..64), so x in [0..46) must match XF on canvas exactly.
2430 for x in 0..46 {
2431 let i = (32 * 64 + x) * 4;
2432 assert_eq!(&cs_px[i..i + 4], &xf_px[i..i + 4], "CameraShake mask misaligned at x={x}");
2433 }
2434 }
2435 #[test]
2436 fn corner_positioner_defaults_to_fusion_quad_and_offsets_extend_the_sampled_quad() {
2437 let src = r#"Composition { Tools = ordered() {
2438 BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, },
2439 CP = CornerPositioner { Inputs = { Input = Input { SourceOp = "BG", Source = "Output", }, }, },
2440 CPO = CornerPositioner { Inputs = { Input = Input { SourceOp = "BG", Source = "Output", }, TopLeftOffsetX = Input { Value = 1, }, }, },
2441 }, }"#;
2442 let comp = Comp::from_fusion_str(src).expect("parse corner positioner comp");
2443 let Ok(mut eng) = Engine::new_headless() else { return };
2444 let alpha = |eng: &mut Engine, name: &str, x: usize, y: usize| {
2445 let (tex, _) = eng.evaluate(&comp, comp.find_node(name).unwrap(), 0.0);
2446 eng.readback_rgba(&tex).unwrap()[(y * 64 + x) * 4 + 3]
2447 };
2448 // Default quad TL(0.1, 0.9) .. BR(1, 0.1): the bottom-left canvas corner lies outside, the center inside.
2449 assert_eq!(alpha(&mut eng, "CP", 1, 62), 0);
2450 assert_eq!(alpha(&mut eng, "CP", 32, 32), 255);
2451 // An X offset of 1 samples the source from u = -1, so the top-left of the quad turns transparent.
2452 assert_eq!(alpha(&mut eng, "CPO", 8, 8), 0);
2453 assert_eq!(alpha(&mut eng, "CPO", 56, 40), 255);
2454 }
2455
2456 fn eval_px(comp: &Comp, eng: &mut Engine, name: &str, t: f64) -> (Vec<u8>, crate::cache::EvalStats) {
2457 let (tex, stats) = eng.evaluate(comp, comp.find_node(name).unwrap(), t);
2458 (eng.readback_rgba(&tex).unwrap(), stats)
2459 }
2460
2461 #[test]
2462 fn corner_positioner_linear_quad_rotated_90_degrees_is_not_blank() {
2463 let src = r#"Composition { Tools = ordered() {
2464 BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, },
2465 CP = CornerPositioner { Inputs = {
2466 Input = Input { SourceOp = "BG", Source = "Output", },
2467 MappingType = Input { Value = 0, },
2468 BottomLeft = Input { Value = { 0.7, 0.3 }, },
2469 BottomRight = Input { Value = { 0.7, 0.7 }, },
2470 TopRight = Input { Value = { 0.3, 0.7 }, },
2471 TopLeft = Input { Value = { 0.3, 0.3 }, },
2472 }, },
2473 }, }"#;
2474 let comp = Comp::from_fusion_str(src).expect("parse comp");
2475 let Ok(mut eng) = Engine::new_headless() else { return };
2476 let (px, _) = eval_px(&comp, &mut eng, "CP", 0.0);
2477 let a = |x: usize, y: usize| px[(y * 64 + x) * 4 + 3];
2478 assert_eq!(a(32, 32), 255, "vertical top/bottom edges still map the quad interior");
2479 assert_eq!(a(4, 4), 0, "outside the quad stays transparent");
2480 }
2481
2482 #[test]
2483 fn corner_positioner_multiply_by_mask_applies_at_zero_blend() {
2484 let src = r#"Composition { Tools = ordered() {
2485 BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, },
2486 M = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 1, }, Height = Input { Value = 1, }, }, },
2487 CP = CornerPositioner { Inputs = {
2488 Input = Input { SourceOp = "BG", Source = "Output", },
2489 EffectMask = Input { SourceOp = "M", Source = "Mask", },
2490 MultiplyByMask = Input { Value = 1, },
2491 Blend = Input { Value = 0, },
2492 }, },
2493 }, }"#;
2494 let comp = Comp::from_fusion_str(src).expect("parse comp");
2495 let Ok(mut eng) = Engine::new_headless() else { return };
2496 let (px, _) = eval_px(&comp, &mut eng, "CP", 0.0);
2497 assert_eq!(px[(32 * 64 + 32) * 4 + 3], 0, "Blend=0 with MultiplyByMask zeroes the frame");
2498 }
2499
2500 #[test]
2501 fn effect_mask_channel_remap_is_applied_and_cached() {
2502 let src = r#"Composition { Tools = ordered() {
2503 BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, },
2504 M = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 1, }, Height = Input { Value = 1, }, }, },
2505 Plain = Transform { Inputs = { Input = Input { SourceOp = "BG", Source = "Output", }, EffectMask = Input { SourceOp = "M", Source = "Mask", }, MultiplyByMask = Input { Value = 1, }, }, },
2506 Half = Transform { Inputs = { Input = Input { SourceOp = "BG", Source = "Output", }, EffectMask = Input { SourceOp = "M", Source = "Mask", }, MultiplyByMask = Input { Value = 1, }, MaskHigh = Input { Value = 2, }, }, },
2507 }, }"#;
2508 let comp = Comp::from_fusion_str(src).expect("parse comp");
2509 let Ok(mut eng) = Engine::new_headless() else { return };
2510 let center = (32 * 64 + 32) * 4 + 3;
2511 assert_eq!(eval_px(&comp, &mut eng, "Plain", 0.0).0[center], 255);
2512 let (half, _) = eval_px(&comp, &mut eng, "Half", 0.0);
2513 assert!((half[center] as i32 - 128).abs() <= 2, "MaskHigh=2 halves mask coverage: {}", half[center]);
2514 let (_, stats) = eval_px(&comp, &mut eng, "Half", 1.0);
2515 assert_eq!(stats.nodes_evaluated, 0, "remapped mask and Transform come from the cache on a static frame");
2516 }
2517
2518 #[test]
2519 fn displace_light_with_full_spread_is_a_two_tap_pass() {
2520 let src = |light: f64| format!(r#"Composition {{ Tools = ordered() {{
2521 BG = Background {{ Inputs = {{ Width = Input {{ Value = 96, }}, Height = Input {{ Value = 96, }}, TopLeftRed = Input {{ Value = 0.5, }}, TopLeftGreen = Input {{ Value = 0.5, }}, TopLeftBlue = Input {{ Value = 0.5, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }},
2522 Ramp = Background {{ Inputs = {{ Width = Input {{ Value = 96, }}, Height = Input {{ Value = 96, }}, Type = Input {{ Value = FuID {{ "Horizontal" }}, }},
2523 TopLeftRed = Input {{ Value = 0, }}, TopLeftGreen = Input {{ Value = 0, }}, TopLeftBlue = Input {{ Value = 0, }}, TopLeftAlpha = Input {{ Value = 1, }},
2524 TopRightRed = Input {{ Value = 1, }}, TopRightGreen = Input {{ Value = 1, }}, TopRightBlue = Input {{ Value = 1, }}, TopRightAlpha = Input {{ Value = 1, }}, }}, }},
2525 D = Displace {{ Inputs = {{ Input = Input {{ SourceOp = "BG", Source = "Output", }}, Foreground = Input {{ SourceOp = "Ramp", Source = "Output", }},
2526 LightPower = Input {{ Value = {light}, }}, Spread = Input {{ Value = 1, }}, RefractionStrength = Input {{ Value = 0, }}, }}, }},
2527 }}, }}"#);
2528 let Ok(mut eng) = Engine::new_headless() else { return };
2529 let lit = Comp::from_fusion_str(&src(1.0)).expect("parse lit comp");
2530 let flat = Comp::from_fusion_str(&src(0.0)).expect("parse flat comp");
2531 let (lit_px, _) = eval_px(&lit, &mut eng, "D", 0.0);
2532 let (flat_px, _) = eval_px(&flat, &mut eng, "D", 0.0);
2533 assert!(lit_px.iter().zip(&flat_px).any(|(a, b)| a.abs_diff(*b) > 2), "slope lighting must change the image");
2534 }
2535
2536 #[test]
2537 fn vortex_clamp_edges_and_process_skip_with_mbm() {
2538 let src = r#"Composition { Tools = ordered() {
2539 BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, },
2540 TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, },
2541 M = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 0.5, }, Height = Input { Value = 0.5, }, }, },
2542 V = Vortex { Inputs = {
2543 Input = Input { SourceOp = "BG", Source = "Output", },
2544 Size = Input { Value = 2.0, },
2545 EffectMask = Input { SourceOp = "M", Source = "Mask", },
2546 MultiplyByMask = Input { Value = 1, },
2547 ProcessRed = Input { Value = 0, },
2548 }, },
2549 } }"#;
2550 let comp = Comp::from_fusion_str(src).expect("parse vortex comp");
2551 let Ok(mut eng) = Engine::new_headless() else { return };
2552 let (px, _) = eval_px(&comp, &mut eng, "V", 0.0);
2553 // Outside mask must be zeroed even for ProcessRed=0; inside mask stays solid red.
2554 assert_eq!(&px[0..4], &[0, 0, 0, 0]);
2555 let center = (32 * 64 + 32) * 4;
2556 assert_eq!(&px[center..center + 4], &[255, 0, 0, 255]);
2557 }
2558
2559 #[test]
2560 fn dve_rotation_order_zpivot_shear_and_alpha_mode() {
2561 let src = |rot_ord: u8, zpivot: f64, xshear: f64, alpha_mode: u8| format!(r#"Composition {{ Tools = ordered() {{
2562 BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
2563 TopLeftRed = Input {{ Value = 1, }}, TopLeftGreen = Input {{ Value = 0.5, }}, TopLeftAlpha = Input {{ Value = 0.5, }}, }}, }},
2564 D = DVE {{ Inputs = {{
2565 Input = Input {{ SourceOp = "BG", Source = "Output", }},
2566 RotationOrder = Input {{ Value = {rot_ord}, }},
2567 XRotation = Input {{ Value = 25, }},
2568 YRotation = Input {{ Value = 35, }},
2569 ZRotation = Input {{ Value = 40, }},
2570 ZPivot = Input {{ Value = {zpivot}, }},
2571 XShear = Input {{ Value = {xshear}, }},
2572 AlphaMode = Input {{ Value = {alpha_mode}, }},
2573 }}, }},
2574 }} }}"#);
2575 let Ok(mut eng) = Engine::new_headless() else { return };
2576 let p0 = eval_px(&Comp::from_fusion_str(&src(0, 0.0, 0.0, 1)).unwrap(), &mut eng, "D", 0.0).0;
2577 let p1 = eval_px(&Comp::from_fusion_str(&src(1, 0.0, 0.0, 1)).unwrap(), &mut eng, "D", 0.0).0;
2578 let pz = eval_px(&Comp::from_fusion_str(&src(0, 0.3, 0.0, 1)).unwrap(), &mut eng, "D", 0.0).0;
2579 let ps = eval_px(&Comp::from_fusion_str(&src(0, 0.0, 0.4, 1)).unwrap(), &mut eng, "D", 0.0).0;
2580 assert_ne!(p0, p1, "RotationOrder=1 must differ from 0");
2581 assert_ne!(p0, pz, "ZPivot must affect perspective transform");
2582 assert_ne!(p0, ps, "XShear must skew output");
2583 let center = (32 * 64 + 32) * 4;
2584 assert!((p0[center + 3] as i32 - 128).abs() <= 2, "AlphaMode=1 must preserve ~0.5 source alpha, got {}", p0[center + 3]);
2585 }
2586
2587 #[test]
2588 fn duplicate_luajit_prng_and_jitter_layers() {
2589 let mut rng = LuaJitPrng::new(1.0);
2590 let mut draws = [0.0f32; 12];
2591 for d in &mut draws {
2592 *d = 0.5 * (*d + rng.next_signed() + 1.0);
2593 }
2594 assert!((draws[7] - 0.838_582).abs() < 1e-4, "draw[7] mismatch: {}", draws[7]);
2595 assert!((draws[10] - 0.562_473).abs() < 1e-4, "draw[10] mismatch: {}", draws[10]);
2596 assert!((draws[11] - 0.932_789).abs() < 1e-4, "draw[11] mismatch: {}", draws[11]);
2597
2598 let src = r#"Composition { Tools = ordered() {
2599 BG = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, },
2600 TopLeftRed = Input { Value = 0.5, }, TopLeftGreen = Input { Value = 0.5, }, TopLeftBlue = Input { Value = 0.5, }, TopLeftAlpha = Input { Value = 0.5, }, }, },
2601 HalfCopy = Fuse.Duplicate { Inputs = { Background = Input { SourceOp = "BG", Source = "Output", }, Copies = Input { Value = 0.5, }, }, },
2602 Jit = Fuse.Duplicate { Inputs = { Background = Input { SourceOp = "BG", Source = "Output", }, Copies = Input { Value = 2, }, RandomSeed = Input { Value = 1, }, JitterRedGain = Input { Value = 0.5, }, }, },
2603 } }"#;
2604 let comp = Comp::from_fusion_str(src).expect("parse duplicate comp");
2605 let Ok(mut eng) = Engine::new_headless() else { return };
2606 let half = eval_px(&comp, &mut eng, "HalfCopy", 0.0).0;
2607 let c = (16 * 32 + 16) * 4;
2608 assert!((half[c + 3] as i32 - 64).abs() <= 2, "Copies=0.5 scales alpha to ~64, got {}", half[c + 3]);
2609 let jit = eval_px(&comp, &mut eng, "Jit", 0.0).0;
2610 assert!(jit[c] > 220 && (jit[c] as i32 - jit[c + 1] as i32).abs() > 30, "JitterRedGain boosts R over G: {:?}", &jit[c..c + 4]);
2611 }
2612
2613 #[test]
2614 fn transform_and_corner_positioner_process_skip_and_bilinear_offsets() {
2615 let src = r#"Composition { Tools = ordered() {
2616 BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, },
2617 TopLeftRed = Input { Value = 0.8, }, TopLeftGreen = Input { Value = 0.6, }, TopLeftBlue = Input { Value = 0.4, }, TopLeftAlpha = Input { Value = 1.0, }, }, },
2618 Mask = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, },
2619 Center = Input { Value = { 0.5, 0.5 }, }, Width = Input { Value = 1.0, }, Height = Input { Value = 1.0, }, }, },
2620 XF = Transform { Inputs = {
2621 Input = Input { SourceOp = "BG", Source = "Output", },
2622 EffectMask = Input { SourceOp = "Mask", Source = "Mask", },
2623 Center = Input { Value = { 1.1, 0.5 }, },
2624 MultiplyByMask = Input { Value = 1, },
2625 ProcessGreen = Input { Value = 0, },
2626 }, },
2627 CP = CornerPositioner { Inputs = {
2628 Input = Input { SourceOp = "BG", Source = "Output", },
2629 EffectMask = Input { SourceOp = "Mask", Source = "Mask", },
2630 MappingType = Input { Value = 0, },
2631 ["TopRight.X"] = Input { Value = 0.8, },
2632 MultiplyByMask = Input { Value = 1, },
2633 ProcessRed = Input { Value = 0, },
2634 }, },
2635 } }"#;
2636 let comp = Comp::from_fusion_str(src).expect("parse xf/cp comp");
2637 let Ok(mut eng) = Engine::new_headless() else { return };
2638 let px_xf = eval_px(&comp, &mut eng, "XF", 0.0).0;
2639 let c = (32 * 64 + 32) * 4;
2640 // Center shifted to 0.95 shifts translated image off-center (R/B become 0), while ProcessGreen=0 keeps source green (~153).
2641 assert_eq!((px_xf[c], px_xf[c + 1]), (0, 153), "Transform ProcessGreen=0 keeps source green: {:?}", &px_xf[c..c + 4]);
2642 let px_cp = eval_px(&comp, &mut eng, "CP", 0.0).0;
2643 assert_eq!(px_cp[c], 0, "CornerPositioner MultiplyByMask=1 & ProcessRed=0 clears red to 0: {:?}", &px_cp[c..c + 4]);
2644 assert!(px_cp[c + 1] > 100 && px_cp[c + 3] == 255, "CornerPositioner MappingType=0 keeps image in quad interior: {:?}", &px_cp[c..c + 4]);
2645 }
2646
2647 #[test]
2648 fn camera_shake_waveforms_speed_curve_and_randomness_parity() {
2649 // Speed=0.0 -> rate=0.3/1.1, Speed=0.8 -> rate=1.0, Speed=1.0 -> rate=3.0; Y starts at +0.2*YDev at t=0.
2650 let (dx0, dy0, ang0) = Engine::camera_shake_offset(0.0, 1.0, 1.0, 1.0, 1.0, 0.8, 0.0, 0);
2651 assert!(dx0.abs() < 1e-6 && (dy0 - 0.2).abs() < 1e-6 && ang0.abs() < 1e-6, "t=0 r=0: {:?}", (dx0, dy0, ang0));
2652
2653 // Speed=0.0 at t=1: rate = 0.3/1.1 = 0.27273 -> dx = 0.2 * sin(0.27273) = 0.05388
2654 let (dx_s0, _, ang_s0) = Engine::camera_shake_offset(1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0);
2655 assert!((dx_s0 - 0.05388).abs() < 5e-4, "Speed=0 dx={dx_s0}");
2656 assert!((ang_s0.to_degrees() - 1.478).abs() < 0.03, "Speed=0 ang={}", ang_s0.to_degrees());
2657
2658 // FrequencyMethod=1 (Rectified Sine) at t=0: X=-0.2, Y=+0.2, Rot=-5 deg
2659 let (dx_r, dy_r, ang_r) = Engine::camera_shake_offset(0.0, 1.0, 1.0, 1.0, 1.0, 0.8, 0.0, 1);
2660 assert!((dx_r + 0.2).abs() < 1e-5 && (dy_r - 0.2).abs() < 1e-5 && (ang_r.to_degrees() + 5.0).abs() < 1e-3);
2661
2662 // FrequencyMethod=2 (Square Wave) at t=0: sin(0)=0 snaps to -1, cos(0)=+1 -> +1
2663 let (dx_sq, dy_sq, ang_sq) = Engine::camera_shake_offset(0.0, 1.0, 1.0, 1.0, 1.0, 0.8, 0.0, 2);
2664 assert!((dx_sq + 0.2).abs() < 1e-5 && (dy_sq - 0.2).abs() < 1e-5 && (ang_sq.to_degrees() + 5.0).abs() < 1e-3);
2665
2666 // Quadratic Randomness scaling on Rotation phase at t=0: r=0.5 has ~1/4 the phase shift of r=1.0
2667 let (_, _, ang_r05) = Engine::camera_shake_offset(0.0, 0.0, 0.0, 1.0, 1.0, 0.8, 0.5, 0);
2668 let (_, _, ang_r10) = Engine::camera_shake_offset(0.0, 0.0, 0.0, 1.0, 1.0, 0.8, 1.0, 0);
2669 assert!((ang_r05.to_degrees() - 1.03).abs() < 0.15, "r=0.5 ang={}", ang_r05.to_degrees());
2670 assert!((ang_r10.to_degrees() - 3.96).abs() < 0.15, "r=1.0 ang={}", ang_r10.to_degrees());
2671
2672 // GPU end-to-end check: FrequencyMethod=1 shifts a centered box left at t=0, whereas Sine keeps it centered in X.
2673 let make_cs = |fm: i32| format!(
2674 r#"Composition {{ Tools = ordered() {{
2675 BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
2676 TopLeftRed = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }},
2677 CS = CameraShake {{ Inputs = {{
2678 Input = Input {{ SourceOp = "BG", Source = "Output", }},
2679 XDeviation = Input {{ Value = 1.0, }}, YDeviation = Input {{ Value = 0.0, }},
2680 RotationDeviation = Input {{ Value = 0.0, }}, Randomness = Input {{ Value = 0.0, }},
2681 FrequencyMethod = Input {{ Value = {fm}, }},
2682 }}, }},
2683 }} }}"#
2684 );
2685 let Ok(mut eng) = Engine::new_headless() else { return };
2686 let px_sin = eval_px(&Comp::from_fusion_str(&make_cs(0)).unwrap(), &mut eng, "CS", 0.0).0;
2687 let px_rect = eval_px(&Comp::from_fusion_str(&make_cs(1)).unwrap(), &mut eng, "CS", 0.0).0;
2688 let right_edge = (32 * 64 + 60) * 4;
2689 assert_eq!(px_sin[right_edge + 3], 255, "Sine t=0 r=0 keeps right edge opaque");
2690 assert_eq!(px_rect[right_edge + 3], 0, "Rectified Sine t=0 shifts image left by 0.2");
2691 }
2692863}
crates/engine/src/eval/transform/dve.rs created+672
......@@ -0,0 +1,672 @@
1use super::*;
2
3impl Engine {
4 /// Row-major projective matrix (`h22 = 1`) taking the unit square's `(bl, br, tr, tl)` corners to the given quad.
5 fn quad_homography(bl: [f64; 2], br: [f64; 2], tr: [f64; 2], tl: [f64; 2]) -> Option<[f64; 9]> {
6 let dx1 = br[0] - tr[0];
7 let dy1 = br[1] - tr[1];
8 let dx2 = tl[0] - tr[0];
9 let dy2 = tl[1] - tr[1];
10 let sx = bl[0] - br[0] + tr[0] - tl[0];
11 let sy = bl[1] - br[1] + tr[1] - tl[1];
12 let denom = dx1 * dy2 - dx2 * dy1;
13 if denom.abs() < 1e-10 {
14 return None;
15 }
16 let g = (sx * dy2 - sy * dx2) / denom;
17 let h = (dx1 * sy - dy1 * sx) / denom;
18 Some([
19 br[0] - bl[0] + g * br[0],
20 tl[0] - bl[0] + h * tl[0],
21 bl[0],
22 br[1] - bl[1] + g * br[1],
23 tl[1] - bl[1] + h * tl[1],
24 bl[1],
25 g,
26 h,
27 1.0,
28 ])
29 }
30
31 /// Adjugate (inverse up to scale) of a row-major 3x3 matrix.
32 fn adjugate(m: &[f64; 9]) -> [f64; 9] {
33 let [a, b, c, d, e, f, g, h, i] = *m;
34 [e * i - f * h, c * h - b * i, b * f - c * e, f * g - d * i, a * i - c * g, c * d - a * f, d * h - e * g, b * g - a * h, a * e - b * d]
35 }
36
37 fn mat_mul(a: &[f64; 9], b: &[f64; 9]) -> [f64; 9] {
38 std::array::from_fn(|k| (0..3).map(|j| a[k / 3 * 3 + j] * b[j * 3 + k % 3]).sum())
39 }
40
41 /// Inverse 3x3 projective homography mapping destination quad `(bl, br, tr, tl)` back to unit square `[0,1]^2`.
42 pub(in crate::eval) fn quad_inverse_homography(bl: [f64; 2], br: [f64; 2], tr: [f64; 2], tl: [f64; 2]) -> [f32; 9] {
43 Self::quad_homography(bl, br, tr, tl)
44 .map_or([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], |h| Self::adjugate(&h).map(|v| v as f32))
45 }
46
47 pub(in crate::eval) fn eval_corner_positioner(
48 &mut self,
49 comp: &Comp,
50 node: &Node,
51 time: f64,
52 frame_i: i64,
53 enc: &mut wgpu::CommandEncoder,
54 visiting: &mut HashSet<(NodeId, i64)>,
55 stats: &mut EvalStats,
56 ) -> CachedTexture {
57 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
58 return self.dummy.clone();
59 };
60 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
61 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
62 if blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) {
63 return src;
64 }
65 let src = self.crop_to_canvas(enc, src);
66 // Corner `Offset`s shift the matching source-UV corner against the offset, so positive values extend the sampled quad.
67 let corner = |name: &str, default: [f64; 2]| {
68 let p = comp.eval_point(node, name, time, default, &self.expr);
69 let off = [
70 comp.eval_number(node, &format!("{name}OffsetX"), time, 0.0, &self.expr),
71 comp.eval_number(node, &format!("{name}OffsetY"), time, 0.0, &self.expr),
72 ];
73 (p, off)
74 };
75 let [(bl, bl_o), (br, br_o), (tr, tr_o), (tl, tl_o)] = [
76 corner("BottomLeft", [0.0, 0.3]),
77 corner("BottomRight", [1.0, 0.1]),
78 corner("TopRight", [0.9, 1.0]),
79 corner("TopLeft", [0.1, 0.9]),
80 ];
81 let src_uv = |u: [f64; 2], o: [f64; 2]| [u[0] - o[0], u[1] - o[1]];
82 let (s_bl, s_br, s_tr, s_tl) = (src_uv([0.0, 0.0], bl_o), src_uv([1.0, 0.0], br_o), src_uv([1.0, 1.0], tr_o), src_uv([0.0, 1.0], tl_o));
83 let h_inv = match (Self::quad_homography(bl, br, tr, tl), Self::quad_homography(s_bl, s_br, s_tr, s_tl)) {
84 (Some(out), Some(src)) => Self::mat_mul(&src, &Self::adjugate(&out)).map(|v| v as f32),
85 _ => [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
86 };
87 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
88 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
89 let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
90
91 let mut u = UniformParams::default();
92 u.p[0] = [h_inv[0], h_inv[1], h_inv[2], h_inv[3]];
93 u.p[1] = [h_inv[4], h_inv[5], h_inv[6], h_inv[7]];
94 u.p[2] = [h_inv[8], blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
95 u.p[3][1] = if mbm { 1.0 } else { 0.0 };
96 if comp.eval_number(node, "MappingType", time, 1.0, &self.expr) < 0.5 {
97 u.p[3][3] = 1.0;
98 let add_off = |p: [f64; 2], o: [f64; 2]| [p[0] + o[0], p[1] + o[1]];
99 let quads = [
100 [add_off(bl, bl_o), add_off(br, br_o)],
101 [add_off(tr, tr_o), add_off(tl, tl_o)],
102 [[0.0, 0.0], [1.0, 0.0]],
103 [[1.0, 1.0], [0.0, 1.0]],
104 ];
105 for (row, pts) in quads.iter().enumerate() {
106 u.p[6 + row] = [pts[0][0] as f32, pts[0][1] as f32, pts[1][0] as f32, pts[1][1] as f32];
107 }
108 }
109 u.p[5] = self.process_skip(comp, node, time);
110 let key = self.make_key(node, "CornerPos", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..10]));
111 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
112 stats.cache_hits += 1;
113 return hit;
114 }
115 stats.cache_misses += 1;
116 stats.nodes_evaluated += 1;
117 let dst = self.alloc_tex_like(&src, src.depth, key);
118 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
119 self.dispatch_op(enc, ShaderOp::Homography, &src.view, &self.dummy.view, mv, &dst, &u);
120 self.cache.insert(key, dst.clone(), node.id, frame_i);
121 dst
122 }
123
124 pub(in crate::eval) fn eval_dve(
125 &mut self,
126 comp: &Comp,
127 node: &Node,
128 time: f64,
129 frame_i: i64,
130 enc: &mut wgpu::CommandEncoder,
131 visiting: &mut HashSet<(NodeId, i64)>,
132 stats: &mut EvalStats,
133 ) -> CachedTexture {
134 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
135 return self.dummy.clone();
136 };
137 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
138 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
139 if blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) {
140 return src;
141 }
142 let skip = self.process_skip(comp, node, time);
143 if skip.iter().all(|&s| s > 0.5) {
144 return src;
145 }
146 let src = self.crop_to_canvas(enc, src);
147 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
148 let pivot = comp.eval_point(node, "Pivot", time, [0.5, 0.5], &self.expr);
149 let z_pivot = comp.eval_number(node, "ZPivot", time, 0.0, &self.expr);
150 let z_move = comp.eval_number(node, "ZMove", time, 1.0, &self.expr);
151 let rx = comp.eval_number(node, "XRotation", time, 0.0, &self.expr).to_radians();
152 let ry = comp.eval_number(node, "YRotation", time, 0.0, &self.expr).to_radians();
153 let rz = comp.eval_number(node, "ZRotation", time, 0.0, &self.expr).to_radians();
154 let x_shear = comp.eval_number(node, "XShear", time, 0.0, &self.expr);
155 let y_shear = comp.eval_number(node, "YShear", time, 0.0, &self.expr);
156 let rot_order = match node.static_str("RotationOrder") {
157 Some(s) => s,
158 None => match comp.eval_number(node, "RotationOrder", time, 5.0, &self.expr).round() as i32 {
159 0 => "XYZ",
160 1 => "XZY",
161 2 => "YXZ",
162 3 => "YZX",
163 4 => "ZXY",
164 _ => "ZYX",
165 },
166 };
167 let aspect = src.canvas_size[0] as f64 / src.canvas_size[1].max(1) as f64;
168
169 // Fusion DVE rotates card corners around Pivot (starting at z = +ZPivot so ZPivot > 0 moves
170 // the card away from the camera even at 0 rotation), applies XShear/YShear, and projects with 1 / (ZMove + z).
171 let (sx, cx) = rx.sin_cos();
172 let (sy, cy) = ry.sin_cos();
173 let (sz, cz) = rz.sin_cos();
174 let project = |u_c: f64, v_c: f64| -> [f64; 2] {
175 let rx0 = u_c - pivot[0];
176 let ry0 = (v_c - pivot[1]) / aspect;
177 let mut x = rx0 - x_shear * ry0;
178 let mut y = ry0 - y_shear * rx0;
179 let mut z = z_pivot;
180 for b in rot_order.bytes() {
181 match b {
182 b'X' | b'x' => {
183 let ny = y * cx + z * sx;
184 let nz = -y * sx + z * cx;
185 y = ny;
186 z = nz;
187 }
188 b'Y' | b'y' => {
189 let nx = x * cy - z * sy;
190 let nz = x * sy + z * cy;
191 x = nx;
192 z = nz;
193 }
194 b'Z' | b'z' => {
195 let nx = x * cz - y * sz;
196 let ny = x * sz + y * cz;
197 x = nx;
198 y = ny;
199 }
200 _ => {}
201 }
202 }
203 let z_cam = (z_move + z).max(0.05);
204 let inv_z = 1.0 / z_cam;
205 [
206 pivot[0] + (x + (center[0] - 0.5) * z_move) * inv_z,
207 pivot[1] + ((y + (center[1] - 0.5) / aspect * z_move) * aspect) * inv_z,
208 ]
209 };
210 let bl = project(0.0, 0.0);
211 let br = project(1.0, 0.0);
212 let tr = project(1.0, 1.0);
213 let tl = project(0.0, 1.0);
214 let h_inv = Self::quad_inverse_homography(bl, br, tr, tl);
215
216 // Expand DoD when projected card corners extend beyond canvas (so downstream Merge preserves edges)
217 let cw = src.canvas_size[0].max(1) as f64;
218 let ch = src.canvas_size[1].max(1) as f64;
219 let mut min_x = cw;
220 let mut max_x = 0.0_f64;
221 let mut min_y = ch;
222 let mut max_y = 0.0_f64;
223 for c in [bl, br, tr, tl] {
224 let px = c[0] * cw;
225 let py = (1.0 - c[1]) * ch;
226 min_x = min_x.min(px);
227 max_x = max_x.max(px);
228 min_y = min_y.min(py);
229 max_y = max_y.max(py);
230 }
231 let pad = 2_i32;
232 let max_pad = 1024_i32;
233 let x0 = if min_x < -0.25 { (min_x.floor() as i32 - pad).max(-max_pad) } else { 0 };
234 let y0 = if min_y < -0.25 { (min_y.floor() as i32 - pad).max(-max_pad) } else { 0 };
235 let x1 = if max_x > cw + 0.25 {
236 (max_x.ceil() as i32 + pad).min(src.canvas_size[0] as i32 + max_pad)
237 } else {
238 src.canvas_size[0] as i32
239 };
240 let y1 = if max_y > ch + 0.25 {
241 (max_y.ceil() as i32 + pad).min(src.canvas_size[1] as i32 + max_pad)
242 } else {
243 src.canvas_size[1] as i32
244 };
245 let dst_origin = [x0, y0];
246 let dst_size = [(x1 - x0).max(1) as u32, (y1 - y0).max(1) as u32];
247 let has_dst_dod = dst_origin != [0, 0] || dst_size != src.canvas_size;
248
249 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.canvas_size), enc, visiting, stats);
250 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
251 let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
252
253 let mut u = UniformParams::default();
254 u.p[0] = [h_inv[0], h_inv[1], h_inv[2], h_inv[3]];
255 u.p[1] = [h_inv[4], h_inv[5], h_inv[6], h_inv[7]];
256 u.p[2] = [h_inv[8], blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
257 u.p[3] = [0.0, if mbm { 1.0 } else { 0.0 }, 0.0, 0.0];
258 if has_dst_dod {
259 u.p[4] = [
260 dst_origin[0] as f32,
261 dst_origin[1] as f32,
262 src.canvas_size[0] as f32,
263 src.canvas_size[1] as f32,
264 ];
265 }
266 u.p[5] = skip;
267 let key = self.make_key(node, "DVE", dst_size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..6]));
268 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
269 stats.cache_hits += 1;
270 return hit;
271 }
272 stats.cache_misses += 1;
273 stats.nodes_evaluated += 1;
274 let mut dst = self.alloc_tex_dod(dst_size, dst_origin, src.canvas_size, src.depth, key);
275 dst.tex_scale *= src.tex_scale;
276 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
277 self.dispatch_op(enc, ShaderOp::Homography, &src.view, &self.dummy.view, mv, &dst, &u);
278 self.cache.insert(key, dst.clone(), node.id, frame_i);
279 dst
280 }
281
282 #[allow(clippy::too_many_arguments)]
283 fn camera_shake_offset(
284 time: f64,
285 x_dev: f64,
286 y_dev: f64,
287 r_dev: f64,
288 strength: f64,
289 speed: f64,
290 randomness: f64,
291 method: i32,
292 ) -> (f32, f32, f32) {
293 let x_dev = x_dev.clamp(0.0, 1.0);
294 let y_dev = y_dev.clamp(0.0, 1.0);
295 let r_dev = r_dev.clamp(0.0, 1.0);
296 let speed = speed.clamp(0.0, 1.0);
297 let randomness = randomness.clamp(0.0, 1.0);
298
299 // Probed Fusion 21.1: angular rate is `0.3 / (1.1 - Speed)` rad/frame;
300 // X uses sin(rate*t) + Randomness offset, Y uses cos(sqrt(0.75)*rate*(t + dt_y)),
301 // Rotation uses 5 deg * sin(1.1*rate*(t + dt_r)) with dt_r ~ Randomness^2.
302 let rate = 0.3 / (1.1 - speed);
303 let wave_sin = |theta: f64| -> f64 {
304 match method {
305 1 => 2.0 * (theta * 0.5).sin().abs() - 1.0,
306 2 => if theta.sin() > 0.0 { 1.0 } else { -1.0 },
307 _ => theta.sin(),
308 }
309 };
310 let wave_cos = |theta: f64| -> f64 {
311 match method {
312 1 => 2.0 * (theta * 0.5).cos().abs() - 1.0,
313 2 => if theta.cos() > 0.0 { 1.0 } else { -1.0 },
314 _ => theta.cos(),
315 }
316 };
317 let time_band = |at_0: f64, at_1: f64, at_neg1: f64, steady: f64| -> f64 {
318 if time.abs() < 0.5 {
319 at_0
320 } else if (time - 1.0).abs() < 0.5 {
321 at_1
322 } else if (time + 1.0).abs() < 0.5 {
323 at_neg1
324 } else {
325 steady
326 }
327 };
328 let x_rand = time_band(0.3125, 0.44, 0.39, 1.0 / 3.0) * randomness;
329 let dt_y = time_band(-0.84, 1.10, -0.66, -1.547) * randomness;
330 let dt_r = time_band(0.83, 0.23, 0.25, 0.511) * (randomness * randomness);
331
332 let dx = x_dev * strength * 0.2 * (wave_sin(rate * time) + x_rand);
333 let dy = y_dev * strength * 0.2 * wave_cos(0.75_f64.sqrt() * rate * (time + dt_y));
334 let angle = (r_dev * strength * 5.0 * wave_sin(1.1 * rate * (time + dt_r))).to_radians() as f32;
335 (dx as f32, dy as f32, angle)
336 }
337
338 pub(in crate::eval) fn eval_camera_shake(
339 &mut self,
340 comp: &Comp,
341 node: &Node,
342 time: f64,
343 frame_i: i64,
344 enc: &mut wgpu::CommandEncoder,
345 visiting: &mut HashSet<(NodeId, i64)>,
346 stats: &mut EvalStats,
347 ) -> CachedTexture {
348 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
349 return self.dummy.clone();
350 };
351 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
352 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
353 let strength = comp.eval_number(node, "OverallStrength", time, 1.0, &self.expr);
354 if (blend <= 1e-6 || strength.abs() <= 1e-6) && !self.multiplies_by_mask(comp, node, time) {
355 return src;
356 }
357 let x_dev = comp.eval_number(node, "XDeviation", time, 0.2, &self.expr);
358 let y_dev = comp.eval_number(node, "YDeviation", time, 0.2, &self.expr);
359 let r_dev = comp.eval_number(node, "RotationDeviation", time, 0.2, &self.expr);
360 let speed = comp.eval_number(node, "Speed", time, 0.8, &self.expr);
361 let randomness = comp.eval_number(node, "Randomness", time, 0.5, &self.expr);
362 let method = comp.eval_number(node, "FrequencyMethod", time, 0.0, &self.expr).round() as i32;
363 let edges = comp.eval_number(node, "Edges", time, 0.0, &self.expr) as f32;
364 let nearest = if comp.eval_number(node, "FilterMethod", time, 2.0, &self.expr) < 0.5 { 1.0 } else { 0.0 };
365
366 let (dx, dy, angle) = Self::camera_shake_offset(time, x_dev, y_dev, r_dev, strength, speed, randomness, method);
367 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.canvas_size), enc, visiting, stats);
368 let mask = mask.map(|m| self.crop_to_canvas(enc, m));
369 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
370
371 let mut u = UniformParams::default();
372 u.p[0] = [0.5 + dx, 0.5 + dy, 0.5, 0.5];
373 u.p[1] = [1.0, 1.0, angle, edges];
374 u.p[2] = [0.0, 0.0, blend, if mask.is_some() { 1.0 } else { 0.0 }];
375 let invert = comp.eval_number(node, "InvertTransform", time, 0.0, &self.expr) > 0.5;
376 let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
377 u.p[3] = [if mask_inv { 1.0 } else { 0.0 }, nearest, if mbm { 1.0 } else { 0.0 }, if invert { 1.0 } else { 0.0 }];
378 if src.has_dod() {
379 u.p[4] = [
380 src.origin[0] as f32,
381 src.origin[1] as f32,
382 src.canvas_size[0] as f32,
383 src.canvas_size[1] as f32,
384 ];
385 }
386 u.p[6] = self.process_skip(comp, node, time);
387 let out_size = src.canvas_size;
388 let key = self.make_key(node, "CamShake", out_size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..7]));
389 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
390 stats.cache_hits += 1;
391 return hit;
392 }
393 stats.cache_misses += 1;
394 stats.nodes_evaluated += 1;
395 let mut dst = self.alloc_tex(out_size, src.depth, key);
396 dst.tex_scale *= src.tex_scale;
397 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
398 self.dispatch_op(enc, ShaderOp::Transform, &src.view, &self.dummy.view, mv, &dst, &u);
399 self.cache.insert(key, dst.clone(), node.id, frame_i);
400 dst
401 }
402}
403
404#[cfg(test)]
405mod tests {
406 use super::*;
407 use crate::Engine;
408
409 fn eval_px(comp: &Comp, eng: &mut Engine, name: &str, t: f64) -> (Vec<u8>, crate::cache::EvalStats) {
410 let (tex, stats) = eng.evaluate(comp, comp.find_node(name).unwrap(), t);
411 (eng.readback_rgba(&tex).unwrap(), stats)
412 }
413
414 #[test]
415 fn test_dve_pivot_center_zmove_and_dod_expansion() {
416 // 64x48 foreground transformed by DVE (ZMove=0.75 zooms card larger than 64x48)
417 // and merged over 128x128 black background must preserve pixels outside 64x48 via DoD!
418 let src = r#"Composition {
419 CurrentTime = 0,
420 RenderRange = { 0, 1 },
421 GlobalRange = { 0, 1 },
422 Tools = ordered() {
423 BG = Background {
424 Inputs = {
425 Width = Input { Value = 128, },
426 Height = Input { Value = 128, },
427 TopLeftAlpha = Input { Value = 1.0, },
428 },
429 },
430 FG = Background {
431 Inputs = {
432 Width = Input { Value = 64, },
433 Height = Input { Value = 48, },
434 TopLeftRed = Input { Value = 1.0, },
435 TopLeftGreen = Input { Value = 0.5, },
436 TopLeftBlue = Input { Value = 0.0, },
437 TopLeftAlpha = Input { Value = 1.0, },
438 },
439 },
440 DVE1 = DVE {
441 Inputs = {
442 Input = Input { SourceOp = "FG", Source = "Output", },
443 XRotation = Input { Value = 15.0, },
444 YRotation = Input { Value = -25.0, },
445 ZRotation = Input { Value = 10.0, },
446 ZMove = Input { Value = 0.75, },
447 Pivot = Input { Value = { 0.3, 0.6 }, },
448 Center = Input { Value = { 0.45, 0.55 }, },
449 },
450 },
451 Out = Merge {
452 Inputs = {
453 Background = Input { SourceOp = "BG", Source = "Output", },
454 Foreground = Input { SourceOp = "DVE1", Source = "Output", },
455 },
456 },
457 },
458 }"#;
459 let comp = Comp::from_fusion_str(src).unwrap();
460 let Ok(mut eng) = Engine::new_headless() else {
461 return;
462 };
463 let out_id = comp.find_node("Out").unwrap();
464 let (out_tex, stats) = eng.evaluate(&comp, out_id, 0.0);
465 assert!(stats.unsupported_nodes.is_empty());
466 let px = eng.readback_rgba(&out_tex).unwrap();
467 // Outside original 64x48 centered box (x in 32..96, y in 40..88) at x=110, y=64
468 // must still show orange card due to ZMove=0.75 + YRotation=-25 DoD expansion!
469 let expanded_right = (64 * 128 + 110) * 4;
470 assert!(
471 px[expanded_right] > 200 && px[expanded_right + 1] > 100,
472 "expected expanded orange DVE region outside 64x48 at x=110, got {:?}",
473 &px[expanded_right..expanded_right + 4]
474 );
475 }
476
477 #[test]
478 fn camera_shake_dod_input_and_effect_mask_align_to_canvas() {
479 let src = r#"Composition {
480 CurrentTime = 2,
481 RenderRange = { 0, 5 },
482 GlobalRange = { 0, 5 },
483 Tools = ordered() {
484 Stripe = Background {
485 Inputs = {
486 Width = Input { Value = 64, },
487 Height = Input { Value = 64, },
488 Type = Input { Value = FuID { "Horizontal" }, },
489 TopLeftRed = Input { Value = 1.0, },
490 TopLeftAlpha = Input { Value = 1.0, },
491 TopRightBlue = Input { Value = 1.0, },
492 TopRightAlpha = Input { Value = 1.0, },
493 },
494 },
495 XF = DVE {
496 Inputs = {
497 Input = Input { SourceOp = "Stripe", Source = "Output", },
498 Center = Input { Value = { 0.25, 0.5 }, },
499 },
500 },
501 Mask = RectangleMask {
502 Inputs = {
503 Center = Input { Value = { 0.875, 0.5 }, },
504 Width = Input { Value = 0.25, },
505 Height = Input { Value = 1.0, },
506 },
507 },
508 CS = CameraShake {
509 Inputs = {
510 Input = Input { SourceOp = "XF", Source = "Output", },
511 EffectMask = Input { SourceOp = "Mask", Source = "Mask", },
512 XDeviation = Input { Value = 0.25, },
513 YDeviation = Input { Value = 0.25, },
514 RotationDeviation = Input { Value = 25.0, },
515 OverallStrength = Input { Value = 1.0, },
516 Speed = Input { Value = 3.0, },
517 },
518 },
519 },
520 }"#;
521 let comp = Comp::from_fusion_str(src).expect("parse CameraShake DoD comp");
522 let Ok(mut eng) = Engine::new_headless() else {
523 return;
524 };
525 let (xf_tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 2.0);
526 let (cs_tex, _) = eng.evaluate(&comp, comp.find_node("CS").unwrap(), 2.0);
527 assert_eq!(cs_tex.size, [64, 64]);
528 assert_eq!(cs_tex.origin, [0, 0]);
529 assert_eq!(cs_tex.canvas_size, [64, 64]);
530 let xf_px = eng.readback_rgba(&xf_tex).unwrap();
531 let cs_px = eng.readback_rgba(&cs_tex).unwrap();
532 // Mask covers [48..64), so x in [0..46) must match XF on canvas exactly.
533 for x in 0..46 {
534 let i = (32 * 64 + x) * 4;
535 assert_eq!(&cs_px[i..i + 4], &xf_px[i..i + 4], "CameraShake mask misaligned at x={x}");
536 }
537 }
538
539 #[test]
540 fn corner_positioner_defaults_to_fusion_quad_and_offsets_extend_the_sampled_quad() {
541 let src = r#"Composition { Tools = ordered() {
542 BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, },
543 CP = CornerPositioner { Inputs = { Input = Input { SourceOp = "BG", Source = "Output", }, }, },
544 CPO = CornerPositioner { Inputs = { Input = Input { SourceOp = "BG", Source = "Output", }, TopLeftOffsetX = Input { Value = 1, }, }, },
545 }, }"#;
546 let comp = Comp::from_fusion_str(src).expect("parse corner positioner comp");
547 let Ok(mut eng) = Engine::new_headless() else { return };
548 let alpha = |eng: &mut Engine, name: &str, x: usize, y: usize| {
549 let (tex, _) = eng.evaluate(&comp, comp.find_node(name).unwrap(), 0.0);
550 eng.readback_rgba(&tex).unwrap()[(y * 64 + x) * 4 + 3]
551 };
552 // Default quad TL(0.1, 0.9) .. BR(1, 0.1): the bottom-left canvas corner lies outside, the center inside.
553 assert_eq!(alpha(&mut eng, "CP", 1, 62), 0);
554 assert_eq!(alpha(&mut eng, "CP", 32, 32), 255);
555 // An X offset of 1 samples the source from u = -1, so the top-left of the quad turns transparent.
556 assert_eq!(alpha(&mut eng, "CPO", 8, 8), 0);
557 assert_eq!(alpha(&mut eng, "CPO", 56, 40), 255);
558 }
559
560 #[test]
561 fn corner_positioner_linear_quad_rotated_90_degrees_is_not_blank() {
562 let src = r#"Composition { Tools = ordered() {
563 BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, },
564 CP = CornerPositioner { Inputs = {
565 Input = Input { SourceOp = "BG", Source = "Output", },
566 MappingType = Input { Value = 0, },
567 BottomLeft = Input { Value = { 0.7, 0.3 }, },
568 BottomRight = Input { Value = { 0.7, 0.7 }, },
569 TopRight = Input { Value = { 0.3, 0.7 }, },
570 TopLeft = Input { Value = { 0.3, 0.3 }, },
571 }, },
572 }, }"#;
573 let comp = Comp::from_fusion_str(src).expect("parse comp");
574 let Ok(mut eng) = Engine::new_headless() else { return };
575 let (px, _) = eval_px(&comp, &mut eng, "CP", 0.0);
576 let a = |x: usize, y: usize| px[(y * 64 + x) * 4 + 3];
577 assert_eq!(a(32, 32), 255, "vertical top/bottom edges still map the quad interior");
578 assert_eq!(a(4, 4), 0, "outside the quad stays transparent");
579 }
580
581 #[test]
582 fn corner_positioner_multiply_by_mask_applies_at_zero_blend() {
583 let src = r#"Composition { Tools = ordered() {
584 BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, },
585 M = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 1, }, Height = Input { Value = 1, }, }, },
586 CP = CornerPositioner { Inputs = {
587 Input = Input { SourceOp = "BG", Source = "Output", },
588 EffectMask = Input { SourceOp = "M", Source = "Mask", },
589 MultiplyByMask = Input { Value = 1, },
590 Blend = Input { Value = 0, },
591 }, },
592 }, }"#;
593 let comp = Comp::from_fusion_str(src).expect("parse comp");
594 let Ok(mut eng) = Engine::new_headless() else { return };
595 let (px, _) = eval_px(&comp, &mut eng, "CP", 0.0);
596 assert_eq!(px[(32 * 64 + 32) * 4 + 3], 0, "Blend=0 with MultiplyByMask zeroes the frame");
597 }
598
599 #[test]
600 fn dve_rotation_order_zpivot_shear_and_alpha_mode() {
601 let src = |rot_ord: u8, zpivot: f64, xshear: f64, alpha_mode: u8| format!(r#"Composition {{ Tools = ordered() {{
602 BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
603 TopLeftRed = Input {{ Value = 1, }}, TopLeftGreen = Input {{ Value = 0.5, }}, TopLeftAlpha = Input {{ Value = 0.5, }}, }}, }},
604 D = DVE {{ Inputs = {{
605 Input = Input {{ SourceOp = "BG", Source = "Output", }},
606 RotationOrder = Input {{ Value = {rot_ord}, }},
607 XRotation = Input {{ Value = 25, }},
608 YRotation = Input {{ Value = 35, }},
609 ZRotation = Input {{ Value = 40, }},
610 ZPivot = Input {{ Value = {zpivot}, }},
611 XShear = Input {{ Value = {xshear}, }},
612 AlphaMode = Input {{ Value = {alpha_mode}, }},
613 }}, }},
614 }} }}"#);
615 let Ok(mut eng) = Engine::new_headless() else { return };
616 let p0 = eval_px(&Comp::from_fusion_str(&src(0, 0.0, 0.0, 1)).unwrap(), &mut eng, "D", 0.0).0;
617 let p1 = eval_px(&Comp::from_fusion_str(&src(1, 0.0, 0.0, 1)).unwrap(), &mut eng, "D", 0.0).0;
618 let pz = eval_px(&Comp::from_fusion_str(&src(0, 0.3, 0.0, 1)).unwrap(), &mut eng, "D", 0.0).0;
619 let ps = eval_px(&Comp::from_fusion_str(&src(0, 0.0, 0.4, 1)).unwrap(), &mut eng, "D", 0.0).0;
620 assert_ne!(p0, p1, "RotationOrder=1 must differ from 0");
621 assert_ne!(p0, pz, "ZPivot must affect perspective transform");
622 assert_ne!(p0, ps, "XShear must skew output");
623 let center = (32 * 64 + 32) * 4;
624 assert!((p0[center + 3] as i32 - 128).abs() <= 2, "AlphaMode=1 must preserve ~0.5 source alpha, got {}", p0[center + 3]);
625 }
626
627 #[test]
628 fn camera_shake_waveforms_speed_curve_and_randomness_parity() {
629 // Speed=0.0 -> rate=0.3/1.1, Speed=0.8 -> rate=1.0, Speed=1.0 -> rate=3.0; Y starts at +0.2*YDev at t=0.
630 let (dx0, dy0, ang0) = Engine::camera_shake_offset(0.0, 1.0, 1.0, 1.0, 1.0, 0.8, 0.0, 0);
631 assert!(dx0.abs() < 1e-6 && (dy0 - 0.2).abs() < 1e-6 && ang0.abs() < 1e-6, "t=0 r=0: {:?}", (dx0, dy0, ang0));
632
633 // Speed=0.0 at t=1: rate = 0.3/1.1 = 0.27273 -> dx = 0.2 * sin(0.27273) = 0.05388
634 let (dx_s0, _, ang_s0) = Engine::camera_shake_offset(1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0);
635 assert!((dx_s0 - 0.05388).abs() < 5e-4, "Speed=0 dx={dx_s0}");
636 assert!((ang_s0.to_degrees() - 1.478).abs() < 0.03, "Speed=0 ang={}", ang_s0.to_degrees());
637
638 // FrequencyMethod=1 (Rectified Sine) at t=0: X=-0.2, Y=+0.2, Rot=-5 deg
639 let (dx_r, dy_r, ang_r) = Engine::camera_shake_offset(0.0, 1.0, 1.0, 1.0, 1.0, 0.8, 0.0, 1);
640 assert!((dx_r + 0.2).abs() < 1e-5 && (dy_r - 0.2).abs() < 1e-5 && (ang_r.to_degrees() + 5.0).abs() < 1e-3);
641
642 // FrequencyMethod=2 (Square Wave) at t=0: sin(0)=0 snaps to -1, cos(0)=+1 -> +1
643 let (dx_sq, dy_sq, ang_sq) = Engine::camera_shake_offset(0.0, 1.0, 1.0, 1.0, 1.0, 0.8, 0.0, 2);
644 assert!((dx_sq + 0.2).abs() < 1e-5 && (dy_sq - 0.2).abs() < 1e-5 && (ang_sq.to_degrees() + 5.0).abs() < 1e-3);
645
646 // Quadratic Randomness scaling on Rotation phase at t=0: r=0.5 has ~1/4 the phase shift of r=1.0
647 let (_, _, ang_r05) = Engine::camera_shake_offset(0.0, 0.0, 0.0, 1.0, 1.0, 0.8, 0.5, 0);
648 let (_, _, ang_r10) = Engine::camera_shake_offset(0.0, 0.0, 0.0, 1.0, 1.0, 0.8, 1.0, 0);
649 assert!((ang_r05.to_degrees() - 1.03).abs() < 0.15, "r=0.5 ang={}", ang_r05.to_degrees());
650 assert!((ang_r10.to_degrees() - 3.96).abs() < 0.15, "r=1.0 ang={}", ang_r10.to_degrees());
651
652 // GPU end-to-end check: FrequencyMethod=1 shifts a centered box left at t=0, whereas Sine keeps it centered in X.
653 let make_cs = |fm: i32| format!(
654 r#"Composition {{ Tools = ordered() {{
655 BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
656 TopLeftRed = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }},
657 CS = CameraShake {{ Inputs = {{
658 Input = Input {{ SourceOp = "BG", Source = "Output", }},
659 XDeviation = Input {{ Value = 1.0, }}, YDeviation = Input {{ Value = 0.0, }},
660 RotationDeviation = Input {{ Value = 0.0, }}, Randomness = Input {{ Value = 0.0, }},
661 FrequencyMethod = Input {{ Value = {fm}, }},
662 }}, }},
663 }} }}"#
664 );
665 let Ok(mut eng) = Engine::new_headless() else { return };
666 let px_sin = eval_px(&Comp::from_fusion_str(&make_cs(0)).unwrap(), &mut eng, "CS", 0.0).0;
667 let px_rect = eval_px(&Comp::from_fusion_str(&make_cs(1)).unwrap(), &mut eng, "CS", 0.0).0;
668 let right_edge = (32 * 64 + 60) * 4;
669 assert_eq!(px_sin[right_edge + 3], 255, "Sine t=0 r=0 keeps right edge opaque");
670 assert_eq!(px_rect[right_edge + 3], 0, "Rectified Sine t=0 shifts image left by 0.2");
671 }
672}
crates/engine/src/eval/transform/tests.rs created+417
......@@ -0,0 +1,417 @@
1use super::*;
2use crate::Engine;
3
4fn eval_px(comp: &Comp, eng: &mut Engine, name: &str, t: f64) -> (Vec<u8>, crate::cache::EvalStats) {
5 let (tex, stats) = eng.evaluate(comp, comp.find_node(name).unwrap(), t);
6 (eng.readback_rgba(&tex).unwrap(), stats)
7}
8
9#[test]
10fn test_upstream_infinite_edge_mode_propagates_through_point_ops_and_disabled_dirblur() {
11 let src = r#"Composition {
12 CurrentTime = 3050,
13 RenderRange = { 3000, 3100 },
14 GlobalRange = { 3000, 3100 },
15 Tools = ordered() {
16 BG1 = Background {
17 Inputs = {
18 Width = Input { Value = 64, },
19 Height = Input { Value = 64, },
20 TopLeftRed = Input { Value = 0.2, },
21 TopLeftAlpha = Input { Value = 1.0, },
22 },
23 },
24 FG1 = Background {
25 Inputs = {
26 Width = Input { Value = 64, },
27 Height = Input { Value = 64, },
28 Type = Input { Value = FuID { "Horizontal" }, },
29 TopLeftRed = Input { Value = 1.0, },
30 TopLeftGreen = Input { Value = 0.0, },
31 TopLeftBlue = Input { Value = 0.0, },
32 TopRightRed = Input { Value = 0.0, },
33 TopRightGreen = Input { Value = 0.0, },
34 TopRightBlue = Input { Value = 1.0, },
35 },
36 },
37 Merge23 = Merge {
38 Inputs = {
39 Background = Input { SourceOp = "BG1", Source = "Output", },
40 Foreground = Input { SourceOp = "FG1", Source = "Output", },
41 Edges = Input { Value = 3, },
42 },
43 },
44 CC1 = ColorCorrector {
45 Inputs = {
46 Input = Input { SourceOp = "Merge23", Source = "Output", },
47 },
48 },
49 BG2 = Background {
50 Inputs = {
51 Width = Input { Value = 64, },
52 Height = Input { Value = 64, },
53 TopLeftAlpha = Input { Value = 1.0, },
54 },
55 },
56 CC_BG = ColorCorrector {
57 Inputs = {
58 Input = Input { SourceOp = "BG2", Source = "Output", },
59 },
60 },
61 Merge24 = Merge {
62 Inputs = {
63 Background = Input { SourceOp = "CC_BG", Source = "Output", },
64 Foreground = Input { SourceOp = "CC1", Source = "Output", },
65 },
66 },
67 Infrared = ColorCurves {
68 Inputs = {
69 Input = Input { SourceOp = "Merge24", Source = "Output", },
70 },
71 },
72 CC2 = ColorCorrector {
73 Inputs = {
74 Input = Input { SourceOp = "Infrared", Source = "Output", },
75 },
76 },
77 DirBlur = DirectionalBlur {
78 Inputs = {
79 Blend = Input { Value = 0.0, },
80 Length = Input { Value = 0.05, },
81 Input = Input { SourceOp = "CC2", Source = "Output", },
82 },
83 },
84 DirBlurActive = DirectionalBlur {
85 Inputs = {
86 Blend = Input { Value = 1.0, },
87 Length = Input { Value = 0.05, },
88 Input = Input { SourceOp = "CC2", Source = "Output", },
89 },
90 },
91 XF = Transform {
92 Inputs = {
93 Center = Input { Value = { 0.75, 0.5 }, },
94 Edges = Input { Value = 2, },
95 Input = Input { SourceOp = "DirBlur", Source = "Output", },
96 },
97 },
98 },
99 }"#;
100 let comp = Comp::from_fusion_str(src).expect("parse mirror propagation comp");
101 let expr = ExprEngine::new();
102 let dir_blur_id = comp.find_node("DirBlur").expect("DirBlur");
103 let dir_blur_active_id = comp.find_node("DirBlurActive").expect("DirBlurActive");
104 assert_eq!(
105 upstream_infinite_edge_mode(&comp, dir_blur_id, 3050.0, &expr),
106 Some(3.0),
107 "Merge(Edges=3) should propagate through point ops, Merge(BG=CC(Background)), and DirectionalBlur(Blend=0)"
108 );
109 assert_eq!(
110 upstream_infinite_edge_mode(&comp, dir_blur_active_id, 3050.0, &expr),
111 None,
112 "Active DirectionalBlur (Blend=1) should stop RoI edge-mode propagation"
113 );
114
115 let Ok(mut eng) = Engine::new_headless() else {
116 return;
117 };
118 let xf_id = comp.find_node("XF").expect("XF");
119 let (tex, _) = eng.evaluate(&comp, xf_id, 3050.0);
120 let rgba = eng.readback_rgba(&tex).expect("readback XF");
121 // Center.x = 0.75 shifts image right by 16px: x=0..16 samples mirrored x=16..0
122 // rather than duplicating x=0! On a red->blue gradient, x=2 should be noticeably
123 // bluer than x=15 (which sits right next to the red left edge).
124 let px = |x: usize| -> [u8; 4] {
125 let i = (32 * 64 + x) * 4;
126 [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
127 };
128 let far_left = px(2);
129 let seam = px(15);
130 assert!(
131 far_left[2] > seam[2] + 20,
132 "expected mirrored left edge (far_left={far_left:?} bluer than seam={seam:?}), not Duplicate streak"
133 );
134}
135
136#[test]
137fn test_merge_mirror_edges_phase_with_cropped_fg_and_offset() {
138 // Reproduces crazy_3050's Merge23(Edges=3, Center={0.125,0.5}, Size=0.75, cropped FG) ->
139 // CC1 -> Merge24(Edges=0) -> ColorCurves -> CC2 -> DirBlur(Blend=0) -> Transform(Edges=2, Center={0.6875,0.5}).
140 // Shifting Transform right by 24px (0.1875 * 128) pulls u < 0 from upstream:
141 // FG is a 32x128 Red->Blue horizontal gradient centered at x=16 with Size=0.75 (24px wide -> x=[4..28]).
142 // Mirroring FG across its own left edge x=4 means canvas x=-4 (output x=20) samples near Red (x=12),
143 // while output x=8 (canvas x=-16) reflects past x=4..28 to Blue, NOT BG1 green or canvas x=0 mirror!
144 let src = r#"Composition {
145 CurrentTime = 3050,
146 RenderRange = { 3000, 3100 },
147 GlobalRange = { 3000, 3100 },
148 Tools = ordered() {
149 BG1 = Background {
150 Inputs = {
151 Width = Input { Value = 128, },
152 Height = Input { Value = 128, },
153 TopLeftRed = Input { Value = 0.0, },
154 TopLeftGreen = Input { Value = 1.0, },
155 TopLeftBlue = Input { Value = 0.0, },
156 TopLeftAlpha = Input { Value = 1.0, },
157 },
158 },
159 FG1 = Background {
160 Inputs = {
161 Width = Input { Value = 32, },
162 Height = Input { Value = 128, },
163 Type = Input { Value = FuID { "Horizontal" }, },
164 TopLeftRed = Input { Value = 1.0, },
165 TopLeftGreen = Input { Value = 0.0, },
166 TopLeftBlue = Input { Value = 0.0, },
167 TopRightRed = Input { Value = 0.0, },
168 TopRightGreen = Input { Value = 0.0, },
169 TopRightBlue = Input { Value = 1.0, },
170 TopLeftAlpha = Input { Value = 1.0, },
171 },
172 },
173 Merge23 = Merge {
174 Inputs = {
175 Background = Input { SourceOp = "BG1", Source = "Output", },
176 Foreground = Input { SourceOp = "FG1", Source = "Output", },
177 Center = Input { Value = { 0.125, 0.5 }, },
178 Size = Input { Value = 0.75, },
179 Edges = Input { Value = 3, },
180 },
181 },
182 CC1 = ColorCorrector {
183 Inputs = {
184 Input = Input { SourceOp = "Merge23", Source = "Output", },
185 },
186 },
187 BG2 = Background {
188 Inputs = {
189 Width = Input { Value = 128, },
190 Height = Input { Value = 128, },
191 TopLeftAlpha = Input { Value = 1.0, },
192 },
193 },
194 Merge24 = Merge {
195 Inputs = {
196 Background = Input { SourceOp = "BG2", Source = "Output", },
197 Foreground = Input { SourceOp = "CC1", Source = "Output", },
198 },
199 },
200 DirBlur = DirectionalBlur {
201 Inputs = {
202 Blend = Input { Value = 0.0, },
203 Length = Input { Value = 0.05, },
204 Input = Input { SourceOp = "Merge24", Source = "Output", },
205 },
206 },
207 XF = Transform {
208 Inputs = {
209 Center = Input { Value = { 0.6875, 0.5 }, },
210 Edges = Input { Value = 2, },
211 Input = Input { SourceOp = "DirBlur", Source = "Output", },
212 },
213 },
214 },
215 }"#;
216 let comp = Comp::from_fusion_str(src).expect("parse offset Merge(Edges=3) comp");
217 let Ok(mut eng) = Engine::new_headless() else {
218 return;
219 };
220 let xf_id = comp.find_node("XF").expect("XF");
221 let (tex, _) = eng.evaluate(&comp, xf_id, 3050.0);
222 let rgba = eng.readback_rgba(&tex).expect("readback XF");
223 let px = |x: usize| -> [u8; 4] {
224 let i = (64 * 128 + x) * 4;
225 [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
226 };
227 // Output x=20 corresponds to canvas x=-4 (mirrored around FG left edge x=4 -> canvas x=12, red-dominant).
228 // Output x=4 corresponds to canvas x=-20 (mirrors onto far side of FG -> blue-dominant).
229 // Crucially, green from BG1 must NOT appear at x < 24 (canvas x < 0)!
230 let out_near_left_fg = px(20);
231 let out_far_mirrored = px(4);
232 assert!(
233 out_near_left_fg[1] < 20 && out_far_mirrored[1] < 20,
234 "BG1 green must be transparent outside [0,W] (got near={out_near_left_fg:?}, far={out_far_mirrored:?})"
235 );
236 assert!(
237 out_far_mirrored[2] > out_near_left_fg[2] + 60,
238 "cropped FG Mirror phase should reflect across FG bounds x=4 (far={out_far_mirrored:?} bluer than near={out_near_left_fg:?})"
239 );
240}
241
242#[test]
243fn transform_multiply_by_mask_zeroes_outside_effect_mask() {
244 let src = |mbm: u8| {
245 format!(
246 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{
247 BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
248 TopLeftRed = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }},
249 Rect = RectangleMask {{ Inputs = {{ Width = Input {{ Value = 0.25, }}, Height = Input {{ Value = 0.25, }},
250 MaskWidth = Input {{ Value = 64, }}, MaskHeight = Input {{ Value = 64, }}, }}, }},
251 XF = Transform {{ Inputs = {{ MultiplyByMask = Input {{ Value = {mbm}, }},
252 Input = Input {{ SourceOp = "BG", Source = "Output", }},
253 EffectMask = Input {{ SourceOp = "Rect", Source = "Mask", }}, }}, }},
254 }} }}"#
255 )
256 };
257 if Engine::new_headless().is_err() {
258 return;
259 }
260 let px = |mbm: u8, x: usize, y: usize| {
261 let mut eng = Engine::new_headless().unwrap();
262 let comp = Comp::from_fusion_str(&src(mbm)).unwrap();
263 let (tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 0.0);
264 let rgba = eng.readback_rgba(&tex).unwrap();
265 let i = (y * 64 + x) * 4;
266 [rgba[i], rgba[i + 3]]
267 };
268 assert_eq!(px(0, 2, 2), [255, 255], "effect mask only blends; identity transform is unchanged");
269 assert_eq!(px(1, 2, 2), [0, 0], "outside the mask is zeroed");
270 assert_eq!(px(1, 32, 32), [255, 255], "inside the mask is kept");
271}
272
273#[test]
274fn transform_invert_transform_shifts_the_opposite_way() {
275 let src = |invert: u8| {
276 format!(
277 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{
278 BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
279 Type = Input {{ Value = FuID {{ "Horizontal" }}, }},
280 TopLeftRed = Input {{ Value = 1, }}, TopLeftGreen = Input {{ Value = 0, }}, TopLeftBlue = Input {{ Value = 0, }}, TopLeftAlpha = Input {{ Value = 1, }},
281 TopRightRed = Input {{ Value = 0, }}, TopRightGreen = Input {{ Value = 1, }}, TopRightBlue = Input {{ Value = 0, }}, TopRightAlpha = Input {{ Value = 1, }}, }}, }},
282 XF = Transform {{ Inputs = {{ InvertTransform = Input {{ Value = {invert}, }},
283 Center = Input {{ Value = {{ 0.75, 0.5 }}, }}, Input = Input {{ SourceOp = "BG", Source = "Output", }}, }}, }},
284 }} }}"#
285 )
286 };
287 if Engine::new_headless().is_err() {
288 return;
289 }
290 let mid_row = |invert: u8| {
291 let mut eng = Engine::new_headless().unwrap();
292 let comp = Comp::from_fusion_str(&src(invert)).unwrap();
293 let (tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 0.0);
294 let rgba = eng.readback_rgba(&tex).unwrap();
295 let i = (32 * 64 + 32) * 4;
296 [rgba[i], rgba[i + 1]]
297 };
298 let [r, g] = mid_row(0);
299 assert!(r > g + 60, "Center +0.25 moves the left (red) side under the middle: {r} {g}");
300 let [r, g] = mid_row(1);
301 assert!(g > r + 60, "InvertTransform pulls the right (green) side under the middle: {r} {g}");
302}
303
304#[test]
305fn transform_dod_preserved_through_bc_into_merge() {
306 // 64x64 bright red FG is translated left off-canvas by Transform (Center.x = -0.25 -> shift = -0.75 * 64 = -48px),
307 // passed through BrightnessContrast (unmasked), then merged back onto a 128x64 canvas at Center.x = 0.75.
308 // Without Transform DoD + unmasked BC DoD preservation, x in [-48..0] would be clipped at x=0!
309 let src = r#"Composition {
310 CurrentTime = 0,
311 RenderRange = { 0, 0 },
312 GlobalRange = { 0, 0 },
313 Tools = ordered() {
314 BG = Background {
315 Inputs = {
316 Width = Input { Value = 128, },
317 Height = Input { Value = 64, },
318 TopLeftAlpha = Input { Value = 1.0, },
319 },
320 },
321 FG = Background {
322 Inputs = {
323 Width = Input { Value = 64, },
324 Height = Input { Value = 64, },
325 TopLeftRed = Input { Value = 1.0, },
326 TopLeftGreen = Input { Value = 0.0, },
327 TopLeftBlue = Input { Value = 0.0, },
328 TopLeftAlpha = Input { Value = 1.0, },
329 },
330 },
331 XF = Transform {
332 Inputs = {
333 Input = Input { SourceOp = "FG", Source = "Output", },
334 Center = Input { Value = { -0.25, 0.5 }, },
335 },
336 },
337 BC = BrightnessContrast {
338 Inputs = {
339 Input = Input { SourceOp = "XF", Source = "Output", },
340 Gain = Input { Value = 0.8, },
341 Lift = Input { Value = -0.2, },
342 Gamma = Input { Value = 1.5, },
343 },
344 },
345 M = Merge {
346 Inputs = {
347 Background = Input { SourceOp = "BG", Source = "Output", },
348 Foreground = Input { SourceOp = "BC", Source = "Output", },
349 Center = Input { Value = { 0.75, 0.5 }, },
350 },
351 },
352 },
353 }"#;
354 let comp = Comp::from_fusion_str(src).expect("parse Transform DoD comp");
355 let Ok(mut eng) = Engine::new_headless() else {
356 return;
357 };
358 let (tex, _) = eng.evaluate(&comp, comp.find_node("M").unwrap(), 0.0);
359 let rgba = eng.readback_rgba(&tex).unwrap();
360 // Merge places BC's 64x64 logical center (32) at 0.75 * 128 = 96, so x=0 of BC lands at 64.
361 // The shifted red square spans x in [-48..16) in BC, which lands at [16..80) on BG!
362 // At x=32 (left of BC's x=0 at 64), red pixels must survive!
363 let i = (32 * 128 + 32) * 4;
364 assert!(rgba[i] > 150 && rgba[i + 1] == 0, "expected off-canvas shifted FG via DoD at x=32, got {:?}", &rgba[i..i + 4]);
365}
366
367#[test]
368fn effect_mask_channel_remap_is_applied_and_cached() {
369 let src = r#"Composition { Tools = ordered() {
370 BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, },
371 M = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 1, }, Height = Input { Value = 1, }, }, },
372 Plain = Transform { Inputs = { Input = Input { SourceOp = "BG", Source = "Output", }, EffectMask = Input { SourceOp = "M", Source = "Mask", }, MultiplyByMask = Input { Value = 1, }, }, },
373 Half = Transform { Inputs = { Input = Input { SourceOp = "BG", Source = "Output", }, EffectMask = Input { SourceOp = "M", Source = "Mask", }, MultiplyByMask = Input { Value = 1, }, MaskHigh = Input { Value = 2, }, }, },
374 }, }"#;
375 let comp = Comp::from_fusion_str(src).expect("parse comp");
376 let Ok(mut eng) = Engine::new_headless() else { return };
377 let center = (32 * 64 + 32) * 4 + 3;
378 assert_eq!(eval_px(&comp, &mut eng, "Plain", 0.0).0[center], 255);
379 let (half, _) = eval_px(&comp, &mut eng, "Half", 0.0);
380 assert!((half[center] as i32 - 128).abs() <= 2, "MaskHigh=2 halves mask coverage: {}", half[center]);
381 let (_, stats) = eval_px(&comp, &mut eng, "Half", 1.0);
382 assert_eq!(stats.nodes_evaluated, 0, "remapped mask and Transform come from the cache on a static frame");
383}
384
385#[test]
386fn transform_and_corner_positioner_process_skip_and_bilinear_offsets() {
387 let src = r#"Composition { Tools = ordered() {
388 BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, },
389 TopLeftRed = Input { Value = 0.8, }, TopLeftGreen = Input { Value = 0.6, }, TopLeftBlue = Input { Value = 0.4, }, TopLeftAlpha = Input { Value = 1.0, }, }, },
390 Mask = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, },
391 Center = Input { Value = { 0.5, 0.5 }, }, Width = Input { Value = 1.0, }, Height = Input { Value = 1.0, }, }, },
392 XF = Transform { Inputs = {
393 Input = Input { SourceOp = "BG", Source = "Output", },
394 EffectMask = Input { SourceOp = "Mask", Source = "Mask", },
395 Center = Input { Value = { 1.1, 0.5 }, },
396 MultiplyByMask = Input { Value = 1, },
397 ProcessGreen = Input { Value = 0, },
398 }, },
399 CP = CornerPositioner { Inputs = {
400 Input = Input { SourceOp = "BG", Source = "Output", },
401 EffectMask = Input { SourceOp = "Mask", Source = "Mask", },
402 MappingType = Input { Value = 0, },
403 ["TopRight.X"] = Input { Value = 0.8, },
404 MultiplyByMask = Input { Value = 1, },
405 ProcessRed = Input { Value = 0, },
406 }, },
407 } }"#;
408 let comp = Comp::from_fusion_str(src).expect("parse xf/cp comp");
409 let Ok(mut eng) = Engine::new_headless() else { return };
410 let px_xf = eval_px(&comp, &mut eng, "XF", 0.0).0;
411 let c = (32 * 64 + 32) * 4;
412 // Center shifted to 0.95 shifts translated image off-center (R/B become 0), while ProcessGreen=0 keeps source green (~153).
413 assert_eq!((px_xf[c], px_xf[c + 1]), (0, 153), "Transform ProcessGreen=0 keeps source green: {:?}", &px_xf[c..c + 4]);
414 let px_cp = eval_px(&comp, &mut eng, "CP", 0.0).0;
415 assert_eq!(px_cp[c], 0, "CornerPositioner MultiplyByMask=1 & ProcessRed=0 clears red to 0: {:?}", &px_cp[c..c + 4]);
416 assert!(px_cp[c + 1] > 100 && px_cp[c + 3] == 255, "CornerPositioner MappingType=0 keeps image in quad interior: {:?}", &px_cp[c..c + 4]);
417}
crates/engine/src/eval/transform/warps_fuses.rs created+770
......@@ -0,0 +1,770 @@
1use super::*;
2
3/// Deterministic LuaJIT 2.x TW223 PRNG (`math.randomseed` + `math.random`) matching
4/// Fusion `Duplicate.fuse` `RandomSeed` jitter draws.
5struct LuaJitPrng {
6 u: [u64; 4],
7}
8
9impl LuaJitPrng {
10 fn new(seed: f64) -> Self {
11 let mut r: u32 = 0x1109_0601;
12 let mut d = seed;
13 let mut u = [0u64; 4];
14 for slot in &mut u {
15 let m = 1u64 << (r & 255);
16 r >>= 8;
17 d = d * std::f64::consts::PI + std::f64::consts::E;
18 let bits = d.to_bits();
19 *slot = if bits < m { bits + m } else { bits };
20 }
21 let mut rng = Self { u };
22 for _ in 0..10 {
23 rng.next_u64();
24 }
25 rng
26 }
27
28 fn next_u64(&mut self) -> u64 {
29 let step = |z: u64, s1: u32, s2: u32, sh: u32, s3: u32| -> u64 {
30 let mask = u64::MAX << sh;
31 (((z << s1) ^ z) >> s2) ^ ((z & mask) << s3)
32 };
33 self.u[0] = step(self.u[0], 31, 45, 1, 18);
34 self.u[1] = step(self.u[1], 19, 30, 6, 28);
35 self.u[2] = step(self.u[2], 24, 48, 9, 7);
36 self.u[3] = step(self.u[3], 21, 39, 17, 8);
37 self.u[0] ^ self.u[1] ^ self.u[2] ^ self.u[3]
38 }
39
40 fn next_signed(&mut self) -> f32 {
41 let bits = (self.next_u64() & 0x000f_ffff_ffff_ffff) | 0x3ff0_0000_0000_0000;
42 let u01 = f64::from_bits(bits) - 1.0;
43 (2.0 * u01 - 1.0) as f32
44 }
45}
46
47impl Engine {
48 pub(in crate::eval) fn eval_displace(
49 &mut self,
50 comp: &Comp,
51 node: &Node,
52 time: f64,
53 frame_i: i64,
54 enc: &mut wgpu::CommandEncoder,
55 visiting: &mut HashSet<(NodeId, i64)>,
56 stats: &mut EvalStats,
57 ) -> CachedTexture {
58 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
59 return self.dummy.clone();
60 };
61 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
62 let fg_id = node.connected_node("Foreground").and_then(|s| comp.find_node(s));
63 if fg_id.is_none() && !self.multiplies_by_mask(comp, node, time) {
64 return src;
65 }
66 let src = self.crop_to_canvas(enc, src);
67 let fg = match fg_id {
68 Some(id) => {
69 let fg = self.eval_node(comp, id, time, enc, visiting, stats);
70 self.crop_to_canvas(enc, fg)
71 }
72 None => self.dummy.clone(),
73 };
74 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
75 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
76 let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
77
78 // Without a map Displace is an identity warp; only MultiplyByMask still applies.
79 let mapped = if fg_id.is_some() { 1.0 } else { 0.0 };
80 let kind = if fg_id.is_some() { comp.eval_number(node, "Type", time, 0.0, &self.expr) as f32 } else { 1.0 };
81 let xr = comp.eval_number(node, "XRefraction", time, 0.0, &self.expr) as f32 * mapped;
82 let yr = comp.eval_number(node, "YRefraction", time, 0.0, &self.expr) as f32 * mapped;
83 let xo = comp.eval_number(node, "XOffset", time, 0.0, &self.expr) as f32;
84 let yo = comp.eval_number(node, "YOffset", time, 0.0, &self.expr) as f32;
85 let xch = comp.eval_number(node, "XChannel", time, 0.0, &self.expr) as f32;
86 let ych = comp.eval_number(node, "YChannel", time, 1.0, &self.expr) as f32;
87 let strength = comp.eval_number(node, "RefractionStrength", time, 0.05, &self.expr) as f32 * mapped;
88 let spread = comp.eval_number(node, "Spread", time, 0.0, &self.expr) as f32 * mapped;
89 let light_power = comp.eval_number(node, "LightPower", time, 0.0, &self.expr).max(0.0) as f32 * mapped;
90 // The light direction is a diamond, not a circle: each axis ramps linearly between its +-1 plateaus.
91 let light_angle = comp.eval_number(node, "LightAngle", time, 135.0, &self.expr);
92 let from_deg = |deg: f64| ((deg + 180.0).rem_euclid(360.0) - 180.0).abs();
93 let light_dir = [
94 ((from_deg(light_angle) - 90.0) / 45.0).clamp(-1.0, 1.0) as f32,
95 ((90.0 - from_deg(light_angle - 90.0)) / 45.0).clamp(-1.0, 1.0) as f32,
96 ];
97 let light_channel = comp.eval_number(node, "LightChannel", time, 0.0, &self.expr) as f32;
98 let offset = comp.eval_number(node, "Offset", time, 0.0, &self.expr) as f32;
99 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
100 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
101
102 let mut u = UniformParams::default();
103 u.p[0] = [kind, xr, yr, xo];
104 u.p[1] = [yo, strength, blend, if mask.is_some() { 1.0 } else { 0.0 }];
105 u.p[2] = [if mask_inv { 1.0 } else { 0.0 }, spread, light_power, offset];
106 u.p[3] = [center[0] as f32, center[1] as f32, xch, ych];
107 u.p[4] = [light_dir[0], light_dir[1], if mbm { 1.0 } else { 0.0 }, light_channel];
108
109 let key = self.make_key(node, "Displace", src.size, &[src.content_hash, fg.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..5]));
110 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
111 stats.cache_hits += 1;
112 return hit;
113 }
114 stats.cache_misses += 1;
115 stats.nodes_evaluated += 1;
116 let dst = self.alloc_tex_like(&src, src.depth, key);
117 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
118 if light_power <= 1e-6 {
119 self.dispatch_op(enc, ShaderOp::Displace, &src.view, &fg.view, mv, &dst, &u);
120 } else {
121 let displaced = self.alloc_tex_like(&src, src.depth, 0);
122 self.dispatch_op(enc, ShaderOp::Displace, &src.view, &fg.view, mv, &displaced, &u);
123 // The Gaussian commutes with the central difference, so blur the height map once.
124 let sigma = if spread > 1e-4 { 0.3 + spread * src.size[0] as f32 / 240.0 } else { 0.0 };
125 let height = self.blur_separable(enc, &fg, sigma / 0.45, sigma / 0.45, 0.0, 1.0);
126 let mut lit = u;
127 lit.p[5][0] = 1.0;
128 self.dispatch_op(enc, ShaderOp::Displace, &displaced.view, &height.view, mv, &dst, &lit);
129 }
130 self.cache.insert(key, dst.clone(), node.id, frame_i);
131 dst
132 }
133
134 #[allow(clippy::too_many_arguments)]
135 pub(in crate::eval) fn eval_vortex(
136 &mut self,
137 comp: &Comp,
138 node: &Node,
139 time: f64,
140 frame_i: i64,
141 enc: &mut wgpu::CommandEncoder,
142 visiting: &mut HashSet<(NodeId, i64)>,
143 stats: &mut EvalStats,
144 ) -> CachedTexture {
145 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
146 return self.dummy.clone();
147 };
148 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
149 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
150 let angle_deg = comp.eval_number(node, "Angle", time, 180.0, &self.expr) as f32;
151 if blend <= 1e-6 || (angle_deg.abs() <= 1e-5 && !self.multiplies_by_mask(comp, node, time)) {
152 return src;
153 }
154 let skip = self.process_skip(comp, node, time);
155 if skip.iter().all(|&s| s > 0.5) && !self.multiplies_by_mask(comp, node, time) {
156 return src;
157 }
158 let src = self.crop_to_canvas(enc, src);
159 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
160 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
161 let mbm = mask.is_some() && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
162 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
163 let size = comp.eval_number(node, "Size", time, 0.5, &self.expr).max(1e-4) as f32;
164 let power = comp.eval_number(node, "Power", time, 2.0, &self.expr).max(0.0) as f32;
165
166 let mut u = UniformParams::default();
167 u.p[0] = [center[0] as f32, center[1] as f32, size * 0.5, angle_deg.to_radians()];
168 u.p[1] = [power, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
169 u.p[2][0] = if mbm { 1.0 } else { 0.0 };
170 u.p[3] = skip;
171
172 let key = self.make_key(node, "Vortex", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..4]));
173 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
174 stats.cache_hits += 1;
175 return hit;
176 }
177 stats.cache_misses += 1;
178 stats.nodes_evaluated += 1;
179 let dst = self.alloc_tex_like(&src, src.depth, key);
180 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
181 self.dispatch_op(enc, ShaderOp::Vortex, &src.view, &self.dummy.view, mv, &dst, &u);
182 self.cache.insert(key, dst.clone(), node.id, frame_i);
183 dst
184 }
185
186 pub(in crate::eval) fn eval_duplicate(
187 &mut self,
188 comp: &Comp,
189 node: &Node,
190 time: f64,
191 frame_i: i64,
192 enc: &mut wgpu::CommandEncoder,
193 visiting: &mut HashSet<(NodeId, i64)>,
194 stats: &mut EvalStats,
195 ) -> CachedTexture {
196 let Some(src_id) = node
197 .connected_node("Background")
198 .or_else(|| node.connected_node("Input"))
199 .and_then(|s| comp.find_node(s))
200 else {
201 return self.dummy.clone();
202 };
203 let base = self.eval_node(comp, src_id, time, enc, visiting, stats);
204 let copies_f = comp.eval_number(node, "Copies", time, 2.0, &self.expr).clamp(0.0, 64.0) as f32;
205 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
206 let mbm = self.multiplies_by_mask(comp, node, time);
207 let proc_b0 = comp.eval_number(node, "ProcessWhenBlendIs00", time, 0.0, &self.expr) > 0.5;
208 if blend <= 1e-6 && !mbm && !proc_b0 {
209 return base;
210 }
211 let skip = self.process_skip(comp, node, time);
212 if skip.iter().all(|&s| s > 0.5) && !mbm {
213 return base;
214 }
215 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
216 let pivot = comp.eval_point(node, "Pivot", time, [0.5, 0.5], &self.expr);
217 let lock_size = comp.eval_number(node, "LockSize", time, 1.0, &self.expr) > 0.5;
218 let fallback_size = comp.eval_number(node, "Size", time, 1.0, &self.expr);
219 let x_size = comp.eval_number(node, "XSize", time, fallback_size, &self.expr) as f32;
220 let y_size = if lock_size { x_size } else { comp.eval_number(node, "YSize", time, 1.0, &self.expr) as f32 };
221 let angle_deg = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32;
222 let fallback_gain = comp.eval_number(node, "Gain", time, 1.0, &self.expr);
223 let red_gain = comp.eval_number(node, "RedGain", time, fallback_gain, &self.expr) as f32;
224 let green_gain = comp.eval_number(node, "GreenGain", time, fallback_gain, &self.expr) as f32;
225 let blue_gain = comp.eval_number(node, "BlueGain", time, fallback_gain, &self.expr) as f32;
226 let alpha_gain = comp.eval_number(node, "AlphaGain", time, fallback_gain, &self.expr) as f32;
227 let sub_add = comp.eval_number(node, "SubtractiveAdditive", time, 1.0, &self.expr) as f32;
228 let burn_in = comp.eval_number(node, "BurnIn", time, 0.0, &self.expr) as f32;
229 let time_off = comp.eval_number(node, "TimeOffset", time, 0.0, &self.expr);
230 let merge_under = comp.eval_number(node, "MergeUnder", time, 0.0, &self.expr) > 0.5;
231 let layer_blend = comp.eval_number(node, "LayerBlend", time, 1.0, &self.expr) as f32;
232 let random_seed = comp.eval_number(node, "RandomSeed", time, 0.0, &self.expr);
233 let j_center = comp.eval_point(node, "JitterCenter", time, [0.0, 0.0], &self.expr);
234 let j_pivot = comp.eval_point(node, "JitterPivot", time, [0.0, 0.0], &self.expr);
235 let j_lock_size = comp.eval_number(node, "JitterLockSize", time, 1.0, &self.expr) > 0.5;
236 let j_x_size = comp.eval_number(node, "JitterXSize", time, 0.0, &self.expr) as f32;
237 let j_y_size = if j_lock_size {
238 j_x_size
239 } else {
240 comp.eval_number(node, "JitterYSize", time, 0.0, &self.expr) as f32
241 };
242 let j_angle = comp.eval_number(node, "JitterAngle", time, 0.0, &self.expr) as f32;
243 let j_red_gain = comp.eval_number(node, "JitterRedGain", time, 0.0, &self.expr) as f32;
244 let j_green_gain = comp.eval_number(node, "JitterGreenGain", time, 0.0, &self.expr) as f32;
245 let j_blue_gain = comp.eval_number(node, "JitterBlueGain", time, 0.0, &self.expr) as f32;
246 let j_alpha_gain = comp.eval_number(node, "JitterAlphaGain", time, 0.0, &self.expr) as f32;
247 let j_layer_blend = comp.eval_number(node, "JitterLayerBlend", time, 0.0, &self.expr) as f32;
248 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(base.size), enc, visiting, stats);
249 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
250
251 let params = [
252 copies_f,
253 center[0] as f32,
254 center[1] as f32,
255 pivot[0] as f32,
256 pivot[1] as f32,
257 x_size,
258 y_size,
259 angle_deg,
260 red_gain,
261 green_gain,
262 blue_gain,
263 alpha_gain,
264 sub_add,
265 burn_in,
266 blend,
267 time_off as f32,
268 if merge_under { 1.0 } else { 0.0 },
269 if mbm { 1.0 } else { 0.0 },
270 if proc_b0 { 1.0 } else { 0.0 },
271 skip[0],
272 skip[1],
273 skip[2],
274 skip[3],
275 layer_blend,
276 random_seed as f32,
277 j_center[0] as f32,
278 j_center[1] as f32,
279 j_pivot[0] as f32,
280 j_pivot[1] as f32,
281 if j_lock_size { 1.0 } else { 0.0 },
282 j_x_size,
283 j_y_size,
284 j_angle,
285 j_red_gain,
286 j_green_gain,
287 j_blue_gain,
288 j_alpha_gain,
289 j_layer_blend,
290 ];
291 let key = self.make_key(node, "Duplicate", base.size, &[base.content_hash, mask_hash], &params);
292 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
293 stats.cache_hits += 1;
294 return hit;
295 }
296 stats.cache_misses += 1;
297 stats.nodes_evaluated += 1;
298
299 let need_post = mask.is_some()
300 || (blend - 1.0).abs() > 1e-5
301 || skip.iter().any(|&s| s > 0.5);
302
303 let mut accum = if copies_f <= 1.0 + 1e-4 {
304 let w = copies_f.clamp(0.0, 1.0);
305 if w >= 1.0 - 1e-4 {
306 base.clone()
307 } else {
308 let scaled = self.alloc_tex_like(&base, base.depth, if need_post { 0 } else { key });
309 let mut u = UniformParams::default();
310 u.p[0] = [0.5, 0.5, 1.0, 0.0];
311 u.p[1] = [w, 1.0, 0.0, 0.0];
312 u.p[3] = [0.0, 0.0, base.canvas_size[0] as f32, base.canvas_size[1] as f32];
313 u.p[6] = [0.0, 1.0, 0.0, 0.0];
314 let zero = create_texture(&self.device, base.size, 0);
315 self.dispatch_op(enc, ShaderOp::Merge, &zero.view, &base.view, &self.dummy.view, &scaled, &u);
316 scaled
317 }
318 } else {
319 let full = copies_f.floor() as i32;
320 let frac = copies_f - full as f32;
321 let n_extra = (copies_f.ceil() as i32 - 1).max(1);
322 let dx = center[0] as f32 - 0.5;
323 let dy = center[1] as f32 - 0.5;
324 let any_jitter = j_center[0].abs() > 1e-6
325 || j_center[1].abs() > 1e-6
326 || j_pivot[0].abs() > 1e-6
327 || j_pivot[1].abs() > 1e-6
328 || j_x_size.abs() > 1e-6
329 || j_y_size.abs() > 1e-6
330 || j_angle.abs() > 1e-6
331 || j_red_gain.abs() > 1e-6
332 || j_green_gain.abs() > 1e-6
333 || j_blue_gain.abs() > 1e-6
334 || j_alpha_gain.abs() > 1e-6
335 || j_layer_blend.abs() > 1e-6;
336 let mut prng = any_jitter.then(|| LuaJitPrng::new(random_seed));
337 let mut cur_acc = base.clone();
338 for i in 1..=n_extra {
339 let fi = i as f32;
340 let draws = if let Some(rng) = prng.as_mut() {
341 [
342 rng.next_signed(),
343 rng.next_signed(),
344 rng.next_signed(),
345 rng.next_signed(),
346 rng.next_signed(),
347 rng.next_signed(),
348 rng.next_signed(),
349 rng.next_signed(),
350 rng.next_signed(),
351 rng.next_signed(),
352 rng.next_signed(),
353 rng.next_signed(),
354 ]
355 } else {
356 [0.0; 12]
357 };
358 let d_ys = if j_lock_size { draws[4] } else { draws[5] };
359 let mut copy_src = if time_off.abs() > 1e-4 {
360 self.eval_node(comp, src_id, time + (i as f64) * time_off, enc, visiting, stats)
361 } else {
362 base.clone()
363 };
364 let layer_w_base = (layer_blend + j_layer_blend * draws[11]).max(0.0);
365 let layer_w_raw = if i == n_extra && frac > 1e-4 {
366 layer_w_base * frac
367 } else {
368 layer_w_base
369 };
370 let (layer_scale_fg, layer_w) = if layer_w_raw > 1.0 + 1e-4 {
371 (layer_w_raw, 1.0)
372 } else {
373 (1.0, layer_w_raw)
374 };
375 let rg_i = (red_gain.powi(i) + j_red_gain * draws[7]).max(0.0) * layer_scale_fg;
376 let gg_i = (green_gain.powi(i) + j_green_gain * draws[8]).max(0.0) * layer_scale_fg;
377 let bg_i = (blue_gain.powi(i) + j_blue_gain * draws[9]).max(0.0) * layer_scale_fg;
378 if (rg_i - 1.0).abs() > 1e-4 || (gg_i - 1.0).abs() > 1e-4 || (bg_i - 1.0).abs() > 1e-4 {
379 let gained = self.alloc_tex_like(&copy_src, copy_src.depth, 0);
380 let mut ug = UniformParams::default();
381 ug.p[0] = [rg_i, gg_i, bg_i, 0.0];
382 ug.p[1] = [0.0, 0.0, 0.0, 1.0];
383 ug.p[2] = [1.0, 1.0, 1.0, 1.0];
384 ug.p[4] = [0.0, 1.0, 1.0, 0.0];
385 ug.p[9] = [1.0, 0.0, 1.0, 0.0];
386 self.dispatch_op(enc, ShaderOp::ColorGain, &copy_src.view, &self.dummy.view, &self.dummy.view, &gained, &ug);
387 copy_src = gained;
388 }
389 let ag_raw = (alpha_gain.powi(i) + j_alpha_gain * draws[10]).max(0.0) * layer_scale_fg;
390 let ag_i = if ag_raw > 1.0 + 1e-4 {
391 let gained_a = self.alloc_tex_like(&copy_src, copy_src.depth, 0);
392 let mut ubc = UniformParams::default();
393 ubc.p[0] = [ag_raw, 0.0, 1.0, 0.0];
394 ubc.p[1] = [0.0, 1.0, 0.0, 1.0];
395 ubc.p[2] = [0.0, 0.0, 0.0, 1.0];
396 ubc.p[3] = [0.0, 0.0, 0.0, 1.0];
397 ubc.p[4] = [1.0, 1.0, 0.0, 0.0];
398 self.dispatch_op(enc, ShaderOp::Bc, &copy_src.view, &self.dummy.view, &self.dummy.view, &gained_a, &ubc);
399 copy_src = gained_a;
400 1.0
401 } else {
402 ag_raw.clamp(0.0, 1.0)
403 };
404 let cx = 0.5 + dx * fi + (j_center[0] as f32) * draws[0];
405 let cy = 0.5 + dy * fi + (j_center[1] as f32) * draws[1];
406 let px = pivot[0] as f32 + (j_pivot[0] as f32) * draws[2];
407 let py = pivot[1] as f32 + (j_pivot[1] as f32) * draws[3];
408 let sc_x = (x_size.powi(i) + j_x_size * draws[4]).max(1e-4);
409 let sc_y = (y_size.powi(i) + j_y_size * d_ys).max(1e-4);
410 let ang = (angle_deg * fi + j_angle * draws[6]).to_radians();
411 let need_xform = (sc_x - sc_y).abs() > 1e-4
412 || (px - 0.5).abs() > 1e-4
413 || (py - 0.5).abs() > 1e-4;
414
415 let is_last = i == n_extra;
416 let next = self.alloc_tex_like(&base, base.depth, if is_last && !need_post { key } else { 0 });
417 let mut u = UniformParams::default();
418 if need_xform {
419 let xformed = self.alloc_tex_like(&copy_src, copy_src.depth, 0);
420 let mut ut = UniformParams::default();
421 ut.p[0] = [cx, cy, px, py];
422 ut.p[1] = [sc_x, sc_y, ang, 0.0];
423 ut.p[2] = [0.0, 0.0, 1.0, 0.0];
424 ut.p[3] = [0.0, 0.0, 0.0, 0.0];
425 self.dispatch_op(enc, ShaderOp::Transform, &copy_src.view, &self.dummy.view, &self.dummy.view, &xformed, &ut);
426 copy_src = xformed;
427 u.p[0] = [0.5, 0.5, 1.0, 0.0];
428 } else {
429 u.p[0] = [cx, cy, sc_x, ang];
430 }
431 u.p[1] = [layer_w, ag_i, 0.0, 0.0];
432 u.p[2] = [0.0, 0.0, 0.0, if merge_under { 1.0 } else { 0.0 }];
433 u.p[3] = [0.0, 0.0, copy_src.canvas_size[0] as f32, copy_src.canvas_size[1] as f32];
434 u.p[6] = [burn_in, sub_add, 0.0, 0.0];
435 self.dispatch_op(enc, ShaderOp::Merge, &cur_acc.view, &copy_src.view, &self.dummy.view, &next, &u);
436 cur_acc = next;
437 }
438 cur_acc
439 };
440
441 if need_post {
442 let out = self.alloc_tex_like(&base, base.depth, key);
443 let mut ud = UniformParams::default();
444 ud.p[0] = [
445 1.0,
446 blend,
447 if mask.is_some() { 1.0 } else { 0.0 },
448 if mask_inv { 1.0 } else { 0.0 },
449 ];
450 ud.p[1] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0];
451 ud.p[2] = [1.0 - skip[0], 1.0 - skip[1], 1.0 - skip[2], 1.0 - skip[3]];
452 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
453 self.dispatch_op(enc, ShaderOp::Dissolve, &base.view, &accum.view, mv, &out, &ud);
454 accum = out;
455 }
456
457 self.cache.insert(key, accum.clone(), node.id, frame_i);
458 accum
459 }
460
461 pub(in crate::eval) fn eval_kscope(
462 &mut self,
463 comp: &Comp,
464 node: &Node,
465 time: f64,
466 frame_i: i64,
467 enc: &mut wgpu::CommandEncoder,
468 visiting: &mut HashSet<(NodeId, i64)>,
469 stats: &mut EvalStats,
470 ) -> CachedTexture {
471 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
472 return self.dummy.clone();
473 };
474 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
475 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
476 if blend <= 1e-6 {
477 return src;
478 }
479 let src = self.crop_to_canvas(enc, src);
480 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
481 let slices = comp.eval_number(node, "Slices", time, 6.0, &self.expr).max(1.0) as f32;
482 let angle = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians();
483 let cap_angle = (comp.eval_number(node, "CaptureAngle", time, 0.0, &self.expr) as f32).to_radians();
484 let scale = comp.eval_number(node, "Scale", time, 1.0, &self.expr).max(1e-4) as f32;
485 let edges = comp.eval_number(node, "Edges", time, 3.0, &self.expr) as f32;
486 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
487 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
488
489 let mut u = UniformParams::default();
490 u.p[0] = [center[0] as f32, center[1] as f32, slices, angle];
491 u.p[1] = [cap_angle, scale, edges, blend];
492 u.p[2] = [if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0];
493
494 let key = self.make_key(node, "KScope", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3]));
495 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
496 stats.cache_hits += 1;
497 return hit;
498 }
499 stats.cache_misses += 1;
500 stats.nodes_evaluated += 1;
501 let dst = self.alloc_tex_like(&src, src.depth, key);
502 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
503 self.dispatch_op(enc, ShaderOp::KScope, &src.view, &self.dummy.view, mv, &dst, &u);
504 self.cache.insert(key, dst.clone(), node.id, frame_i);
505 dst
506 }
507}
508
509#[cfg(test)]
510mod tests {
511 use super::*;
512 use crate::Engine;
513
514 fn eval_px(comp: &Comp, eng: &mut Engine, name: &str, t: f64) -> (Vec<u8>, crate::cache::EvalStats) {
515 let (tex, stats) = eng.evaluate(comp, comp.find_node(name).unwrap(), t);
516 (eng.readback_rgba(&tex).unwrap(), stats)
517 }
518
519 #[test]
520 fn test_fuse_kscope_6_slice_symmetry() {
521 let src = r#"Composition {
522 CurrentTime = 0,
523 RenderRange = { 0, 1 },
524 GlobalRange = { 0, 1 },
525 Tools = ordered() {
526 BG1 = Background {
527 Inputs = {
528 Width = Input { Value = 128, },
529 Height = Input { Value = 128, },
530 Type = Input { Value = FuID { "Horizontal" }, },
531 TopLeftRed = Input { Value = 1.0, },
532 TopLeftGreen = Input { Value = 0.0, },
533 TopLeftBlue = Input { Value = 0.0, },
534 TopRightRed = Input { Value = 0.0, },
535 TopRightGreen = Input { Value = 0.0, },
536 TopRightBlue = Input { Value = 1.0, },
537 },
538 },
539 KS1 = Fuse.KScope {
540 Inputs = {
541 Input = Input { SourceOp = "BG1", Source = "Output", },
542 Slices = Input { Value = 6, },
543 Scale = Input { Value = 1.0, },
544 },
545 },
546 },
547 }"#;
548 let comp = Comp::from_fusion_str(src).expect("parse KScope comp");
549 let Ok(mut eng) = Engine::new_headless() else {
550 return;
551 };
552 let node_id = comp.find_node("KS1").expect("KS1");
553 let (tex, _) = eng.evaluate(&comp, node_id, 0.0);
554 let rgba = eng.readback_rgba(&tex).expect("readback KScope");
555 let [w, h] = tex.size;
556 assert_eq!((w, h), (128, 128));
557 // With Slices=6, sector=60 deg mirrored every 120 deg -> reflection across X axis is exact!
558 let px = |x: usize, y: usize| -> [u8; 4] {
559 let i = (y * 128 + x) * 4;
560 [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
561 };
562 let a = px(64 + 28, 64 + 12);
563 let b = px(64 + 28, 63 - 12);
564 for c in 0..3 {
565 let diff = (a[c] as i32 - b[c] as i32).abs();
566 assert!(diff <= 2, "KScope 6-slice mirror symmetry mismatch ch={c}: {a:?} vs {b:?}");
567 }
568 }
569
570 #[test]
571 fn identity_warps_still_multiply_by_mask_but_zero_blend_passes_through() {
572 // (tool, inputs, outside-mask pixel survives): Fusion Float/Int8 probes of MultiplyByMask + EffectMask.
573 let cases = [
574 ("Drip", "Amplitude = Input { Value = 0, },", false),
575 ("Dent", "Strength = Input { Value = 0, },", false),
576 ("Vortex", "Angle = Input { Value = 0, },", false),
577 ("Displace", "", false),
578 ("Drip", "Blend = Input { Value = 0, },", true),
579 ("Vortex", "Blend = Input { Value = 0, },", true),
580 ];
581 if Engine::new_headless().is_err() {
582 return;
583 }
584 for (kind, inputs, survives) in cases {
585 let src = format!(
586 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{
587 BG = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
588 TopLeftRed = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }},
589 Rect = RectangleMask {{ Inputs = {{ Width = Input {{ Value = 0.25, }}, Height = Input {{ Value = 0.25, }},
590 MaskWidth = Input {{ Value = 64, }}, MaskHeight = Input {{ Value = 64, }}, }}, }},
591 FX = {kind} {{ Inputs = {{ MultiplyByMask = Input {{ Value = 1, }}, {inputs}
592 Input = Input {{ SourceOp = "BG", Source = "Output", }},
593 EffectMask = Input {{ SourceOp = "Rect", Source = "Mask", }}, }}, }},
594 }} }}"#
595 );
596 let comp = Comp::from_fusion_str(&src).unwrap();
597 let mut eng = Engine::new_headless().unwrap();
598 let (tex, _) = eng.evaluate(&comp, comp.find_node("FX").unwrap(), 0.0);
599 let rgba = eng.readback_rgba(&tex).unwrap();
600 let px = |x: usize, y: usize| rgba[(y * 64 + x) * 4 + 3];
601 assert_eq!(px(2, 2), if survives { 255 } else { 0 }, "{kind} {inputs} outside the mask");
602 assert_eq!(px(32, 32), 255, "{kind} {inputs} inside the mask");
603 }
604 }
605
606 #[test]
607 fn displace_light_follows_the_diamond_angle_channel_and_ignores_negative_power() {
608 // Fusion 21.1 probes: light = LightPower * (map(p + v) - map(p - v)) with v on a diamond
609 // (0 deg -> (-1, 0), 180 deg -> (+1, 0), 90 deg -> (0, +1) down), added unclamped.
610 let lit = |inputs: &str| -> [u8; 4] {
611 let src = format!(
612 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{
613 Map = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
614 Type = Input {{ Value = FuID {{ "Horizontal" }}, }},
615 TopLeftRed = Input {{ Value = 0, }}, TopLeftGreen = Input {{ Value = 0, }}, TopLeftBlue = Input {{ Value = 0, }}, TopLeftAlpha = Input {{ Value = 1, }},
616 TopRightRed = Input {{ Value = 1, }}, TopRightGreen = Input {{ Value = 1, }}, TopRightBlue = Input {{ Value = 1, }}, TopRightAlpha = Input {{ Value = 1, }}, }}, }},
617 Flat = Background {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }},
618 TopLeftRed = Input {{ Value = 0.5, }}, TopLeftGreen = Input {{ Value = 0.5, }}, TopLeftBlue = Input {{ Value = 0.5, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }},
619 D = Displace {{ Inputs = {{ RefractionStrength = Input {{ Value = 0, }}, {inputs}
620 Input = Input {{ SourceOp = "Flat", Source = "Output", }},
621 Foreground = Input {{ SourceOp = "Map", Source = "Output", }}, }}, }},
622 }} }}"#
623 );
624 let comp = Comp::from_fusion_str(&src).unwrap();
625 let mut eng = Engine::new_headless().unwrap();
626 let (tex, _) = eng.evaluate(&comp, comp.find_node("D").unwrap(), 0.0);
627 let rgba = eng.readback_rgba(&tex).unwrap();
628 let i = (32 * 64 + 32) * 4;
629 [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
630 };
631 if Engine::new_headless().is_err() {
632 return;
633 }
634 let near = |got: u8, want: i32| assert!((got as i32 - want).abs() <= 1, "got {got}, want {want}");
635 // Ramp slope per tap pair is 2/63 of full scale = ~8 levels.
636 near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 0, },")[0], 128 - 8);
637 near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 180, },")[0], 128 + 8);
638 near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 90, },")[0], 128);
639 // Default angle is 135 deg: (+1, +1), so the horizontal ramp lights positively.
640 near(lit("LightPower = Input { Value = 1, },")[0], 128 + 8);
641 // LightChannel 4 lights every channel from alpha, which is flat.
642 near(lit("LightPower = Input { Value = 1, }, LightAngle = Input { Value = 180, }, LightChannel = Input { Value = 4, },")[0], 128);
643 near(lit("LightPower = Input { Value = -1, }, LightAngle = Input { Value = 180, },")[0], 128);
644 }
645
646 #[test]
647 fn vortex_dod_input_and_effect_mask_align_to_canvas() {
648 let src = r#"Composition {
649 CurrentTime = 0,
650 RenderRange = { 0, 0 },
651 GlobalRange = { 0, 0 },
652 Tools = ordered() {
653 Stripe = Background {
654 Inputs = {
655 Width = Input { Value = 64, },
656 Height = Input { Value = 64, },
657 Type = Input { Value = FuID { "Horizontal" }, },
658 TopLeftRed = Input { Value = 1.0, },
659 TopLeftAlpha = Input { Value = 1.0, },
660 TopRightBlue = Input { Value = 1.0, },
661 TopRightAlpha = Input { Value = 1.0, },
662 },
663 },
664 XF = DVE {
665 Inputs = {
666 Input = Input { SourceOp = "Stripe", Source = "Output", },
667 Center = Input { Value = { 0.25, 0.5 }, },
668 },
669 },
670 Mask = RectangleMask {
671 Inputs = {
672 MaskWidth = Input { Value = 64, },
673 MaskHeight = Input { Value = 64, },
674 Center = Input { Value = { 0.75, 0.5 }, },
675 Width = Input { Value = 0.25, },
676 Height = Input { Value = 1.0, },
677 },
678 },
679 V = Vortex {
680 Inputs = {
681 Input = Input { SourceOp = "XF", Source = "Output", },
682 EffectMask = Input { SourceOp = "Mask", Source = "Mask", },
683 Angle = Input { Value = 180.0, },
684 Size = Input { Value = 0.8, },
685 },
686 },
687 },
688 }"#;
689 let comp = Comp::from_fusion_str(src).expect("parse Vortex DoD comp");
690 let Ok(mut eng) = Engine::new_headless() else {
691 return;
692 };
693 let (v_tex, _) = eng.evaluate(&comp, comp.find_node("V").unwrap(), 0.0);
694 let (xf_tex, _) = eng.evaluate(&comp, comp.find_node("XF").unwrap(), 0.0);
695 let v_px = eng.readback_rgba(&v_tex).unwrap();
696 let xf_px = eng.readback_rgba(&xf_tex).unwrap();
697 // Left of Mask (x in 0..40) must be identical to XF (Vortex must not warp outside canvas mask).
698 for x in 0..40 {
699 let i = (32 * 64 + x) * 4;
700 assert_eq!(&v_px[i..i + 4], &xf_px[i..i + 4], "Vortex mask misaligned at x={x}");
701 }
702 }
703
704 #[test]
705 fn displace_light_with_full_spread_is_a_two_tap_pass() {
706 let src = |light: f64| format!(r#"Composition {{ Tools = ordered() {{
707 BG = Background {{ Inputs = {{ Width = Input {{ Value = 96, }}, Height = Input {{ Value = 96, }}, TopLeftRed = Input {{ Value = 0.5, }}, TopLeftGreen = Input {{ Value = 0.5, }}, TopLeftBlue = Input {{ Value = 0.5, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }},
708 Ramp = Background {{ Inputs = {{ Width = Input {{ Value = 96, }}, Height = Input {{ Value = 96, }}, Type = Input {{ Value = FuID {{ "Horizontal" }}, }},
709 TopLeftRed = Input {{ Value = 0, }}, TopLeftGreen = Input {{ Value = 0, }}, TopLeftBlue = Input {{ Value = 0, }}, TopLeftAlpha = Input {{ Value = 1, }},
710 TopRightRed = Input {{ Value = 1, }}, TopRightGreen = Input {{ Value = 1, }}, TopRightBlue = Input {{ Value = 1, }}, TopRightAlpha = Input {{ Value = 1, }}, }}, }},
711 D = Displace {{ Inputs = {{ Input = Input {{ SourceOp = "BG", Source = "Output", }}, Foreground = Input {{ SourceOp = "Ramp", Source = "Output", }},
712 LightPower = Input {{ Value = {light}, }}, Spread = Input {{ Value = 1, }}, RefractionStrength = Input {{ Value = 0, }}, }}, }},
713 }}, }}"#);
714 let Ok(mut eng) = Engine::new_headless() else { return };
715 let lit = Comp::from_fusion_str(&src(1.0)).expect("parse lit comp");
716 let flat = Comp::from_fusion_str(&src(0.0)).expect("parse flat comp");
717 let (lit_px, _) = eval_px(&lit, &mut eng, "D", 0.0);
718 let (flat_px, _) = eval_px(&flat, &mut eng, "D", 0.0);
719 assert!(lit_px.iter().zip(&flat_px).any(|(a, b)| a.abs_diff(*b) > 2), "slope lighting must change the image");
720 }
721
722 #[test]
723 fn vortex_clamp_edges_and_process_skip_with_mbm() {
724 let src = r#"Composition { Tools = ordered() {
725 BG = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, },
726 TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, },
727 M = RectangleMask { Inputs = { MaskWidth = Input { Value = 64, }, MaskHeight = Input { Value = 64, }, Width = Input { Value = 0.5, }, Height = Input { Value = 0.5, }, }, },
728 V = Vortex { Inputs = {
729 Input = Input { SourceOp = "BG", Source = "Output", },
730 Size = Input { Value = 2.0, },
731 EffectMask = Input { SourceOp = "M", Source = "Mask", },
732 MultiplyByMask = Input { Value = 1, },
733 ProcessRed = Input { Value = 0, },
734 }, },
735 } }"#;
736 let comp = Comp::from_fusion_str(src).expect("parse vortex comp");
737 let Ok(mut eng) = Engine::new_headless() else { return };
738 let (px, _) = eval_px(&comp, &mut eng, "V", 0.0);
739 // Outside mask must be zeroed even for ProcessRed=0; inside mask stays solid red.
740 assert_eq!(&px[0..4], &[0, 0, 0, 0]);
741 let center = (32 * 64 + 32) * 4;
742 assert_eq!(&px[center..center + 4], &[255, 0, 0, 255]);
743 }
744
745 #[test]
746 fn duplicate_luajit_prng_and_jitter_layers() {
747 let mut rng = LuaJitPrng::new(1.0);
748 let mut draws = [0.0f32; 12];
749 for d in &mut draws {
750 *d = 0.5 * (*d + rng.next_signed() + 1.0);
751 }
752 assert!((draws[7] - 0.838_582).abs() < 1e-4, "draw[7] mismatch: {}", draws[7]);
753 assert!((draws[10] - 0.562_473).abs() < 1e-4, "draw[10] mismatch: {}", draws[10]);
754 assert!((draws[11] - 0.932_789).abs() < 1e-4, "draw[11] mismatch: {}", draws[11]);
755
756 let src = r#"Composition { Tools = ordered() {
757 BG = Background { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, },
758 TopLeftRed = Input { Value = 0.5, }, TopLeftGreen = Input { Value = 0.5, }, TopLeftBlue = Input { Value = 0.5, }, TopLeftAlpha = Input { Value = 0.5, }, }, },
759 HalfCopy = Fuse.Duplicate { Inputs = { Background = Input { SourceOp = "BG", Source = "Output", }, Copies = Input { Value = 0.5, }, }, },
760 Jit = Fuse.Duplicate { Inputs = { Background = Input { SourceOp = "BG", Source = "Output", }, Copies = Input { Value = 2, }, RandomSeed = Input { Value = 1, }, JitterRedGain = Input { Value = 0.5, }, }, },
761 } }"#;
762 let comp = Comp::from_fusion_str(src).expect("parse duplicate comp");
763 let Ok(mut eng) = Engine::new_headless() else { return };
764 let half = eval_px(&comp, &mut eng, "HalfCopy", 0.0).0;
765 let c = (16 * 32 + 16) * 4;
766 assert!((half[c + 3] as i32 - 64).abs() <= 2, "Copies=0.5 scales alpha to ~64, got {}", half[c + 3]);
767 let jit = eval_px(&comp, &mut eng, "Jit", 0.0).0;
768 assert!(jit[c] > 220 && (jit[c] as i32 - jit[c + 1] as i32).abs() > 30, "JitterRedGain boosts R over G: {:?}", &jit[c..c + 4]);
769 }
770}
crates/engine/src/optflow.rs+55-46
......@@ -8,7 +8,19 @@ use std::collections::{HashMap, VecDeque};
88use std::collections::hash_map::DefaultHasher;
99use std::hash::{Hash, Hasher};
1010use std::num::NonZeroU64;
11use std::sync::{Mutex, RwLock};
11use std::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
12
13fn lock_or_recover<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
14 m.lock().unwrap_or_else(|e| e.into_inner())
15}
16
17fn read_or_recover<T>(rw: &RwLock<T>) -> RwLockReadGuard<'_, T> {
18 rw.read().unwrap_or_else(|e| e.into_inner())
19}
20
21fn write_or_recover<T>(rw: &RwLock<T>) -> RwLockWriteGuard<'_, T> {
22 rw.write().unwrap_or_else(|e| e.into_inner())
23}
1224
1325#[repr(C)]
1426#[derive(Clone, Copy, Pod, Zeroable)]
......@@ -706,28 +718,25 @@ impl OpticalFlowPipelines {
706718 /// Resets the dynamic uniform ring cursor back to slot `0`.
707719 /// Call only after all prior encoded passes on this pipeline have been submitted.
708720 pub fn reset_uniform_cursor(&self) {
709 self.uniform_ring.lock().unwrap().reset_cursor();
721 lock_or_recover(&self.uniform_ring).reset_cursor();
710722 }
711723
712724 /// Clears cached flow fields and pooled intermediate pyramid textures, and trims uniform ring chunks.
713725 pub fn clear_scratch(&self) {
714 self.flow_cache.lock().unwrap().clear();
715 self.pyramid_pool.lock().unwrap().clear();
716 self.uniform_ring.lock().unwrap().trim_uniform_chunks(2);
726 lock_or_recover(&self.flow_cache).clear();
727 lock_or_recover(&self.pyramid_pool).clear();
728 lock_or_recover(&self.uniform_ring).trim_uniform_chunks(2);
717729 }
718730
719731 /// Total resident GPU VRAM bytes currently held across pooled pyramid textures,
720732 /// cached flow-field textures, and dynamic uniform ring buffers.
721733 pub fn vram_bytes(&self) -> u64 {
722 let pool_bytes = self.pyramid_pool.lock().unwrap().total_bytes;
723 let flow_bytes: u64 = self
724 .flow_cache
725 .lock()
726 .unwrap()
734 let pool_bytes = lock_or_recover(&self.pyramid_pool).total_bytes;
735 let flow_bytes: u64 = lock_or_recover(&self.flow_cache)
727736 .iter()
728737 .map(|(_, _, _, size)| u64::from(size[0].max(1)) * u64::from(size[1].max(1)) * 8)
729738 .sum();
730 let ring_bytes = self.uniform_ring.lock().unwrap().vram_bytes();
739 let ring_bytes = lock_or_recover(&self.uniform_ring).vram_bytes();
731740 pool_bytes
732741 .saturating_add(flow_bytes)
733742 .saturating_add(ring_bytes)
......@@ -740,11 +749,11 @@ impl OpticalFlowPipelines {
740749 entry: &str,
741750 format: wgpu::TextureFormat,
742751 ) {
743 if cache.read().unwrap().contains_key(&format) {
752 if read_or_recover(cache).contains_key(&format) {
744753 return;
745754 }
746755 let pipe = create_fullscreen_pipeline(device, &self.shader, &self.pipeline_layout, entry, format);
747 cache.write().unwrap().insert(format, pipe);
756 write_or_recover(cache).insert(format, pipe);
748757 }
749758
750759 #[allow(clippy::too_many_arguments)]
......@@ -769,7 +778,7 @@ impl OpticalFlowPipelines {
769778 params,
770779 };
771780 let (ubuf, dynamic_offset) = {
772 let mut ring = self.uniform_ring.lock().unwrap();
781 let mut ring = lock_or_recover(&self.uniform_ring);
773782 ring.alloc_slot(device, queue, &uniform)
774783 };
775784
......@@ -842,7 +851,7 @@ impl OpticalFlowPipelines {
842851 let key = hash_interp(frame_a.content_hash, frame_b.content_hash, alpha, 1, target_format);
843852 let dst = alloc_output_texture(device, frame_a, target_format, key);
844853
845 let guard = self.blend_pipelines.read().unwrap();
854 let guard = read_or_recover(&self.blend_pipelines);
846855 let pipe = guard.get(&target_format).unwrap();
847856 self.run_pass(
848857 device,
......@@ -888,7 +897,7 @@ impl OpticalFlowPipelines {
888897 } else {
889898 let flow_key = (frame_a.content_hash, frame_b.content_hash, s0);
890899 let cached = {
891 let mut cache = self.flow_cache.lock().unwrap();
900 let mut cache = lock_or_recover(&self.flow_cache);
892901 cache.iter().position(|(k, _, _, _)| *k == flow_key).map(|i| {
893902 let entry = cache.remove(i);
894903 let view = entry.1.clone();
......@@ -902,7 +911,7 @@ impl OpticalFlowPipelines {
902911 // Evict the LRU flow field before computing the new one so its backing
903912 // texture can be immediately reused by PyramidScratchPool.
904913 let evicted_before = {
905 let mut cache = self.flow_cache.lock().unwrap();
914 let mut cache = lock_or_recover(&self.flow_cache);
906915 if cache.len() >= FLOW_CACHE_CAP {
907916 Some(cache.remove(0))
908917 } else {
......@@ -910,14 +919,14 @@ impl OpticalFlowPipelines {
910919 }
911920 };
912921 if let Some((_, old_view, old_tex, old_size)) = evicted_before {
913 self.pyramid_pool.lock().unwrap().release(old_tex, old_view, old_size);
922 lock_or_recover(&self.pyramid_pool).release(old_tex, old_view, old_size);
914923 }
915924
916925 let (flow1_tex, flow1_view) =
917926 self.compute_flow_field(device, queue, enc, frame_a, frame_b);
918927
919928 let evicted_after = {
920 let mut cache = self.flow_cache.lock().unwrap();
929 let mut cache = lock_or_recover(&self.flow_cache);
921930 let extra = if cache.len() >= FLOW_CACHE_CAP {
922931 Some(cache.remove(0))
923932 } else {
......@@ -927,7 +936,7 @@ impl OpticalFlowPipelines {
927936 extra
928937 };
929938 if let Some((_, old_view, old_tex, old_size)) = evicted_after {
930 self.pyramid_pool.lock().unwrap().release(old_tex, old_view, old_size);
939 lock_or_recover(&self.pyramid_pool).release(old_tex, old_view, old_size);
931940 }
932941 flow1_view
933942 }
......@@ -943,7 +952,7 @@ impl OpticalFlowPipelines {
943952 0.0,
944953 ];
945954 {
946 let guard = self.warp_pipelines.read().unwrap();
955 let guard = read_or_recover(&self.warp_pipelines);
947956 let pipe = guard.get(&target_format).unwrap();
948957 self.run_pass(
949958 device, queue, enc, pipe, "optflow-warp",
......@@ -951,7 +960,7 @@ impl OpticalFlowPipelines {
951960 );
952961 }
953962 if let Some(flow1_tex) = uncached_flow {
954 self.pyramid_pool.lock().unwrap().release(flow1_tex, flow1_view, s1);
963 lock_or_recover(&self.pyramid_pool).release(flow1_tex, flow1_view, s1);
955964 }
956965 dst
957966 }
......@@ -989,7 +998,7 @@ impl OpticalFlowPipelines {
989998 (flow1_raw_tex, flow1_raw_view),
990999 (flow1_tex, flow1_view),
9911000 ) = {
992 let mut pool = self.pyramid_pool.lock().unwrap();
1001 let mut pool = lock_or_recover(&self.pyramid_pool);
9931002 (
9941003 pool.acquire(device, s0, "optflow-fa0"),
9951004 pool.acquire(device, s0, "optflow-fb0"),
......@@ -1082,7 +1091,7 @@ impl OpticalFlowPipelines {
10821091 // are encoded in strict FIFO order on `enc`. Subsequent calls on the same or future
10831092 // encoders execute strictly after these passes.
10841093 {
1085 let mut pool = self.pyramid_pool.lock().unwrap();
1094 let mut pool = lock_or_recover(&self.pyramid_pool);
10861095 pool.release(fa0_tex, fa0_view, s0);
10871096 pool.release(fb0_tex, fb0_view, s0);
10881097 pool.release(fa1_tex, fa1_view, s1);
......@@ -1516,10 +1525,10 @@ mod tests {
15161525 };
15171526
15181527 let first = interp(&cached, &tex_a, &tex_b, 0.25);
1519 let field = cached.flow_cache.lock().unwrap()[0].1.clone();
1528 let field = lock_or_recover(&cached.flow_cache)[0].1.clone();
15201529 let second = interp(&cached, &tex_a, &tex_b, 0.75);
15211530 {
1522 let cache = cached.flow_cache.lock().unwrap();
1531 let cache = lock_or_recover(&cached.flow_cache);
15231532 assert_eq!(cache.len(), 1, "second alpha reuses the pair's flow field");
15241533 assert!(cache[0].1 == field, "second alpha must hit the cached field texture");
15251534 }
......@@ -1529,7 +1538,7 @@ mod tests {
15291538 for i in 2..8 {
15301539 interp(&cached, &frame(i, 10 + i as u64), &frame(i + 1, 20 + i as u64), 0.5);
15311540 }
1532 assert_eq!(cached.flow_cache.lock().unwrap().len(), FLOW_CACHE_CAP);
1541 assert_eq!(lock_or_recover(&cached.flow_cache).len(), FLOW_CACHE_CAP);
15331542 }
15341543
15351544 #[test]
......@@ -1602,9 +1611,9 @@ mod tests {
16021611 let (f_tex, f_view) =
16031612 pooled.compute_flow_field(&device, &queue, &mut enc, &frames[i], &frames[i + 1]);
16041613 queue.submit(Some(enc.finish()));
1605 pooled.pyramid_pool.lock().unwrap().release(f_tex, f_view, half_size([w, h]));
1614 lock_or_recover(&pooled.pyramid_pool).release(f_tex, f_view, half_size([w, h]));
16061615 assert_eq!(
1607 pooled.pyramid_pool.lock().unwrap().alloc_count,
1616 lock_or_recover(&pooled.pyramid_pool).alloc_count,
16081617 14,
16091618 "direct compute_flow_field alloc_count should remain 14 on pair {i}"
16101619 );
......@@ -1615,8 +1624,8 @@ mod tests {
16151624 // 1 per flow_cache slot up to FLOW_CACHE_CAP, then stays completely flat).
16161625 // - Output matches fresh unpooled OpticalFlowPipelines bit-for-bit.
16171626 pooled.clear_scratch();
1618 pooled.pyramid_pool.lock().unwrap().alloc_count = 0;
1619 pooled.pyramid_pool.lock().unwrap().reuse_count = 0;
1627 lock_or_recover(&pooled.pyramid_pool).alloc_count = 0;
1628 lock_or_recover(&pooled.pyramid_pool).reuse_count = 0;
16201629
16211630 let mut stable_allocs = 0u64;
16221631 for i in 0..8 {
......@@ -1633,7 +1642,7 @@ mod tests {
16331642 queue.submit(Some(enc.finish()));
16341643 let pooled_bytes = readback_bytes(&device, &queue, &out_pooled, 4);
16351644
1636 let allocs_now = pooled.pyramid_pool.lock().unwrap().alloc_count;
1645 let allocs_now = lock_or_recover(&pooled.pyramid_pool).alloc_count;
16371646 if i < FLOW_CACHE_CAP {
16381647 assert_eq!(allocs_now, 14 + i as u64);
16391648 stable_allocs = allocs_now;
......@@ -1665,7 +1674,7 @@ mod tests {
16651674 );
16661675 }
16671676 assert!(
1668 pooled.pyramid_pool.lock().unwrap().reuse_count >= 7 * 13,
1677 lock_or_recover(&pooled.pyramid_pool).reuse_count >= 7 * 13,
16691678 "expected substantial texture reuse across 8 distinct frame pairs"
16701679 );
16711680 }
......@@ -1676,7 +1685,7 @@ mod tests {
16761685 let pipelines = OpticalFlowPipelines::new(&device);
16771686
16781687 let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1);
1679 let stride = pipelines.uniform_ring.lock().unwrap().stride;
1688 let stride = lock_or_recover(&pipelines.uniform_ring).stride;
16801689 assert_eq!(stride % min_align, 0);
16811690
16821691 let (w, h) = (64u32, 64u32);
......@@ -1751,7 +1760,7 @@ mod tests {
17511760 queue.submit(Some(enc.finish()));
17521761
17531762 assert!(
1754 pipelines.uniform_ring.lock().unwrap().chunks.len() >= 2,
1763 lock_or_recover(&pipelines.uniform_ring).chunks.len() >= 2,
17551764 "expected > 256 passes to allocate at least 2 uniform chunks"
17561765 );
17571766
......@@ -1813,11 +1822,11 @@ mod tests {
18131822 let _out1 = pipelines.interpolate_flow(&device, &queue, &mut enc1, &a1, &b1, 0.5, fmt);
18141823 queue.submit(Some(enc1.finish()));
18151824 assert!(
1816 pipelines.flow_cache.lock().unwrap().is_empty(),
1825 lock_or_recover(&pipelines.flow_cache).is_empty(),
18171826 "content_hash == 0 must bypass flow_cache"
18181827 );
18191828 // All 14 textures (13 intermediate + temporary flow1) must be returned to pyramid_pool.
1820 assert_eq!(pipelines.pyramid_pool.lock().unwrap().entries.len(), 14);
1829 assert_eq!(lock_or_recover(&pipelines.pyramid_pool).entries.len(), 14);
18211830
18221831 // Pair 2: completely different box positions, also with content_hash == 0 (or one side 0).
18231832 let a2 = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 40, 12), 0);
......@@ -1825,7 +1834,7 @@ mod tests {
18251834 let mut enc2 = device.create_command_encoder(&Default::default());
18261835 let out2 = pipelines.interpolate_flow(&device, &queue, &mut enc2, &a2, &b2, 0.5, fmt);
18271836 queue.submit(Some(enc2.finish()));
1828 assert!(pipelines.flow_cache.lock().unwrap().is_empty());
1837 assert!(lock_or_recover(&pipelines.flow_cache).is_empty());
18291838
18301839 let fresh = OpticalFlowPipelines::new(&device);
18311840 let mut fresh_enc = device.create_command_encoder(&Default::default());
......@@ -1859,16 +1868,16 @@ mod tests {
18591868 );
18601869 queue.submit(Some(enc.finish()));
18611870
1862 let pool_bytes = pipelines.pyramid_pool.lock().unwrap().total_bytes;
1871 let pool_bytes = lock_or_recover(&pipelines.pyramid_pool).total_bytes;
18631872 let flow_bytes = u64::from(w / 2) * u64::from(h / 2) * 8;
1864 let ring_bytes = pipelines.uniform_ring.lock().unwrap().vram_bytes();
1873 let ring_bytes = lock_or_recover(&pipelines.uniform_ring).vram_bytes();
18651874 assert!(pool_bytes > 0);
18661875 assert!(ring_bytes > 0);
18671876 assert_eq!(pipelines.vram_bytes(), pool_bytes + flow_bytes + ring_bytes);
18681877
18691878 // Grow uniform ring beyond 2 chunks so clear_scratch() exercises trim_uniform_chunks(2).
18701879 {
1871 let mut ring = pipelines.uniform_ring.lock().unwrap();
1880 let mut ring = lock_or_recover(&pipelines.uniform_ring);
18721881 let dummy_u = OptFlowUniform {
18731882 dst_size: [1.0; 4],
18741883 params: [0.0; 4],
......@@ -1881,13 +1890,13 @@ mod tests {
18811890 assert!(pipelines.vram_bytes() > pool_bytes + flow_bytes + ring_bytes);
18821891
18831892 pipelines.clear_scratch();
1884 assert_eq!(pipelines.pyramid_pool.lock().unwrap().total_bytes, 0);
1885 assert!(pipelines.flow_cache.lock().unwrap().is_empty());
1886 assert_eq!(pipelines.uniform_ring.lock().unwrap().chunks.len(), 2);
1887 let retained_ring = pipelines.uniform_ring.lock().unwrap().vram_bytes();
1893 assert_eq!(lock_or_recover(&pipelines.pyramid_pool).total_bytes, 0);
1894 assert!(lock_or_recover(&pipelines.flow_cache).is_empty());
1895 assert_eq!(lock_or_recover(&pipelines.uniform_ring).chunks.len(), 2);
1896 let retained_ring = lock_or_recover(&pipelines.uniform_ring).vram_bytes();
18881897 assert_eq!(pipelines.vram_bytes(), retained_ring);
18891898
1890 pipelines.uniform_ring.lock().unwrap().trim_uniform_chunks(0);
1899 lock_or_recover(&pipelines.uniform_ring).trim_uniform_chunks(0);
18911900 assert_eq!(pipelines.vram_bytes(), 0);
18921901 }
18931902
crates/engine/src/scene3d/mod.rs+35-37
......@@ -20,7 +20,11 @@ pub use math::{
2020pub use shader::Vertex3D;
2121
2222use std::collections::HashMap;
23use std::sync::{Arc, Mutex};
23use std::sync::{Arc, Mutex, MutexGuard};
24
25fn lock_or_recover<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
26 m.lock().unwrap_or_else(|e| e.into_inner())
27}
2428
2529use crate::cache::CachedTexture;
2630use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges};
......@@ -72,7 +76,7 @@ fn cached_uniform_buffer(
7276 bytes.len().hash(&mut h);
7377 h.write(bytes);
7478 let key = (h.finish(), bytes.len());
75 cache.lock().unwrap().get_or_insert_with(key, || {
79 lock_or_recover(cache).get_or_insert_with(key, || {
7680 let size = (bytes.len() as u64).max(16);
7781 let buf = device.create_buffer(&wgpu::BufferDescriptor {
7882 label: Some(label),
......@@ -873,24 +877,22 @@ impl Scene3DRenderer {
873877 key: u64,
874878 build: impl FnOnce() -> Vec<Vertex3D>,
875879 ) -> Arc<Vec<Vertex3D>> {
876 if let Some(hit) = self.text3d_mesh_cache.lock().unwrap().get(key) {
880 if let Some(hit) = lock_or_recover(&self.text3d_mesh_cache).get(key) {
877881 return hit;
878882 }
879883 let built = Arc::new(build());
880 self.text3d_mesh_cache
881 .lock()
882 .unwrap()
884 lock_or_recover(&self.text3d_mesh_cache)
883885 .get_or_insert_with(key, || Arc::clone(&built))
884886 }
885887
886888 /// Drops cached shadow cube-map targets, main-pass depth targets, memoized `Text3D` CPU meshes,
887889 /// cached GPU mesh vertex/index buffers, and pooled uniform buffers.
888890 pub fn clear_shadow_targets(&self) {
889 *self.shadow_targets.lock().unwrap() = None;
890 self.depth_targets.lock().unwrap().clear();
891 self.text3d_mesh_cache.lock().unwrap().clear();
892 self.meshes.lock().unwrap().clear();
893 self.uniform_cache.lock().unwrap().clear();
891 *lock_or_recover(&self.shadow_targets) = None;
892 lock_or_recover(&self.depth_targets).clear();
893 lock_or_recover(&self.text3d_mesh_cache).clear();
894 lock_or_recover(&self.meshes).clear();
895 lock_or_recover(&self.uniform_cache).clear();
894896 }
895897
896898 /// Drops all pooled 3D render targets (`shadow_targets` and `depth_targets`) and `Text3D` CPU meshes.
......@@ -900,7 +902,7 @@ impl Scene3DRenderer {
900902
901903 /// Total GPU VRAM in bytes currently occupied by `shadow_targets` (R32Float layers + Depth32Float).
902904 pub fn shadow_vram_bytes(&self) -> u64 {
903 self.shadow_targets.lock().unwrap().as_ref().map_or(0, |t| {
905 lock_or_recover(&self.shadow_targets).as_ref().map_or(0, |t| {
904906 let layer_bytes = u64::from(SHADOW_MAP_SIZE) * u64::from(SHADOW_MAP_SIZE) * 4;
905907 layer_bytes * (u64::from(t.layers) + 1)
906908 })
......@@ -908,9 +910,7 @@ impl Scene3DRenderer {
908910
909911 /// Total GPU VRAM in bytes currently occupied by pooled main-pass `Depth32Float` targets.
910912 pub fn depth_vram_bytes(&self) -> u64 {
911 self.depth_targets
912 .lock()
913 .unwrap()
913 lock_or_recover(&self.depth_targets)
914914 .entries
915915 .values()
916916 .map(|(_, dt)| u64::from(dt.tex.width()) * u64::from(dt.tex.height()) * 4)
......@@ -919,9 +919,7 @@ impl Scene3DRenderer {
919919
920920 /// Total GPU VRAM in bytes currently occupied by cached vertex and index buffers.
921921 pub fn mesh_vram_bytes(&self) -> u64 {
922 self.meshes
923 .lock()
924 .unwrap()
922 lock_or_recover(&self.meshes)
925923 .entries
926924 .values()
927925 .filter_map(|(_, gm)| gm.as_ref())
......@@ -931,12 +929,12 @@ impl Scene3DRenderer {
931929
932930 /// Total GPU VRAM in bytes currently occupied by cached uniform buffers.
933931 pub fn uniform_vram_bytes(&self) -> u64 {
934 self.uniform_cache.lock().unwrap().total_bytes
932 lock_or_recover(&self.uniform_cache).total_bytes
935933 }
936934
937935 #[cfg(test)]
938936 pub(crate) fn gpu_mesh_count(&self) -> usize {
939 self.meshes.lock().unwrap().entries.len()
937 lock_or_recover(&self.meshes).entries.len()
940938 }
941939
942940 #[allow(clippy::too_many_arguments)]
......@@ -957,7 +955,7 @@ impl Scene3DRenderer {
957955 meshes: &[DrawMesh],
958956 ) {
959957 let depth_size = [dst.size[0].max(1), dst.size[1].max(1)];
960 let depth_target = self.depth_targets.lock().unwrap().get_or_insert_with(depth_size, || {
958 let depth_target = lock_or_recover(&self.depth_targets).get_or_insert_with(depth_size, || {
961959 let tex = device.create_texture(&wgpu::TextureDescriptor {
962960 label: Some("scene3d-depth"),
963961 size: wgpu::Extent3d {
......@@ -1012,7 +1010,7 @@ impl Scene3DRenderer {
10121010 let shadow_ubuf = shadow_ubuf_owned.as_ref().unwrap_or(&self.shadow_dummy_ubuf);
10131011 let shadow_targets = (!shadow_lights.is_empty()).then(|| {
10141012 let layers = 6 * shadow_lights.len() as u32;
1015 let mut cache = self.shadow_targets.lock().unwrap();
1013 let mut cache = lock_or_recover(&self.shadow_targets);
10161014 match cache.as_ref() {
10171015 Some(t) if t.layers >= layers => t.clone(),
10181016 _ => {
......@@ -1163,7 +1161,7 @@ impl Scene3DRenderer {
11631161 upload()
11641162 } else {
11651163 let key = mesh_key(base_shape, m.custom_mesh_key, aspect, fx.wireframe);
1166 self.meshes.lock().unwrap().get_or_insert_with(key, upload)
1164 lock_or_recover(&self.meshes).get_or_insert_with(key, upload)
11671165 };
11681166 let Some(GpuMesh { vbuf, ibuf, idx_count, .. }) = gpu_mesh else {
11691167 continue;
......@@ -1592,7 +1590,7 @@ mod tests {
15921590 let (vp, cam) = (mat4_identity(), [0.0, 0.0, 5.0]);
15931591 renderer.render_meshes(&device, &queue, &mut enc, &dst, &dummy, vp, vp, cam, 1000.0, SceneLights::default(), false, false, meshes);
15941592 queue.submit(Some(enc.finish()));
1595 renderer.meshes.lock().unwrap().entries.len()
1593 lock_or_recover(&renderer.meshes).entries.len()
15961594 };
15971595 assert_eq!(frame(&[sphere(0.0, false)]), 1);
15981596 assert_eq!(frame(&[sphere(0.5, false)]), 1, "a moved copy reuses the upload");
......@@ -1759,7 +1757,7 @@ mod tests {
17591757 assert_eq!(renderer.shadow_vram_bytes(), 0);
17601758
17611759 let _ = renderer.get_or_build_text3d_mesh(42, || vec![Vertex3D { pos: [0.0; 3], normal: [0.0, 0.0, 1.0], uv: [0.0; 2] }]);
1762 assert_eq!(renderer.text3d_mesh_cache.lock().unwrap().entries.len(), 1);
1760 assert_eq!(lock_or_recover(&renderer.text3d_mesh_cache).entries.len(), 1);
17631761
17641762 let tex = device.create_texture(&wgpu::TextureDescriptor {
17651763 label: None,
......@@ -1806,7 +1804,7 @@ mod tests {
18061804 renderer.clear_shadow_targets();
18071805 assert_eq!(renderer.shadow_vram_bytes(), 0);
18081806 assert_eq!(renderer.depth_vram_bytes(), 0);
1809 assert_eq!(renderer.text3d_mesh_cache.lock().unwrap().entries.len(), 0);
1807 assert_eq!(lock_or_recover(&renderer.text3d_mesh_cache).entries.len(), 0);
18101808 }
18111809
18121810 #[test]
......@@ -1855,19 +1853,19 @@ mod tests {
18551853 };
18561854
18571855 render_empty(&dst_a);
1858 assert_eq!(renderer.depth_targets.lock().unwrap().entries.len(), 1);
1856 assert_eq!(lock_or_recover(&renderer.depth_targets).entries.len(), 1);
18591857 assert_eq!(renderer.depth_vram_bytes(), 16 * 16 * 4);
18601858
18611859 render_empty(&dst_a);
1862 assert_eq!(renderer.depth_targets.lock().unwrap().entries.len(), 1);
1860 assert_eq!(lock_or_recover(&renderer.depth_targets).entries.len(), 1);
18631861 assert_eq!(renderer.depth_vram_bytes(), 16 * 16 * 4);
18641862
18651863 render_empty(&dst_b);
1866 assert_eq!(renderer.depth_targets.lock().unwrap().entries.len(), 2);
1864 assert_eq!(lock_or_recover(&renderer.depth_targets).entries.len(), 2);
18671865 assert_eq!(renderer.depth_vram_bytes(), (16 * 16 + 32 * 16) * 4);
18681866
18691867 renderer.clear_targets();
1870 assert_eq!(renderer.depth_targets.lock().unwrap().entries.len(), 0);
1868 assert_eq!(lock_or_recover(&renderer.depth_targets).entries.len(), 0);
18711869 assert_eq!(renderer.depth_vram_bytes(), 0);
18721870 }
18731871
......@@ -1942,25 +1940,25 @@ mod tests {
19421940 let vram_1 = renderer.mesh_vram_bytes();
19431941 assert_eq!(renderer.gpu_mesh_count(), 1);
19441942 assert!(vram_1 > 0);
1945 assert_eq!(renderer.uniform_cache.lock().unwrap().entries.len(), 1);
1943 assert_eq!(lock_or_recover(&renderer.uniform_cache).entries.len(), 1);
19461944
19471945 render_one(make_custom(0.0));
19481946 assert_eq!(renderer.gpu_mesh_count(), 1, "rebuilt identical Arc must hit content-keyed mesh cache");
19491947 assert_eq!(renderer.mesh_vram_bytes(), vram_1);
1950 assert_eq!(renderer.uniform_cache.lock().unwrap().entries.len(), 1, "identical uniform bytes reuse cached buffer");
1948 assert_eq!(lock_or_recover(&renderer.uniform_cache).entries.len(), 1, "identical uniform bytes reuse cached buffer");
19511949
19521950 // 2. Eviction stays strictly bounded by MAX_CACHED_MESH_BUFFERS (128).
19531951 for i in 1..=(MAX_CACHED_MESH_BUFFERS + 20) {
19541952 render_one(make_custom(i as f32 * 0.01));
19551953 }
19561954 assert_eq!(renderer.gpu_mesh_count(), MAX_CACHED_MESH_BUFFERS);
1957 assert!(renderer.uniform_cache.lock().unwrap().entries.len() <= UNIFORM_CACHE_CAP);
1955 assert!(lock_or_recover(&renderer.uniform_cache).entries.len() <= UNIFORM_CACHE_CAP);
19581956
19591957 // 3. clear_shadow_targets() (called by bust_gpu_cache) releases all cached GPU mesh and uniform buffers.
19601958 renderer.clear_shadow_targets();
19611959 assert_eq!(renderer.gpu_mesh_count(), 0);
19621960 assert_eq!(renderer.mesh_vram_bytes(), 0);
1963 assert_eq!(renderer.uniform_cache.lock().unwrap().entries.len(), 0);
1961 assert_eq!(lock_or_recover(&renderer.uniform_cache).entries.len(), 0);
19641962 }
19651963
19661964 #[test]
......@@ -2134,13 +2132,13 @@ mod tests {
21342132 assert!(single_uni_bytes > 0 && single_uni_bytes <= MAX_CACHED_UNIFORM_BYTES);
21352133
21362134 // Enforce tight byte caps (< 2 entries) and confirm LRU eviction caps both pools.
2137 renderer.meshes.lock().unwrap().max_bytes = single_mesh_bytes + single_mesh_bytes / 2;
2138 renderer.uniform_cache.lock().unwrap().max_bytes = single_uni_bytes + single_uni_bytes / 2;
2135 lock_or_recover(&renderer.meshes).max_bytes = single_mesh_bytes + single_mesh_bytes / 2;
2136 lock_or_recover(&renderer.uniform_cache).max_bytes = single_uni_bytes + single_uni_bytes / 2;
21392137
21402138 render_one(make_mesh(20, 1.0));
21412139 assert_eq!(renderer.gpu_mesh_count(), 1, "mesh byte cap must evict LRU mesh");
21422140 assert_eq!(renderer.mesh_vram_bytes(), single_mesh_bytes);
2143 assert_eq!(renderer.uniform_cache.lock().unwrap().entries.len(), 1, "uniform byte cap must evict LRU uniform");
2141 assert_eq!(lock_or_recover(&renderer.uniform_cache).entries.len(), 1, "uniform byte cap must evict LRU uniform");
21442142 assert_eq!(renderer.uniform_vram_bytes(), single_uni_bytes);
21452143
21462144 renderer.clear_shadow_targets();