authoravatarclover caruso<git@paperclover.net>2026-12-01 23:19:18-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 23:45:58-08:00
log5a3cb3e5d6dd4e95bdeb25236fe84dc2fcc13c06
treed1164168e3251ef65681c9e89728fe75b3df111d
parent4301134881311f5b9d2e1f0753e297645a7bb2ee
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

feat(engine): implement SurfaceTracker mesh warp, PlanarTracker/PlanarTransform, and live tracker API


8 files changed, 2056 insertions(+), 13 deletions(-)

compatibility.md+8-7
......@@ -2,18 +2,18 @@
22
33# Fusion 21.1 Compatibility
44
5Fission currently supports **127** tool types across 2D/3D compositing, all with high accuracy. This document tracks the progress on parity with Blackmagic Fusion Studio. The main metric, **accuracy**, is the inverse of the image's [mean absolute error](https://en.wikipedia.org/wiki/Mean_absolute_error), meaning `100%` accuracy means the pixels are all identical. For details, see [`scripts/fuzz_node.py`](scripts/fuzz_node.py).
5Fission currently supports **132** tool types across 2D/3D compositing, all with high accuracy. This document tracks the progress on parity with Blackmagic Fusion Studio. The main metric, **accuracy**, is the inverse of the image's [mean absolute error](https://en.wikipedia.org/wiki/Mean_absolute_error), meaning `100%` accuracy means the pixels are all identical. For details, see [`scripts/fuzz_node.py`](scripts/fuzz_node.py).
66
77## Summary
88
99| Metric | Value |
1010| --- | --- |
11| **Supported Tools** | **127** |
11| **Supported Tools** | **132** |
1212| **Modifiers & Animation** | **8** |
1313| **Accuracy across [paper clover](https://paperclover.net)'s compositions** | **99.5%** |
1414| **Supported Tool Accuracy** | **99.7%** |
15| **Supported Tools with 100% Accuracy** | **49** |
16| **Coverage of Fusion's Built-in Tools** | **28.3%** |
15| **Supported Tools with 100% Accuracy** | **51** |
16| **Coverage of Fusion's Built-in Tools** | **29.1%** |
1717| **Coverage of All Fuses on Reactor** | **0.6%** |
1818
1919## Generators
......@@ -105,6 +105,7 @@ Fission currently supports **127** tool types across 2D/3D compositing, all with
105105| `BetterResize` | 99.9% | — |
106106| `Crop` | ✅ 100.0% | — |
107107| `SetDomain` | 99.9% | — |
108| `Dimension.PlanarTransform` | ✅ 100.0% | Applies projective 3×3 `ToRef` homography splines (`Invert`, `Blend`, `EffectMask`). |
108109
109110## Masks
110111
......@@ -190,7 +191,9 @@ Each 3D tool's accuracy is measured by rendering it inside a lit `Merge3D` + `Ca
190191| `Fuse.SwitchElse` | ✅ 100.0% | — |
191192| `PipeRouter` | ✅ 100.0% | — |
192193| `Fuse.Wireless` | ✅ 100.0% | — |
193| `Tracker` | ✅ 100.0% | Live optical tracking not implemented; evaluates baked `TrackerModifier` paths. |
194| `Tracker` | ✅ 100.0% | Evaluates baked `TrackerModifier` paths; live NCC point & planar homography API in `engine::tracker`. |
195| `SurfaceTracker` | 99.5%–99.9% | GPU 2D triangle-mesh warp (`FuTriMesh` + `WarpableCanvas`); live NCC & homography API in `engine::tracker`. |
196| `Dimension.PlanarTracker` | ✅ 100.0% | Evaluates `Track` / `CornerPin` / `Steady` / `Stabilize` modes from baked `Matrix` tracks. |
194197| `MacroOperator` | ✅ 100.0% | Internal subgraph is read-only in interactive Flow. |
195198| `GroupOperator` | ✅ 100.0% | Internal subgraph is read-only in interactive Flow. |
196199| `Custom` | 98.2% | — |
......@@ -216,9 +219,7 @@ Unlike Blackmagic Fusion — which unlinks missing OFX or Resolve-only plugins w
216219
217220| Tool Class | Issue | Notes |
218221| --- | --- | --- |
219| `SurfaceTracker` | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. |
220222| `MagicMask` | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. |
221| `PlanarTracker` | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. |
222223
223224---
224225
crates/app/src/add_tool.rs+3
......@@ -186,6 +186,9 @@ pub const TOOL_CATALOG: &[ToolEntry] = &[
186186 ToolEntry { kind: "ChangeDepth", display: "Change Depth", aliases: "cd bit depth float", category: ToolCategory::Utility, is_generator: false },
187187 ToolEntry { kind: "SetDomain", display: "Set Domain", aliases: "dod roi", category: ToolCategory::Utility, is_generator: false },
188188 ToolEntry { kind: "Tracker", display: "Tracker", aliases: "tr matchmove", category: ToolCategory::Utility, is_generator: false },
189 ToolEntry { kind: "SurfaceTracker", display: "Surface Tracker", aliases: "st mesh warp surface matchmove", category: ToolCategory::Utility, is_generator: false },
190 ToolEntry { kind: "Dimension.PlanarTracker", display: "Planar Tracker", aliases: "pt planar track cornerpin steady stabilize", category: ToolCategory::Utility, is_generator: false },
191 ToolEntry { kind: "Dimension.PlanarTransform", display: "Planar Transform", aliases: "pxf planar homography warp matchmove", category: ToolCategory::TransformWarp, is_generator: false },
189192 ToolEntry { kind: "Note", display: "Sticky Note", aliases: "comment note", category: ToolCategory::Utility, is_generator: true },
190193 ToolEntry { kind: "Underlay", display: "Underlay", aliases: "backdrop group", category: ToolCategory::Utility, is_generator: true },
191194 ToolEntry { kind: "Custom", display: "Custom Tool", aliases: "ct shader expression", category: ToolCategory::Utility, is_generator: false },
crates/engine/src/eval/mod.rs+528-1
......@@ -73,6 +73,7 @@ pub struct Engine {
7373 supports_f32_filter: bool,
7474 scene3d: crate::scene3d::Scene3DRenderer,
7575 optflow: std::sync::OnceLock<crate::optflow::OpticalFlowPipelines>,
76 tracker: std::sync::OnceLock<crate::tracker::TrackerPipelines>,
7677 particles: crate::particles::ParticleCache,
7778 custom_shaders: crate::custom_shader::CustomShaderCache,
7879 sprite_cache: HashMap<(NodeId, u64, i64), (crate::particles::SpriteImage, u64)>,
......@@ -176,6 +177,7 @@ impl Engine {
176177 supports_f32_filter,
177178 scene3d,
178179 optflow: std::sync::OnceLock::new(),
180 tracker: std::sync::OnceLock::new(),
179181 particles: crate::particles::ParticleCache::default(),
180182 custom_shaders: crate::custom_shader::CustomShaderCache::new(),
181183 sprite_cache: HashMap::new(),
......@@ -826,7 +828,49 @@ impl Engine {
826828 "DirectionalBlur" => self.eval_dir_blur(comp, node, time, frame_i, enc, visiting, stats),
827829 "Glow" | "SoftGlow" => self.eval_glow(comp, node, time, frame_i, enc, visiting, stats),
828830 "Fuse.XGlow" => self.eval_xglow(comp, node, time, frame_i, enc, visiting, stats),
829 "ErodeDilate" => self.eval_erode_dilate(comp, node, time, frame_i, enc, visiting, stats),
831 "ErodeDilate" => {
832 let mut out = self.eval_erode_dilate(comp, node, time, frame_i, enc, visiting, stats);
833 if self.multiplies_by_mask(comp, node, time) {
834 let (mask, mask_inv) = self.eval_mask_input_sized(
835 comp,
836 node,
837 time,
838 Some(out.canvas_size),
839 enc,
840 visiting,
841 stats,
842 );
843 if let Some(m) = mask {
844 let out_c = self.crop_to_canvas(enc, out);
845 let key = self.make_key(
846 node,
847 "ErodeDilateMBM",
848 out_c.size,
849 &[out_c.content_hash, m.content_hash],
850 &[if mask_inv { 1.0 } else { 0.0 }],
851 );
852 out = if let Some(hit) = self.cache.get(key, node.id, frame_i) {
853 hit
854 } else {
855 let dst = self.alloc_tex(out_c.size, out_c.depth, key);
856 let mut u = UniformParams::default();
857 u.p[0][0] = if mask_inv { 1.0 } else { 0.0 };
858 self.dispatch_op(
859 enc,
860 ShaderOp::MaskApply,
861 &out_c.view,
862 &self.dummy.view,
863 &m.view,
864 &dst,
865 &u,
866 );
867 self.cache.insert(key, dst.clone(), node.id, frame_i);
868 dst
869 };
870 }
871 }
872 out
873 }
830874 "FastNoise" => self.eval_fast_noise(comp, node, time, frame_i, comp_dims, enc, stats),
831875 "Plasma" => self.eval_plasma(comp, node, time, frame_i, comp_dims, enc, visiting, stats),
832876 "DaySky" => self.eval_day_sky(comp, node, time, frame_i, comp_dims, enc, visiting, stats),
......@@ -877,6 +921,13 @@ impl Engine {
877921 | "pBounce" => self.dummy.clone(),
878922 "Custom" if node.connected_node("Image1").and_then(|s| comp.find_node(s)).is_none() => self.dummy.clone(),
879923 "Custom" => self.eval_custom(comp, node, time, frame_i, comp_dims, enc, visiting, stats),
924 "SurfaceTracker" => self.eval_surface_tracker(comp, node, time, frame_i, enc, visiting, stats),
925 "Dimension.PlanarTransform" | "PlanarTransform" => {
926 self.eval_planar_transform(comp, node, time, frame_i, enc, visiting, stats)
927 }
928 "Dimension.PlanarTracker" | "PlanarTracker" => {
929 self.eval_planar_tracker(comp, node, time, frame_i, enc, visiting, stats)
930 }
880931 "Renderer3D" => self.eval_renderer3d(comp, node, time, frame_i, comp_dims, enc, visiting, stats),
881932 other => {
882933 // Graceful passthrough for preserved/unknown image nodes (e.g. SurfaceTracker, MagicMask,
......@@ -1041,6 +1092,482 @@ impl Engine {
10411092 self.eval_node(comp, src_id, remapped, enc, visiting, stats)
10421093 }
10431094
1095 fn parse_surface_apply_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> f32 {
1096 let mode_str = node
1097 .static_str("OverlayCompositeMode")
1098 .or_else(|| node.static_str("CompositeMode"))
1099 .or_else(|| node.static_str("ApplyMode"));
1100 if let Some(s) = mode_str {
1101 return match s {
1102 "Screen" => 1.0,
1103 "Multiply" => 2.0,
1104 "Overlay" => 3.0,
1105 "SoftLight" | "Soft Light" => 4.0,
1106 "HardLight" | "Hard Light" => 5.0,
1107 "ColorDodge" | "Color Dodge" => 6.0,
1108 "Darken" => 7.0,
1109 "Lighten" => 8.0,
1110 "Difference" => 9.0,
1111 "Exclusion" => 10.0,
1112 "Add" | "LinearDodge" | "Linear Dodge" => 11.0,
1113 _ => 0.0,
1114 };
1115 }
1116 let n = comp
1117 .eval_number(node, "OverlayCompositeMode", time, 0.0, expr)
1118 .round() as i32;
1119 match n {
1120 1 => 1.0,
1121 2 => 2.0,
1122 3 => 3.0,
1123 4 => 4.0,
1124 5 => 5.0,
1125 _ => 0.0,
1126 }
1127 }
1128
1129 #[allow(clippy::too_many_arguments)]
1130 fn eval_surface_tracker(
1131 &mut self,
1132 comp: &Comp,
1133 node: &Node,
1134 time: f64,
1135 frame_i: i64,
1136 enc: &mut wgpu::CommandEncoder,
1137 visiting: &mut HashSet<(NodeId, i64)>,
1138 stats: &mut EvalStats,
1139 ) -> CachedTexture {
1140 let Some(bg_id) = node
1141 .connected_node("Input")
1142 .or_else(|| node.connected_node("Background"))
1143 .and_then(|s| comp.find_node(s))
1144 else {
1145 return self.dummy.clone();
1146 };
1147 let bg = self.eval_node(comp, bg_id, time, enc, visiting, stats);
1148
1149 let stage = comp
1150 .eval_number(node, "ProcessStage", time, 2.0, &self.expr)
1151 .round() as i32;
1152 if stage < 2 {
1153 return bg;
1154 }
1155
1156 let Some(overlay_id) = node
1157 .connected_node("Overlay")
1158 .or_else(|| node.connected_node("Foreground"))
1159 .and_then(|s| comp.find_node(s))
1160 else {
1161 return bg;
1162 };
1163
1164 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1165 let opacity = comp.eval_number(node, "OverlayOpacity", time, 1.0, &self.expr) as f32;
1166 let eff_blend = (blend * opacity).clamp(0.0, 1.0);
1167 if eff_blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) {
1168 return bg;
1169 }
1170
1171 let explicit_ref = node
1172 .inputs
1173 .contains_key("ReferenceFrame")
1174 .then(|| comp.eval_number(node, "ReferenceFrame", time, 0.0, &self.expr));
1175 let Some((ref_mesh, cur_mesh, ref_frame)) =
1176 crate::tracker::eval_surface_mesh(comp, node, time, explicit_ref)
1177 else {
1178 return bg;
1179 };
1180
1181 let overlay_time = match node.static_str("OverlaySource") {
1182 Some("OverlayFrameRef" | "OverlayFrameReference") => ref_frame,
1183 Some("OverlayFrameCurrent" | "OverlayFrameFirst") => time,
1184 _ => time,
1185 };
1186 let overlay = self.eval_node(comp, overlay_id, overlay_time, enc, visiting, stats);
1187 let bg = self.crop_to_canvas(enc, bg);
1188 let overlay = self.crop_to_canvas(enc, overlay);
1189
1190 let placement = comp
1191 .eval_number(node, "OverlayPlacement", time, 1.0, &self.expr)
1192 .round() as i32;
1193 let corners = if placement == 0 {
1194 crate::tracker::extract_warpable_canvas_corners(node)
1195 .unwrap_or([[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]])
1196 } else {
1197 crate::tracker::extract_warpable_canvas_corners(node)
1198 .unwrap_or([[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]])
1199 };
1200 let h_inv = crate::tracker::quad_to_unit_homography(
1201 corners[0],
1202 corners[1],
1203 corners[2],
1204 corners[3],
1205 );
1206
1207 let photo_strength = if node.inputs.contains_key("LightingWeight") {
1208 comp.eval_number(node, "LightingWeight", time, 0.0, &self.expr) as f32
1209 } else if node.inputs.contains_key("MatchLighting") {
1210 comp.eval_number(node, "MatchLighting", time, 0.0, &self.expr) as f32
1211 } else {
1212 0.0
1213 }
1214 .clamp(0.0, 1.0);
1215
1216 let apply_mode = Self::parse_surface_apply_mode(comp, node, time, &self.expr);
1217 let (mask, mask_inv) =
1218 self.eval_mask_input_sized(comp, node, time, Some(bg.size), enc, visiting, stats);
1219 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1220 let mbm = mask.is_some()
1221 && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
1222 let dst_depth = self.node_depth(comp, node, time, Some(bg.depth.max(overlay.depth)));
1223
1224 let ref_hash = ref_mesh.content_hash();
1225 let cur_hash = cur_mesh.content_hash();
1226 let params_f32: [f32; 14] = [
1227 h_inv[0] as f32,
1228 h_inv[1] as f32,
1229 h_inv[2] as f32,
1230 h_inv[3] as f32,
1231 h_inv[4] as f32,
1232 h_inv[5] as f32,
1233 h_inv[6] as f32,
1234 h_inv[7] as f32,
1235 h_inv[8] as f32,
1236 eff_blend,
1237 apply_mode,
1238 photo_strength,
1239 if mask_inv { 1.0 } else { 0.0 },
1240 if mbm { 1.0 } else { 0.0 },
1241 ];
1242 let key = self.make_key(
1243 node,
1244 "SurfaceTracker",
1245 bg.size,
1246 &[bg.content_hash, overlay.content_hash, mask_hash, ref_hash, cur_hash],
1247 &params_f32,
1248 );
1249 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1250 stats.cache_hits += 1;
1251 return hit;
1252 }
1253 stats.cache_misses += 1;
1254 stats.nodes_evaluated += 1;
1255
1256 // WebGPU safety: render mesh exclusively into Rgba8Unorm or Rgba16Float (never Rgba32Float).
1257 let render_depth = match self.effective_depth(dst_depth) {
1258 BitDepth::Int8 => BitDepth::Int8,
1259 _ => BitDepth::Float16,
1260 };
1261 let warped = self.alloc_tex(bg.size, render_depth, key ^ 0x57A1_7EAC);
1262 let tracker = self
1263 .tracker
1264 .get_or_init(|| crate::tracker::TrackerPipelines::new(&self.device));
1265 tracker.render_surface_mesh(
1266 &self.device,
1267 enc,
1268 &overlay.view,
1269 &warped.view,
1270 warped.format,
1271 &ref_mesh,
1272 &cur_mesh,
1273 h_inv,
1274 photo_strength,
1275 );
1276
1277 let dst = self.alloc_tex(bg.size, dst_depth, key);
1278 let mut u = UniformParams::default();
1279 u.p[0] = [0.5, 0.5, 1.0, 0.0];
1280 u.p[1] = [eff_blend, 1.0, apply_mode, 0.0];
1281 u.p[2] = [0.0, 0.0, 0.0, 0.0];
1282 u.p[3] = [
1283 if mask.is_some() { 1.0 } else { 0.0 },
1284 if mask_inv { 1.0 } else { 0.0 },
1285 bg.size[0] as f32,
1286 bg.size[1] as f32,
1287 ];
1288 u.p[6] = [0.0, 1.0, 0.0, 0.0];
1289 u.p[7] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0];
1290 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1291 self.dispatch_op(enc, ShaderOp::Merge, &bg.view, &warped.view, mv, &dst, &u);
1292 self.cache.insert(key, dst.clone(), node.id, frame_i);
1293 dst
1294 }
1295
1296 #[allow(clippy::too_many_arguments)]
1297 fn dispatch_planar_homography(
1298 &mut self,
1299 comp: &Comp,
1300 node: &Node,
1301 tag: &str,
1302 src: &CachedTexture,
1303 dst_size: [u32; 2],
1304 dst_depth: BitDepth,
1305 h_inv: [f64; 9],
1306 blend: f32,
1307 mask: Option<&CachedTexture>,
1308 mask_inv: bool,
1309 mbm: bool,
1310 time: f64,
1311 frame_i: i64,
1312 enc: &mut wgpu::CommandEncoder,
1313 stats: &mut EvalStats,
1314 ) -> CachedTexture {
1315 let mask_hash = mask.map_or(0, |m| m.content_hash);
1316 let mut u = UniformParams::default();
1317 u.p[0] = [h_inv[0] as f32, h_inv[1] as f32, h_inv[2] as f32, h_inv[3] as f32];
1318 u.p[1] = [h_inv[4] as f32, h_inv[5] as f32, h_inv[6] as f32, h_inv[7] as f32];
1319 u.p[2] = [
1320 h_inv[8] as f32,
1321 blend,
1322 if mask.is_some() { 1.0 } else { 0.0 },
1323 if mask_inv { 1.0 } else { 0.0 },
1324 ];
1325 u.p[3][1] = if mbm { 1.0 } else { 0.0 };
1326 if src.size != dst_size {
1327 u.p[4] = [0.0, 0.0, dst_size[0] as f32, dst_size[1] as f32];
1328 }
1329 u.p[5] = self.process_skip(comp, node, time);
1330 let key = self.make_key(
1331 node,
1332 tag,
1333 dst_size,
1334 &[src.content_hash, mask_hash],
1335 bytemuck::cast_slice(&u.p[..6]),
1336 );
1337 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1338 stats.cache_hits += 1;
1339 return hit;
1340 }
1341 stats.cache_misses += 1;
1342 stats.nodes_evaluated += 1;
1343 let dst = self.alloc_tex(dst_size, dst_depth, key);
1344 let mv = mask.map_or(&self.dummy.view, |m| &m.view);
1345 self.dispatch_op(enc, ShaderOp::Homography, &src.view, &self.dummy.view, mv, &dst, &u);
1346 self.cache.insert(key, dst.clone(), node.id, frame_i);
1347 dst
1348 }
1349
1350 #[allow(clippy::too_many_arguments)]
1351 fn eval_planar_transform(
1352 &mut self,
1353 comp: &Comp,
1354 node: &Node,
1355 time: f64,
1356 frame_i: i64,
1357 enc: &mut wgpu::CommandEncoder,
1358 visiting: &mut HashSet<(NodeId, i64)>,
1359 stats: &mut EvalStats,
1360 ) -> CachedTexture {
1361 let Some(src_id) = node
1362 .connected_node("Input")
1363 .or_else(|| node.connected_node("Background"))
1364 .and_then(|s| comp.find_node(s))
1365 else {
1366 return self.dummy.clone();
1367 };
1368 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1369 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1370 if blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) {
1371 return src;
1372 }
1373 let Some(track) = crate::tracker::eval_planar_track(comp, node, "Track", time) else {
1374 return src;
1375 };
1376 let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) >= 0.5;
1377 let h_inv = if invert {
1378 crate::tracker::mat3_invert(&track.to_ref_3x3).unwrap_or(track.to_ref_3x3)
1379 } else {
1380 track.to_ref_3x3
1381 };
1382 let src = self.crop_to_canvas(enc, src);
1383 let (mask, mask_inv) =
1384 self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1385 let mbm = mask.is_some()
1386 && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
1387 let dst_depth = self.node_depth(comp, node, time, Some(src.depth));
1388 self.dispatch_planar_homography(
1389 comp,
1390 node,
1391 "PlanarTransform",
1392 &src,
1393 src.size,
1394 dst_depth,
1395 h_inv,
1396 blend,
1397 mask.as_ref(),
1398 mask_inv,
1399 mbm,
1400 time,
1401 frame_i,
1402 enc,
1403 stats,
1404 )
1405 }
1406
1407 #[allow(clippy::too_many_arguments)]
1408 fn eval_planar_tracker(
1409 &mut self,
1410 comp: &Comp,
1411 node: &Node,
1412 time: f64,
1413 frame_i: i64,
1414 enc: &mut wgpu::CommandEncoder,
1415 visiting: &mut HashSet<(NodeId, i64)>,
1416 stats: &mut EvalStats,
1417 ) -> CachedTexture {
1418 let Some(bg_id) = node
1419 .connected_node("Background")
1420 .or_else(|| node.connected_node("Input"))
1421 .and_then(|s| comp.find_node(s))
1422 else {
1423 return self.dummy.clone();
1424 };
1425 let bg = self.eval_node(comp, bg_id, time, enc, visiting, stats);
1426
1427 // OperationMode: "Track"/0 = passthrough, "CornerPin"/1, "Steady"/2, "Stabilize"/3.
1428 let op_mode = match node.static_str("OperationMode") {
1429 Some("CornerPin") => 1,
1430 Some("Steady") => 2,
1431 Some("Stabilize") => 3,
1432 Some(_) => 0,
1433 None => comp
1434 .eval_number(node, "OperationMode", time, 0.0, &self.expr)
1435 .round() as i32,
1436 };
1437 if op_mode == 0 {
1438 return bg;
1439 }
1440
1441 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1442 if blend <= 1e-6 && !self.multiplies_by_mask(comp, node, time) {
1443 return bg;
1444 }
1445
1446 if op_mode == 2 || op_mode == 3 {
1447 // Steady (2) warps Background by inv(ToRef) to lock the plane to RefTime.
1448 // Stabilize (3) uses StableTrack if valid, falling back to inv(Track.ToRef).
1449 let mat = if op_mode == 3 {
1450 crate::tracker::eval_planar_track(comp, node, "StableTrack", time)
1451 .or_else(|| crate::tracker::eval_planar_track(comp, node, "Track", time))
1452 } else {
1453 crate::tracker::eval_planar_track(comp, node, "Track", time)
1454 };
1455 let Some(track) = mat else {
1456 return bg;
1457 };
1458 let Some(h_inv) = crate::tracker::mat3_invert(&track.to_ref_3x3) else {
1459 return bg;
1460 };
1461 let bg = self.crop_to_canvas(enc, bg);
1462 let (mask, mask_inv) =
1463 self.eval_mask_input_sized(comp, node, time, Some(bg.size), enc, visiting, stats);
1464 let mbm = mask.is_some()
1465 && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
1466 let dst_depth = self.node_depth(comp, node, time, Some(bg.depth));
1467 let tag = if op_mode == 3 { "PlanarStabilize" } else { "PlanarSteady" };
1468 return self.dispatch_planar_homography(
1469 comp,
1470 node,
1471 tag,
1472 &bg,
1473 bg.size,
1474 dst_depth,
1475 h_inv,
1476 blend,
1477 mask.as_ref(),
1478 mask_inv,
1479 mbm,
1480 time,
1481 frame_i,
1482 enc,
1483 stats,
1484 );
1485 }
1486
1487 // CornerPin (1): warp CornerPin1 / Foreground via CornerPin quad + ToRef over Background.
1488 let Some(fg_id) = node
1489 .connected_node("CornerPin1")
1490 .or_else(|| node.connected_node("Foreground"))
1491 .or_else(|| node.connected_node("CornerPin"))
1492 .and_then(|s| comp.find_node(s))
1493 else {
1494 return bg;
1495 };
1496 let fg = self.eval_node(comp, fg_id, time, enc, visiting, stats);
1497 let bg = self.crop_to_canvas(enc, bg);
1498 let fg = self.crop_to_canvas(enc, fg);
1499
1500 let read_corner = |primary: &str, alt: &str, default: [f64; 2]| -> [f64; 2] {
1501 if node.inputs.contains_key(primary) {
1502 comp.eval_point(node, primary, time, default, &self.expr)
1503 } else {
1504 comp.eval_point(node, alt, time, default, &self.expr)
1505 }
1506 };
1507 let bl = read_corner("CornerPinBottomLeft", "BottomLeft", [0.0, 0.0]);
1508 let br = read_corner("CornerPinBottomRight", "BottomRight", [1.0, 0.0]);
1509 let tr = read_corner("CornerPinTopRight", "TopRight", [1.0, 1.0]);
1510 let tl = read_corner("CornerPinTopLeft", "TopLeft", [0.0, 1.0]);
1511 let h_pin_inv = crate::tracker::quad_to_unit_homography(tl, tr, br, bl);
1512 let h_to_ref = crate::tracker::eval_planar_track(comp, node, "Track", time)
1513 .map_or([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], |m| m.to_ref_3x3);
1514 let h_combined = crate::tracker::mat3_mul(&h_pin_inv, &h_to_ref);
1515
1516 let dst_depth = self.node_depth(comp, node, time, Some(bg.depth.max(fg.depth)));
1517 let warped_fg = self.dispatch_planar_homography(
1518 comp,
1519 node,
1520 "PlanarCornerPinWarp",
1521 &fg,
1522 bg.size,
1523 dst_depth,
1524 h_combined,
1525 1.0,
1526 None,
1527 false,
1528 false,
1529 time,
1530 frame_i,
1531 enc,
1532 stats,
1533 );
1534
1535 let (mask, mask_inv) =
1536 self.eval_mask_input_sized(comp, node, time, Some(bg.size), enc, visiting, stats);
1537 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1538 let mbm = mask.is_some()
1539 && comp.eval_number(node, "MultiplyByMask", time, 0.0, &self.expr) > 0.5;
1540 let key = self.make_key(
1541 node,
1542 "PlanarCornerPinComp",
1543 bg.size,
1544 &[bg.content_hash, warped_fg.content_hash, mask_hash],
1545 &[blend, if mask_inv { 1.0 } else { 0.0 }, if mbm { 1.0 } else { 0.0 }],
1546 );
1547 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1548 stats.cache_hits += 1;
1549 return hit;
1550 }
1551 stats.cache_misses += 1;
1552 let dst = self.alloc_tex(bg.size, dst_depth, key);
1553 let mut u = UniformParams::default();
1554 u.p[0] = [0.5, 0.5, 1.0, 0.0];
1555 u.p[1] = [blend, 1.0, 0.0, 0.0];
1556 u.p[2] = [0.0, 0.0, 0.0, 0.0];
1557 u.p[3] = [
1558 if mask.is_some() { 1.0 } else { 0.0 },
1559 if mask_inv { 1.0 } else { 0.0 },
1560 bg.size[0] as f32,
1561 bg.size[1] as f32,
1562 ];
1563 u.p[6] = [0.0, 1.0, 0.0, 0.0];
1564 u.p[7] = [if mbm { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0];
1565 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1566 self.dispatch_op(enc, ShaderOp::Merge, &bg.view, &warped_fg.view, mv, &dst, &u);
1567 self.cache.insert(key, dst.clone(), node.id, frame_i);
1568 dst
1569 }
1570
10441571 fn make_key(&self, node: &Node, tag: &str, size: [u32; 2], upstream: &[u64], params: &[f32]) -> u64 {
10451572 let mut h = DefaultHasher::new();
10461573 self.cache.gpu_salt.hash(&mut h);
crates/engine/src/lib.rs+1
......@@ -14,6 +14,7 @@ pub mod profile;
1414pub mod ram_cache;
1515pub mod scene3d;
1616pub mod text_engine;
17pub mod tracker;
1718
1819#[cfg(not(target_arch = "wasm32"))]
1920pub use audio::{AudioPlayer, AudioTrack};
crates/engine/src/shaders/tracker_mesh.wgsl created+72
......@@ -0,0 +1,72 @@
1// WebGPU-safe 2D triangle mesh warp renderer for Fusion `SurfaceTracker`.
2//
3// Vertex positions are supplied in Fusion normalized Y-up [0..1] coordinates:
4// - `cur_pos`: tracked mesh vertex position at the evaluated frame
5// - `ref_pos`: reference mesh vertex position at `ReferenceFrame`
6// - `photo_weight`: per-vertex photometric weight ratio (`cur_pw / ref_pw`)
7//
8// The fragment shader projects `ref_pos` through the inverse `WarpableCanvas`
9// 3x3 projective homography `H_inv` into Overlay normalized Y-up [0..1] space,
10// converts to top-down texture UV, and bilinearly samples `overlay_tex`.
11
12struct MeshWarpUniform {
13 // Row-major 3x3 inverse homography mapping ref_pos (Fusion Y-up) -> Overlay (Fusion Y-up):
14 // h0 = (h00, h01, h02, h10)
15 // h1 = (h11, h12, h20, h21)
16 // h2 = (h22, photo_strength, 0.0, 0.0)
17 h0: vec4<f32>,
18 h1: vec4<f32>,
19 h2: vec4<f32>,
20 extra: vec4<f32>,
21};
22
23@group(0) @binding(0) var overlay_tex: texture_2d<f32>;
24@group(0) @binding(1) var lin_samp: sampler;
25@group(0) @binding(2) var<uniform> u: MeshWarpUniform;
26
27struct VsIn {
28 @location(0) cur_pos: vec2<f32>,
29 @location(1) ref_pos: vec2<f32>,
30 @location(2) photo_weight: f32,
31};
32
33struct VsOut {
34 @builtin(position) pos: vec4<f32>,
35 @location(0) ref_pos: vec2<f32>,
36 @location(1) photo_weight: f32,
37};
38
39@vertex
40fn vs_mesh(in: VsIn) -> VsOut {
41 var out: VsOut;
42 // Fusion Y-up [0..1] maps directly to WebGPU NDC [-1..1] (where +1 is top, -1 is bottom).
43 let ndc = vec2<f32>(in.cur_pos.x * 2.0 - 1.0, in.cur_pos.y * 2.0 - 1.0);
44 out.pos = vec4<f32>(ndc, 0.0, 1.0);
45 out.ref_pos = in.ref_pos;
46 out.photo_weight = in.photo_weight;
47 return out;
48}
49
50@fragment
51fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
52 let rx = in.ref_pos.x;
53 let ry = in.ref_pos.y;
54 let sx = u.h0.x * rx + u.h0.y * ry + u.h0.z;
55 let sy = u.h0.w * rx + u.h1.x * ry + u.h1.y;
56 let sw = u.h1.z * rx + u.h1.w * ry + u.h2.x;
57 if (abs(sw) < 1e-6) {
58 discard;
59 }
60 let fu_uv = vec2<f32>(sx / sw, sy / sw);
61 if (fu_uv.x < 0.0 || fu_uv.x > 1.0 || fu_uv.y < 0.0 || fu_uv.y > 1.0) {
62 discard;
63 }
64 let tex_uv = vec2<f32>(fu_uv.x, 1.0 - fu_uv.y);
65 var col = textureSampleLevel(overlay_tex, lin_samp, tex_uv, 0.0);
66 let photo_strength = clamp(u.h2.y, 0.0, 1.0);
67 if (photo_strength > 0.0) {
68 let pw = mix(1.0, max(in.photo_weight, 0.0), photo_strength);
69 col = vec4<f32>(col.rgb * pw, col.a);
70 }
71 return col;
72}
crates/engine/src/tracker.rs created+1431
......@@ -0,0 +1,1431 @@
1//! `SurfaceTracker` 2D triangle-mesh warp, `Dimension.PlanarTracker` /
2//! `Dimension.PlanarTransform` projective track evaluation, and live point/planar
3//! tracking helpers (`track_point_ncc`, `estimate_planar_homography`).
4
5use bytemuck::{Pod, Zeroable};
6use model::{Comp, LuaKey, LuaTable, LuaValue, Node, ParamValue};
7use std::collections::HashMap;
8use std::collections::hash_map::DefaultHasher;
9use std::hash::{Hash, Hasher};
10use std::sync::Mutex;
11use wgpu::util::DeviceExt;
12
13const TRACKER_MESH_WGSL: &str = include_str!("shaders/tracker_mesh.wgsl");
14
15// ============================================================================
16// 1. Raw Fusion Lua table parsing (`FuTriMesh`, `WarpableCanvas`, `Matrix`)
17// ============================================================================
18
19/// Parsed Fusion `FuTriMesh` keyframe payload from `SurfaceTracker.MeshCustom`.
20#[derive(Clone, Debug, PartialEq)]
21pub struct FuTriMesh {
22 /// Vertex positions in Fusion normalized `[0..1]` Y-up space.
23 pub vertices: Vec<[f32; 2]>,
24 /// 0-based triangle vertex indices (always a multiple of 3, bounds-checked).
25 pub faces: Vec<u32>,
26 /// Per-vertex photometric lighting weights (optional; defaults to `1.0` when absent).
27 pub photo_weights: Vec<f32>,
28}
29
30impl FuTriMesh {
31 /// Parses a `FuTriMesh { Vertices = {...}, Faces = {...}, PhotoWeights = {...} }` table.
32 pub fn from_lua_table(tbl: &LuaTable) -> Option<Self> {
33 let verts_tbl = tbl.get_table("Vertices")?;
34 let raw_v: Vec<f64> = verts_tbl
35 .positional_values()
36 .filter_map(LuaValue::as_f64)
37 .collect();
38 let n_verts = raw_v.len() / 2;
39 if n_verts < 3 {
40 return None;
41 }
42 let mut vertices = Vec::with_capacity(n_verts);
43 for i in 0..n_verts {
44 let x = raw_v[i * 2];
45 let y = raw_v[i * 2 + 1];
46 if !x.is_finite() || !y.is_finite() {
47 return None;
48 }
49 vertices.push([x as f32, y as f32]);
50 }
51
52 let faces_tbl = tbl.get_table("Faces")?;
53 let raw_f: Vec<i64> = faces_tbl
54 .positional_values()
55 .filter_map(LuaValue::as_f64)
56 .map(|v| v.round() as i64)
57 .collect();
58 let n_tris = raw_f.len() / 3;
59 let mut faces = Vec::with_capacity(n_tris * 3);
60 let max_v = n_verts as i64;
61 for t in 0..n_tris {
62 let i0 = raw_f[t * 3];
63 let i1 = raw_f[t * 3 + 1];
64 let i2 = raw_f[t * 3 + 2];
65 if i0 >= 0 && i0 < max_v && i1 >= 0 && i1 < max_v && i2 >= 0 && i2 < max_v {
66 faces.push(i0 as u32);
67 faces.push(i1 as u32);
68 faces.push(i2 as u32);
69 }
70 }
71 if faces.is_empty() {
72 return None;
73 }
74
75 let photo_weights = tbl
76 .get_table("PhotoWeights")
77 .map(|pw| {
78 pw.positional_values()
79 .filter_map(LuaValue::as_f64)
80 .map(|v| if v.is_finite() { v as f32 } else { 1.0 })
81 .collect::<Vec<_>>()
82 })
83 .unwrap_or_default();
84
85 Some(Self {
86 vertices,
87 faces,
88 photo_weights,
89 })
90 }
91
92 /// Linearly interpolates vertex positions and photometric weights between two matching-topology meshes.
93 pub fn lerp(&self, other: &Self, frac: f64) -> Self {
94 if self.vertices.len() != other.vertices.len() {
95 return if frac < 0.5 { self.clone() } else { other.clone() };
96 }
97 let t = frac.clamp(0.0, 1.0) as f32;
98 let vertices = self
99 .vertices
100 .iter()
101 .zip(other.vertices.iter())
102 .map(|(a, b)| [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t])
103 .collect();
104 let photo_weights = if self.photo_weights.len() == self.vertices.len()
105 && other.photo_weights.len() == other.vertices.len()
106 {
107 self.photo_weights
108 .iter()
109 .zip(other.photo_weights.iter())
110 .map(|(&a, &b)| a + (b - a) * t)
111 .collect()
112 } else if !self.photo_weights.is_empty() {
113 self.photo_weights.clone()
114 } else {
115 other.photo_weights.clone()
116 };
117 Self {
118 vertices,
119 faces: self.faces.clone(),
120 photo_weights,
121 }
122 }
123
124 pub fn content_hash(&self) -> u64 {
125 let mut h = DefaultHasher::new();
126 self.vertices.len().hash(&mut h);
127 for v in &self.vertices {
128 v[0].to_bits().hash(&mut h);
129 v[1].to_bits().hash(&mut h);
130 }
131 self.faces.hash(&mut h);
132 for &w in &self.photo_weights {
133 w.to_bits().hash(&mut h);
134 }
135 h.finish()
136 }
137}
138
139/// Parsed Fusion `Matrix { RefTime, RefSize, RefAspect, ToRef }` payload from
140/// `Dimension.PlanarTracker` / `Dimension.PlanarTransform` track splines.
141#[derive(Clone, Debug, PartialEq)]
142pub struct PlanarMatrix {
143 pub ref_time: f64,
144 pub ref_size: Option<[f64; 2]>,
145 pub ref_aspect: Option<[f64; 2]>,
146 pub is_bogus: bool,
147 /// Row-major 3x3 column-vector projective homography `H_to_ref` mapping
148 /// current-frame normalized Fusion `[x, y, 1]^T` -> reference-frame `[u, v, w]^T`.
149 pub to_ref_3x3: [f64; 9],
150}
151
152impl PlanarMatrix {
153 pub fn from_lua_table(tbl: &LuaTable) -> Option<Self> {
154 let is_bogus = tbl.get_bool("IsBogus").unwrap_or(false);
155 let ref_time = tbl.get_f64("RefTime").unwrap_or(0.0);
156 let ref_size = tbl.get_table("RefSize").and_then(extract_vec2);
157 let ref_aspect = tbl.get_table("RefAspect").and_then(extract_vec2);
158 let to_ref_tbl = tbl.get_table("ToRef")?;
159 let m = extract_matrix16(to_ref_tbl)?;
160 // Fusion stores `ToRef` as a 4x4 row-vector matrix:
161 // [x, y, 0, 1] * M = [m0*x + m4*y + m12, m1*x + m5*y + m13, ..., m3*x + m7*y + m15]
162 // Converting to column-vector form `H * [x, y, 1]^T` takes rows (0, 1, 3) & cols (0, 1, 3) transposed.
163 let to_ref_3x3 = [
164 m[0], m[4], m[12],
165 m[1], m[5], m[13],
166 m[3], m[7], m[15],
167 ];
168 if to_ref_3x3.iter().any(|v| !v.is_finite()) {
169 return None;
170 }
171 Some(Self {
172 ref_time,
173 ref_size,
174 ref_aspect,
175 is_bogus,
176 to_ref_3x3,
177 })
178 }
179
180 pub fn lerp(&self, other: &Self, frac: f64) -> Self {
181 let t = frac.clamp(0.0, 1.0);
182 let a = normalize_h(&self.to_ref_3x3);
183 let b = normalize_h(&other.to_ref_3x3);
184 let mut h = [0.0f64; 9];
185 for i in 0..9 {
186 h[i] = a[i] + (b[i] - a[i]) * t;
187 }
188 Self {
189 ref_time: self.ref_time,
190 ref_size: self.ref_size.or(other.ref_size),
191 ref_aspect: self.ref_aspect.or(other.ref_aspect),
192 is_bogus: self.is_bogus && other.is_bogus,
193 to_ref_3x3: h,
194 }
195 }
196}
197
198fn extract_vec2(tbl: &LuaTable) -> Option<[f64; 2]> {
199 let mut it = tbl.positional_values().filter_map(LuaValue::as_f64);
200 let x = it.next()?;
201 let y = it.next()?;
202 if x.is_finite() && y.is_finite() {
203 Some([x, y])
204 } else {
205 None
206 }
207}
208
209/// Extracts 16 finite floats from a Lua matrix table, handling both Fusion's `[0] = m0, m1, ..., m15`
210/// 0-based layout and standard 1-based `{ m0, m1, ..., m15 }` positional tables.
211fn extract_matrix16(tbl: &LuaTable) -> Option<[f64; 16]> {
212 let mut vals = [0.0f64; 16];
213 if tbl.get_index(0).is_some() {
214 for (i, slot) in vals.iter_mut().enumerate() {
215 let v = tbl.get_index(i as i64)?.as_f64()?;
216 if !v.is_finite() {
217 return None;
218 }
219 *slot = v;
220 }
221 return Some(vals);
222 }
223 let pos: Vec<f64> = tbl.positional_values().filter_map(LuaValue::as_f64).collect();
224 if pos.len() >= 16 && pos[..16].iter().all(|v| v.is_finite()) {
225 vals.copy_from_slice(&pos[..16]);
226 return Some(vals);
227 }
228 None
229}
230
231/// Recursively locates a named tool/spline inside `Tools` (including nested Macro/Group `Tools`).
232fn find_raw_tool<'a>(tools: &'a LuaTable, target: &str) -> Option<&'a LuaTable> {
233 if let Some(t) = tools.get_table(target) {
234 return Some(t);
235 }
236 tools
237 .entries
238 .iter()
239 .filter_map(|(_, v)| v.as_table()?.get_table("Tools"))
240 .find_map(|inner| find_raw_tool(inner, target))
241}
242
243fn sample_mesh_keyframes(kfs: &[(f64, FuTriMesh)], time: f64) -> FuTriMesh {
244 if kfs.len() == 1 || time.is_nan() || time <= kfs[0].0 {
245 return kfs[0].1.clone();
246 }
247 let last = kfs.len() - 1;
248 if time >= kfs[last].0 {
249 return kfs[last].1.clone();
250 }
251 let idx = kfs.partition_point(|(t, _)| *t <= time).saturating_sub(1);
252 let (t0, ref m0) = kfs[idx];
253 let (t1, ref m1) = kfs[(idx + 1).min(last)];
254 let span = t1 - t0;
255 if span.abs() < 1e-9 || (time - t0).abs() < 1e-6 {
256 return m0.clone();
257 }
258 if (t1 - time).abs() < 1e-6 {
259 return m1.clone();
260 }
261 m0.lerp(m1, (time - t0) / span)
262}
263
264/// Evaluates `(ref_mesh, cur_mesh, ref_frame)` for a `SurfaceTracker` node at `time`.
265pub fn eval_surface_mesh(
266 comp: &Comp,
267 node: &Node,
268 time: f64,
269 ref_frame_override: Option<f64>,
270) -> Option<(FuTriMesh, FuTriMesh, f64)> {
271 // Try spline-backed `MeshCustom` first.
272 if let Some(spline_name) = node.inputs.get("MeshCustom").and_then(|b| b.source_op.as_deref()) {
273 let tools = comp.raw_root.as_ref()?.get_table("Tools")?;
274 let stbl = find_raw_tool(tools, spline_name)?;
275 let kfs_tbl = stbl.get_table("KeyFrames")?;
276 let mut kfs: Vec<(f64, FuTriMesh)> = Vec::new();
277 for (k, v) in &kfs_tbl.entries {
278 let t = match k {
279 LuaKey::Index(i) => *i as f64,
280 LuaKey::Number(n) => *n,
281 _ => continue,
282 };
283 if let Some(m) = v
284 .as_table()
285 .and_then(|kt| kt.get_table("Value"))
286 .and_then(FuTriMesh::from_lua_table)
287 {
288 kfs.push((t, m));
289 }
290 }
291 if !kfs.is_empty() {
292 kfs.sort_by(|a, b| a.0.total_cmp(&b.0));
293 let ref_frame = ref_frame_override.unwrap_or(kfs[0].0);
294 let cur_mesh = sample_mesh_keyframes(&kfs, time);
295 let mut ref_mesh = sample_mesh_keyframes(&kfs, ref_frame);
296 if ref_mesh.vertices.len() != cur_mesh.vertices.len() {
297 // Fall back to the closest keyframe to `ref_frame` with matching vertex count.
298 ref_mesh = kfs
299 .iter()
300 .filter(|(_, m)| m.vertices.len() == cur_mesh.vertices.len())
301 .min_by(|(ta, _), (tb, _)| (ta - ref_frame).abs().total_cmp(&(tb - ref_frame).abs()))
302 .map(|(_, m)| m.clone())
303 .unwrap_or_else(|| cur_mesh.clone());
304 }
305 return Some((ref_mesh, cur_mesh, ref_frame));
306 }
307 }
308
309 // Fallback: static `MeshCustom = Input { Value = FuTriMesh { ... } }`.
310 let static_tbl = node
311 .inputs
312 .get("MeshCustom")
313 .and_then(|b| match b.value.as_ref()? {
314 ParamValue::Raw(LuaValue::Table(t)) => Some(t),
315 _ => None,
316 })
317 .or_else(|| {
318 node.raw
319 .get_table("Inputs")
320 .and_then(|i| i.get_table("MeshCustom"))
321 .and_then(|m| m.get_table("Value"))
322 })?;
323 let mesh = FuTriMesh::from_lua_table(static_tbl)?;
324 let rf = ref_frame_override.unwrap_or(0.0);
325 Some((mesh.clone(), mesh, rf))
326}
327
328/// Extracts `WarpableCanvas.Corners` as `[tl, tr, br, bl]` in Fusion Y-up `[0..1]` space.
329/// Returns `None` if `WarpableCanvas` corners are absent or invalid.
330pub fn extract_warpable_canvas_corners(node: &Node) -> Option<[[f64; 2]; 4]> {
331 let wc_tbl = node
332 .inputs
333 .get("WarpableCanvas")
334 .and_then(|b| match b.value.as_ref()? {
335 ParamValue::Raw(LuaValue::Table(t)) => Some(t),
336 _ => None,
337 })
338 .or_else(|| {
339 node.raw
340 .get_table("Inputs")
341 .and_then(|i| i.get_table("WarpableCanvas"))
342 .and_then(|w| w.get_table("Value"))
343 })?;
344 let corners_tbl = wc_tbl.get_table("Corners")?;
345 let vals: Vec<f64> = corners_tbl
346 .positional_values()
347 .filter_map(LuaValue::as_f64)
348 .collect();
349 if vals.len() < 8 || !vals[..8].iter().all(|v| v.is_finite()) {
350 return None;
351 }
352 Some([
353 [vals[0], vals[1]], // TL
354 [vals[2], vals[3]], // TR
355 [vals[4], vals[5]], // BR
356 [vals[6], vals[7]], // BL
357 ])
358}
359
360/// Evaluates a `Dimension.PlanarTracker` / `Dimension.PlanarTransform` `Matrix` spline input
361/// (such as `"Track"` or `"StableTrack"`) at `time`.
362pub fn eval_planar_track(comp: &Comp, node: &Node, input_name: &str, time: f64) -> Option<PlanarMatrix> {
363 if let Some(spline_name) = node.inputs.get(input_name).and_then(|b| b.source_op.as_deref()) {
364 let tools = comp.raw_root.as_ref()?.get_table("Tools")?;
365 if let Some(stbl) = find_raw_tool(tools, spline_name)
366 && let Some(kfs_tbl) = stbl.get_table("KeyFrames")
367 {
368 let mut kfs: Vec<(f64, PlanarMatrix)> = Vec::new();
369 for (k, v) in &kfs_tbl.entries {
370 let t = match k {
371 LuaKey::Index(i) => *i as f64,
372 LuaKey::Number(n) => *n,
373 _ => continue,
374 };
375 if let Some(pm) = v
376 .as_table()
377 .and_then(|kt| kt.get_table("Value"))
378 .and_then(PlanarMatrix::from_lua_table)
379 && !pm.is_bogus
380 {
381 kfs.push((t, pm));
382 }
383 }
384 if !kfs.is_empty() {
385 kfs.sort_by(|a, b| a.0.total_cmp(&b.0));
386 if kfs.len() == 1 || time.is_nan() || time <= kfs[0].0 {
387 return Some(kfs[0].1.clone());
388 }
389 let last = kfs.len() - 1;
390 if time >= kfs[last].0 {
391 return Some(kfs[last].1.clone());
392 }
393 let idx = kfs.partition_point(|(t, _)| *t <= time).saturating_sub(1);
394 let (t0, ref m0) = kfs[idx];
395 let (t1, ref m1) = kfs[(idx + 1).min(last)];
396 let span = t1 - t0;
397 if span.abs() < 1e-9 || (time - t0).abs() < 1e-6 {
398 return Some(m0.clone());
399 }
400 if (t1 - time).abs() < 1e-6 {
401 return Some(m1.clone());
402 }
403 return Some(m0.lerp(m1, (time - t0) / span));
404 }
405 }
406 }
407
408 // Fallback: static `Matrix { ... }` on the input itself.
409 let static_tbl = node
410 .inputs
411 .get(input_name)
412 .and_then(|b| match b.value.as_ref()? {
413 ParamValue::Raw(LuaValue::Table(t)) => Some(t),
414 _ => None,
415 })
416 .or_else(|| {
417 node.raw
418 .get_table("Inputs")
419 .and_then(|i| i.get_table(input_name))
420 .and_then(|m| m.get_table("Value"))
421 })?;
422 let pm = PlanarMatrix::from_lua_table(static_tbl)?;
423 if pm.is_bogus {
424 None
425 } else {
426 Some(pm)
427 }
428}
429
430// ============================================================================
431// 2. 3x3 Projective Homography Math
432// ============================================================================
433
434pub fn normalize_h(h: &[f64; 9]) -> [f64; 9] {
435 if h[8].abs() > 1e-12 {
436 let inv = 1.0 / h[8];
437 h.map(|v| v * inv)
438 } else {
439 let norm = h.iter().map(|v| v * v).sum::<f64>().sqrt();
440 if norm > 1e-12 {
441 h.map(|v| v / norm)
442 } else {
443 *h
444 }
445 }
446}
447
448pub fn mat3_mul(a: &[f64; 9], b: &[f64; 9]) -> [f64; 9] {
449 std::array::from_fn(|k| {
450 let r = k / 3;
451 let c = k % 3;
452 a[r * 3] * b[c] + a[r * 3 + 1] * b[3 + c] + a[r * 3 + 2] * b[6 + c]
453 })
454}
455
456pub fn mat3_det(m: &[f64; 9]) -> f64 {
457 let [a, b, c, d, e, f, g, h, i] = *m;
458 a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g)
459}
460
461pub fn mat3_invert(m: &[f64; 9]) -> Option<[f64; 9]> {
462 let [a, b, c, d, e, f, g, h, i] = *m;
463 let adj = [
464 e * i - f * h,
465 c * h - b * i,
466 b * f - c * e,
467 f * g - d * i,
468 a * i - c * g,
469 c * d - a * f,
470 d * h - e * g,
471 b * g - a * h,
472 a * e - b * d,
473 ];
474 let det = a * adj[0] + b * adj[3] + c * adj[6];
475 if det.abs() < 1e-12 {
476 return None;
477 }
478 let inv_det = 1.0 / det;
479 Some(adj.map(|v| v * inv_det))
480}
481
482/// Computes the 3x3 projective homography mapping the Fusion Y-up quad `(tl, tr, br, bl)`
483/// to the unit square `[0, 1]^2` where `bl -> (0, 0), br -> (1, 0), tr -> (1, 1), tl -> (0, 1)`.
484pub fn quad_to_unit_homography(
485 tl: [f64; 2],
486 tr: [f64; 2],
487 br: [f64; 2],
488 bl: [f64; 2],
489) -> [f64; 9] {
490 let dx1 = br[0] - tr[0];
491 let dy1 = br[1] - tr[1];
492 let dx2 = tl[0] - tr[0];
493 let dy2 = tl[1] - tr[1];
494 let sx = bl[0] - br[0] + tr[0] - tl[0];
495 let sy = bl[1] - br[1] + tr[1] - tl[1];
496 let denom = dx1 * dy2 - dx2 * dy1;
497 if denom.abs() < 1e-10 {
498 return [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
499 }
500 let g = (sx * dy2 - sy * dx2) / denom;
501 let h = (dx1 * sy - dy1 * sx) / denom;
502 let unit_to_quad = [
503 br[0] - bl[0] + g * br[0],
504 tl[0] - bl[0] + h * tl[0],
505 bl[0],
506 br[1] - bl[1] + g * br[1],
507 tl[1] - bl[1] + h * tl[1],
508 bl[1],
509 g,
510 h,
511 1.0,
512 ];
513 mat3_invert(&unit_to_quad)
514 .map(|inv| normalize_h(&inv))
515 .unwrap_or([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0])
516}
517
518// ============================================================================
519// 3. WebGPU-Safe `SurfaceTracker` Mesh Warp Renderer
520// ============================================================================
521
522#[repr(C)]
523#[derive(Clone, Copy, Pod, Zeroable)]
524struct MeshVertex {
525 cur_pos: [f32; 2],
526 ref_pos: [f32; 2],
527 photo_weight: f32,
528 _pad: f32,
529}
530
531#[repr(C)]
532#[derive(Clone, Copy, Pod, Zeroable)]
533struct MeshWarpUniform {
534 h0: [f32; 4],
535 h1: [f32; 4],
536 h2: [f32; 4],
537 extra: [f32; 4],
538}
539
540/// Lazily initialized WebGPU-safe render pipelines for `SurfaceTracker` mesh warping.
541/// Only renders to `Rgba8Unorm` or `Rgba16Float` (always baseline WebGPU `RENDER_ATTACHMENT`).
542pub struct TrackerPipelines {
543 shader: wgpu::ShaderModule,
544 bgl: wgpu::BindGroupLayout,
545 pipeline_layout: wgpu::PipelineLayout,
546 sampler: wgpu::Sampler,
547 pipelines: Mutex<HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>>,
548}
549
550impl TrackerPipelines {
551 pub fn new(device: &wgpu::Device) -> Self {
552 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
553 label: Some("tracker-mesh-shader"),
554 source: wgpu::ShaderSource::Wgsl(TRACKER_MESH_WGSL.into()),
555 });
556 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
557 label: Some("tracker-mesh-bgl"),
558 entries: &[
559 wgpu::BindGroupLayoutEntry {
560 binding: 0,
561 visibility: wgpu::ShaderStages::FRAGMENT,
562 ty: wgpu::BindingType::Texture {
563 sample_type: wgpu::TextureSampleType::Float { filterable: true },
564 view_dimension: wgpu::TextureViewDimension::D2,
565 multisampled: false,
566 },
567 count: None,
568 },
569 wgpu::BindGroupLayoutEntry {
570 binding: 1,
571 visibility: wgpu::ShaderStages::FRAGMENT,
572 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
573 count: None,
574 },
575 wgpu::BindGroupLayoutEntry {
576 binding: 2,
577 visibility: wgpu::ShaderStages::FRAGMENT,
578 ty: wgpu::BindingType::Buffer {
579 ty: wgpu::BufferBindingType::Uniform,
580 has_dynamic_offset: false,
581 min_binding_size: wgpu::BufferSize::new(
582 std::mem::size_of::<MeshWarpUniform>() as u64,
583 ),
584 },
585 count: None,
586 },
587 ],
588 });
589 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
590 label: Some("tracker-mesh-pl"),
591 bind_group_layouts: &[Some(&bgl)],
592 immediate_size: 0,
593 });
594 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
595 label: Some("tracker-mesh-lin-samp"),
596 address_mode_u: wgpu::AddressMode::ClampToEdge,
597 address_mode_v: wgpu::AddressMode::ClampToEdge,
598 address_mode_w: wgpu::AddressMode::ClampToEdge,
599 mag_filter: wgpu::FilterMode::Linear,
600 min_filter: wgpu::FilterMode::Linear,
601 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
602 ..Default::default()
603 });
604 Self {
605 shader,
606 bgl,
607 pipeline_layout,
608 sampler,
609 pipelines: Mutex::new(HashMap::new()),
610 }
611 }
612
613 fn create_pipeline(
614 &self,
615 device: &wgpu::Device,
616 format: wgpu::TextureFormat,
617 ) -> wgpu::RenderPipeline {
618 const VERTEX_ATTRS: [wgpu::VertexAttribute; 3] = wgpu::vertex_attr_array![
619 0 => Float32x2,
620 1 => Float32x2,
621 2 => Float32,
622 ];
623 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
624 label: Some("tracker-mesh-pipeline"),
625 layout: Some(&self.pipeline_layout),
626 vertex: wgpu::VertexState {
627 module: &self.shader,
628 entry_point: Some("vs_mesh"),
629 compilation_options: Default::default(),
630 buffers: &[Some(wgpu::VertexBufferLayout {
631 array_stride: std::mem::size_of::<MeshVertex>() as wgpu::BufferAddress,
632 step_mode: wgpu::VertexStepMode::Vertex,
633 attributes: &VERTEX_ATTRS,
634 })],
635 },
636 primitive: wgpu::PrimitiveState {
637 topology: wgpu::PrimitiveTopology::TriangleList,
638 strip_index_format: None,
639 front_face: wgpu::FrontFace::Ccw,
640 cull_mode: None,
641 unclipped_depth: false,
642 polygon_mode: wgpu::PolygonMode::Fill,
643 conservative: false,
644 },
645 depth_stencil: None,
646 multisample: wgpu::MultisampleState::default(),
647 fragment: Some(wgpu::FragmentState {
648 module: &self.shader,
649 entry_point: Some("fs_mesh"),
650 compilation_options: Default::default(),
651 targets: &[Some(wgpu::ColorTargetState {
652 format,
653 blend: None,
654 write_mask: wgpu::ColorWrites::ALL,
655 })],
656 }),
657 multiview_mask: None,
658 cache: None,
659 })
660 }
661
662 /// Rasterizes the tracked 2D triangle mesh (`ref_mesh` -> `cur_mesh`) sampling `overlay_view`
663 /// through `h_inv_fu` onto `dst_view` (cleared to transparent black).
664 ///
665 /// `dst_format` must be a baseline WebGPU renderable format (`Rgba8Unorm` or `Rgba16Float`).
666 #[allow(clippy::too_many_arguments)]
667 pub fn render_surface_mesh(
668 &self,
669 device: &wgpu::Device,
670 enc: &mut wgpu::CommandEncoder,
671 overlay_view: &wgpu::TextureView,
672 dst_view: &wgpu::TextureView,
673 dst_format: wgpu::TextureFormat,
674 ref_mesh: &FuTriMesh,
675 cur_mesh: &FuTriMesh,
676 h_inv_fu: [f64; 9],
677 photo_strength: f32,
678 ) {
679 let n_verts = cur_mesh.vertices.len().min(ref_mesh.vertices.len());
680 if n_verts < 3 || cur_mesh.faces.len() < 3 {
681 // Clear target to transparent even if mesh is empty.
682 let _pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
683 label: Some("surface-tracker-clear"),
684 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
685 view: dst_view,
686 depth_slice: None,
687 resolve_target: None,
688 ops: wgpu::Operations {
689 load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
690 store: wgpu::StoreOp::Store,
691 },
692 })],
693 depth_stencil_attachment: None,
694 timestamp_writes: None,
695 occlusion_query_set: None,
696 multiview_mask: None,
697 });
698 return;
699 }
700
701 let mut vertices = Vec::with_capacity(n_verts);
702 for i in 0..n_verts {
703 let cur_pw = cur_mesh.photo_weights.get(i).copied().unwrap_or(1.0);
704 let ref_pw = ref_mesh.photo_weights.get(i).copied().unwrap_or(1.0);
705 let ratio = if ref_pw.abs() > 1e-4 { cur_pw / ref_pw } else { 1.0 };
706 vertices.push(MeshVertex {
707 cur_pos: cur_mesh.vertices[i],
708 ref_pos: ref_mesh.vertices[i],
709 photo_weight: ratio.clamp(0.0, 4.0),
710 _pad: 0.0,
711 });
712 }
713
714 let max_v = n_verts as u32;
715 let mut indices = Vec::with_capacity(cur_mesh.faces.len());
716 for tri in cur_mesh.faces.chunks_exact(3) {
717 if tri[0] < max_v && tri[1] < max_v && tri[2] < max_v {
718 indices.extend_from_slice(tri);
719 }
720 }
721 if indices.is_empty() {
722 return;
723 }
724
725 let vbuf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
726 label: Some("surface-tracker-vbuf"),
727 contents: bytemuck::cast_slice(&vertices),
728 usage: wgpu::BufferUsages::VERTEX,
729 });
730 let ibuf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
731 label: Some("surface-tracker-ibuf"),
732 contents: bytemuck::cast_slice(&indices),
733 usage: wgpu::BufferUsages::INDEX,
734 });
735 let uniform = MeshWarpUniform {
736 h0: [
737 h_inv_fu[0] as f32,
738 h_inv_fu[1] as f32,
739 h_inv_fu[2] as f32,
740 h_inv_fu[3] as f32,
741 ],
742 h1: [
743 h_inv_fu[4] as f32,
744 h_inv_fu[5] as f32,
745 h_inv_fu[6] as f32,
746 h_inv_fu[7] as f32,
747 ],
748 h2: [h_inv_fu[8] as f32, photo_strength, 0.0, 0.0],
749 extra: [0.0; 4],
750 };
751 let ubuf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
752 label: Some("surface-tracker-ubuf"),
753 contents: bytemuck::bytes_of(&uniform),
754 usage: wgpu::BufferUsages::UNIFORM,
755 });
756 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
757 label: Some("surface-tracker-bg"),
758 layout: &self.bgl,
759 entries: &[
760 wgpu::BindGroupEntry {
761 binding: 0,
762 resource: wgpu::BindingResource::TextureView(overlay_view),
763 },
764 wgpu::BindGroupEntry {
765 binding: 1,
766 resource: wgpu::BindingResource::Sampler(&self.sampler),
767 },
768 wgpu::BindGroupEntry {
769 binding: 2,
770 resource: ubuf.as_entire_binding(),
771 },
772 ],
773 });
774
775 let mut cache = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
776 let pipeline = cache
777 .entry(dst_format)
778 .or_insert_with(|| self.create_pipeline(device, dst_format));
779
780 let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
781 label: Some("surface-tracker-mesh-pass"),
782 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
783 view: dst_view,
784 depth_slice: None,
785 resolve_target: None,
786 ops: wgpu::Operations {
787 load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
788 store: wgpu::StoreOp::Store,
789 },
790 })],
791 depth_stencil_attachment: None,
792 timestamp_writes: None,
793 occlusion_query_set: None,
794 multiview_mask: None,
795 });
796 pass.set_pipeline(pipeline);
797 pass.set_bind_group(0, &bg, &[]);
798 pass.set_vertex_buffer(0, vbuf.slice(..));
799 pass.set_index_buffer(ibuf.slice(..), wgpu::IndexFormat::Uint32);
800 pass.draw_indexed(0..indices.len() as u32, 0, 0..1);
801 }
802}
803
804// ============================================================================
805// 4. Live Tracking Helper API (NCC Point Tracker + Normalized DLT Homography)
806// ============================================================================
807
808#[inline]
809fn rgba_luma_bilinear(rgba: &[u8], w: u32, h: u32, x: f64, y: f64) -> f64 {
810 let wf = (w - 1) as f64;
811 let hf = (h - 1) as f64;
812 let cx = x.clamp(0.0, wf);
813 let cy = y.clamp(0.0, hf);
814 let x0 = cx.floor() as u32;
815 let y0 = cy.floor() as u32;
816 let x1 = (x0 + 1).min(w - 1);
817 let y1 = (y0 + 1).min(h - 1);
818 let fx = cx - x0 as f64;
819 let fy = cy - y0 as f64;
820
821 let sample = |ix: u32, iy: u32| -> f64 {
822 let idx = ((iy as usize) * (w as usize) + (ix as usize)) * 4;
823 0.299 * rgba[idx] as f64 + 0.587 * rgba[idx + 1] as f64 + 0.114 * rgba[idx + 2] as f64
824 };
825 let v00 = sample(x0, y0);
826 let v10 = sample(x1, y0);
827 let v01 = sample(x0, y1);
828 let v11 = sample(x1, y1);
829 let top = v00 + (v10 - v00) * fx;
830 let bot = v01 + (v11 - v01) * fx;
831 top + (bot - top) * fy
832}
833
834/// Sub-pixel parabolic-refined Zero-Mean Normalized Cross-Correlation (NCC) point tracker.
835///
836/// Tracks `prev_pos_fu` (Fusion normalized `[0..1]` Y-up coordinates) from `prev_rgba` to
837/// `cur_rgba` within `search_radius_px` using a `(2 * patch_radius_px + 1)^2` template patch.
838/// Returns `(new_pos_fu, confidence)` where `confidence` is in `[0.0, 1.0]`.
839pub fn track_point_ncc(
840 prev_rgba: &[u8],
841 cur_rgba: &[u8],
842 size: [u32; 2],
843 prev_pos_fu: [f64; 2],
844 search_radius_px: i32,
845 patch_radius_px: i32,
846) -> ([f64; 2], f32) {
847 let [w, h] = size;
848 if w == 0 || h == 0 {
849 return (prev_pos_fu, 0.0);
850 }
851 let expected_len = (w as usize).saturating_mul(h as usize).saturating_mul(4);
852 if prev_rgba.len() < expected_len || cur_rgba.len() < expected_len {
853 return (prev_pos_fu, 0.0);
854 }
855 let sr = search_radius_px.max(0);
856 let pr = patch_radius_px.max(1);
857 let side = (2 * pr + 1) as usize;
858 let n_pix = side * side;
859
860 let wf = w as f64;
861 let hf = h as f64;
862 let px = prev_pos_fu[0] * wf - 0.5;
863 let py = (1.0 - prev_pos_fu[1]) * hf - 0.5;
864
865 // Sample template patch centered at exact (sub-pixel) `prev_pos_fu`.
866 let mut tpl = Vec::with_capacity(n_pix);
867 let mut tpl_sum = 0.0f64;
868 for oy in -pr..=pr {
869 for ox in -pr..=pr {
870 let v = rgba_luma_bilinear(prev_rgba, w, h, px + ox as f64, py + oy as f64);
871 tpl.push(v);
872 tpl_sum += v;
873 }
874 }
875 let tpl_mean = tpl_sum / n_pix as f64;
876 let mut tpl_var = 0.0f64;
877 for v in &mut tpl {
878 *v -= tpl_mean;
879 tpl_var += *v * *v;
880 }
881 if tpl_var < 1e-6 {
882 return (prev_pos_fu, 0.0);
883 }
884
885 let grid_side = (2 * sr + 1) as usize;
886 let mut scores = vec![-1.0f64; grid_side * grid_side];
887 let mut best_score = -2.0f64;
888 let mut best_dx = 0i32;
889 let mut best_dy = 0i32;
890
891 let mut cand = vec![0.0f64; n_pix];
892 for dy in -sr..=sr {
893 for dx in -sr..=sr {
894 let cx = px + dx as f64;
895 let cy = py + dy as f64;
896 let mut sum = 0.0f64;
897 let mut k = 0usize;
898 for oy in -pr..=pr {
899 for ox in -pr..=pr {
900 let v = rgba_luma_bilinear(cur_rgba, w, h, cx + ox as f64, cy + oy as f64);
901 cand[k] = v;
902 sum += v;
903 k += 1;
904 }
905 }
906 let mean = sum / n_pix as f64;
907 let mut num = 0.0f64;
908 let mut cand_var = 0.0f64;
909 for i in 0..n_pix {
910 let d = cand[i] - mean;
911 num += tpl[i] * d;
912 cand_var += d * d;
913 }
914 let denom = (tpl_var * cand_var).sqrt();
915 let score = if denom > 1e-8 { num / denom } else { -1.0 };
916 let gx = (dx + sr) as usize;
917 let gy = (dy + sr) as usize;
918 scores[gy * grid_side + gx] = score;
919 if score > best_score {
920 best_score = score;
921 best_dx = dx;
922 best_dy = dy;
923 }
924 }
925 }
926
927 if best_score <= -1.5 {
928 return (prev_pos_fu, 0.0);
929 }
930
931 // Parabolic sub-pixel peak refinement along X and Y.
932 let gx = (best_dx + sr) as usize;
933 let gy = (best_dy + sr) as usize;
934 let sub_x = if gx > 0 && gx + 1 < grid_side {
935 let cm = scores[gy * grid_side + (gx - 1)];
936 let c0 = scores[gy * grid_side + gx];
937 let cp = scores[gy * grid_side + (gx + 1)];
938 let denom = cm - 2.0 * c0 + cp;
939 if denom < -1e-9 {
940 (0.5 * (cm - cp) / denom).clamp(-0.5, 0.5)
941 } else {
942 0.0
943 }
944 } else {
945 0.0
946 };
947 let sub_y = if gy > 0 && gy + 1 < grid_side {
948 let cm = scores[(gy - 1) * grid_side + gx];
949 let c0 = scores[gy * grid_side + gx];
950 let cp = scores[(gy + 1) * grid_side + gx];
951 let denom = cm - 2.0 * c0 + cp;
952 if denom < -1e-9 {
953 (0.5 * (cm - cp) / denom).clamp(-0.5, 0.5)
954 } else {
955 0.0
956 }
957 } else {
958 0.0
959 };
960
961 let new_px = px + best_dx as f64 + sub_x;
962 let new_py = py + best_dy as f64 + sub_y;
963 let new_fu = [(new_px + 0.5) / wf, 1.0 - (new_py + 0.5) / hf];
964 (new_fu, best_score.clamp(0.0, 1.0) as f32)
965}
966
967/// Hartley isotropic point normalization: translates centroid to `(0, 0)` and scales average
968/// distance from origin to `sqrt(2)`. Returns `(T, T_inv, normalized_points)`.
969fn hartley_normalize(pts: &[[f64; 2]]) -> Option<([f64; 9], [f64; 9], Vec<[f64; 2]>)> {
970 let n = pts.len() as f64;
971 if pts.is_empty() {
972 return None;
973 }
974 let mut cx = 0.0;
975 let mut cy = 0.0;
976 for p in pts {
977 if !p[0].is_finite() || !p[1].is_finite() {
978 return None;
979 }
980 cx += p[0];
981 cy += p[1];
982 }
983 cx /= n;
984 cy /= n;
985
986 let mut mean_dist = 0.0;
987 for p in pts {
988 let dx = p[0] - cx;
989 let dy = p[1] - cy;
990 mean_dist += (dx * dx + dy * dy).sqrt();
991 }
992 mean_dist /= n;
993 if mean_dist < 1e-12 {
994 return None;
995 }
996 let s = std::f64::consts::SQRT_2 / mean_dist;
997 let inv_s = 1.0 / s;
998
999 let t = [s, 0.0, -s * cx, 0.0, s, -s * cy, 0.0, 0.0, 1.0];
1000 let t_inv = [inv_s, 0.0, cx, 0.0, inv_s, cy, 0.0, 0.0, 1.0];
1001 let norm = pts.iter().map(|p| [(p[0] - cx) * s, (p[1] - cy) * s]).collect();
1002 Some((t, t_inv, norm))
1003}
1004
1005/// Cyclic Jacobi eigensolver for a 9x9 real symmetric matrix; returns the unit eigenvector
1006/// corresponding to the smallest eigenvalue.
1007fn smallest_eigenvector_9x9(mut a: [[f64; 9]; 9]) -> [f64; 9] {
1008 let mut v = [[0.0f64; 9]; 9];
1009 for (i, row) in v.iter_mut().enumerate() {
1010 row[i] = 1.0;
1011 }
1012 for _sweep in 0..32 {
1013 let mut max_off = 0.0f64;
1014 for p in 0..9 {
1015 for q in (p + 1)..9 {
1016 let apq = a[p][q];
1017 let abs_apq = apq.abs();
1018 if abs_apq > max_off {
1019 max_off = abs_apq;
1020 }
1021 if abs_apq < 1e-15 {
1022 continue;
1023 }
1024 let tau = (a[q][q] - a[p][p]) / (2.0 * apq);
1025 let t = if tau >= 0.0 {
1026 1.0 / (tau + (1.0 + tau * tau).sqrt())
1027 } else {
1028 -1.0 / (-tau + (1.0 + tau * tau).sqrt())
1029 };
1030 let c = 1.0 / (1.0 + t * t).sqrt();
1031 let s = t * c;
1032
1033 let app = a[p][p];
1034 let aqq = a[q][q];
1035 a[p][p] = app - t * apq;
1036 a[q][q] = aqq + t * apq;
1037 a[p][q] = 0.0;
1038 a[q][p] = 0.0;
1039
1040 for r in 0..9 {
1041 if r != p && r != q {
1042 let arp = a[r][p];
1043 let arq = a[r][q];
1044 let nrp = c * arp - s * arq;
1045 let nrq = s * arp + c * arq;
1046 a[r][p] = nrp;
1047 a[p][r] = nrp;
1048 a[r][q] = nrq;
1049 a[q][r] = nrq;
1050 }
1051 let vrp = v[r][p];
1052 let vrq = v[r][q];
1053 v[r][p] = c * vrp - s * vrq;
1054 v[r][q] = s * vrp + c * vrq;
1055 }
1056 }
1057 }
1058 if max_off < 1e-14 {
1059 break;
1060 }
1061 }
1062 let mut min_idx = 0usize;
1063 let mut min_val = a[0][0];
1064 for (i, row) in a.iter().enumerate().skip(1) {
1065 if row[i] < min_val {
1066 min_val = row[i];
1067 min_idx = i;
1068 }
1069 }
1070 std::array::from_fn(|r| v[r][min_idx])
1071}
1072
1073/// Normalized Direct Linear Transform (DLT) 2D projective homography solver (`>= 4` correspondences).
1074///
1075/// Returns a row-major 3x3 column-vector projective matrix `H` mapping `src_pts[i] -> dst_pts[i]`
1076/// (normalized so `H[8] == 1.0` when non-zero), directly compatible with `Dimension.PlanarTransform`.
1077pub fn estimate_planar_homography(src_pts: &[[f64; 2]], dst_pts: &[[f64; 2]]) -> Option<[f64; 9]> {
1078 if src_pts.len() != dst_pts.len() || src_pts.len() < 4 {
1079 return None;
1080 }
1081 let (t_src, _, norm_src) = hartley_normalize(src_pts)?;
1082 let (_, t_dst_inv, norm_dst) = hartley_normalize(dst_pts)?;
1083
1084 // Accumulate 9x9 symmetric normal matrix M = A^T A.
1085 let mut ata = [[0.0f64; 9]; 9];
1086 for (p, q) in norm_src.iter().zip(norm_dst.iter()) {
1087 let [x, y] = *p;
1088 let [u, v] = *q;
1089 let r1 = [-x, -y, -1.0, 0.0, 0.0, 0.0, u * x, u * y, u];
1090 let r2 = [0.0, 0.0, 0.0, -x, -y, -1.0, v * x, v * y, v];
1091 for row in [&r1, &r2] {
1092 for i in 0..9 {
1093 let ri = row[i];
1094 if ri == 0.0 {
1095 continue;
1096 }
1097 for j in i..9 {
1098 ata[i][j] += ri * row[j];
1099 }
1100 }
1101 }
1102 }
1103 for i in 0..9 {
1104 for j in 0..i {
1105 ata[i][j] = ata[j][i];
1106 }
1107 }
1108
1109 let h_norm = smallest_eigenvector_9x9(ata);
1110 let h = mat3_mul(&mat3_mul(&t_dst_inv, &h_norm), &t_src);
1111 if mat3_det(&h).abs() < 1e-12 || h.iter().any(|v| !v.is_finite()) {
1112 return None;
1113 }
1114 Some(normalize_h(&h))
1115}
1116
1117#[cfg(test)]
1118mod tests {
1119 use super::*;
1120 use crate::Engine;
1121
1122 #[test]
1123 fn track_point_ncc_tracks_subpixel_shift_within_half_pixel() {
1124 let w = 96u32;
1125 let h = 96u32;
1126 let make_img = |cx: f64, cy: f64| -> Vec<u8> {
1127 let mut out = vec![0u8; (w * h * 4) as usize];
1128 for y in 0..h {
1129 for x in 0..w {
1130 let dx = x as f64 - cx;
1131 let dy = y as f64 - cy;
1132 // Distinct asymmetric feature blob + ring so NCC peak is sharp and unique.
1133 let g1 = (-((dx * dx + dy * dy) / 14.0)).exp();
1134 let g2 = (-(((dx - 4.0).powi(2) + (dy + 3.0).powi(2)) / 9.0)).exp();
1135 let wave = 0.5 + 0.5 * (dx * 0.45).sin() * (dy * 0.35).cos();
1136 let luma = (25.0 + 180.0 * g1 + 95.0 * g2 + 25.0 * wave * g1).clamp(0.0, 255.0) as u8;
1137 let idx = ((y * w + x) * 4) as usize;
1138 out[idx] = luma;
1139 out[idx + 1] = luma;
1140 out[idx + 2] = luma;
1141 out[idx + 3] = 255;
1142 }
1143 }
1144 out
1145 };
1146
1147 let prev_cx = 40.0;
1148 let prev_cy = 44.0;
1149 let shift_x = 5.35;
1150 let shift_y = -3.65;
1151 let prev = make_img(prev_cx, prev_cy);
1152 let cur = make_img(prev_cx + shift_x, prev_cy + shift_y);
1153
1154 let prev_fu = [(prev_cx + 0.5) / w as f64, 1.0 - (prev_cy + 0.5) / h as f64];
1155 let (new_fu, conf) = track_point_ncc(&prev, &cur, [w, h], prev_fu, 12, 8);
1156 let got_x = new_fu[0] * w as f64 - 0.5;
1157 let got_y = (1.0 - new_fu[1]) * h as f64 - 0.5;
1158 let err = ((got_x - (prev_cx + shift_x)).powi(2) + (got_y - (prev_cy + shift_y)).powi(2)).sqrt();
1159 assert!(conf > 0.95, "expected high NCC confidence, got {conf}");
1160 assert!(
1161 err < 0.5,
1162 "expected sub-pixel NCC error < 0.5 px, got {err:.4} px (got ({got_x:.3}, {got_y:.3}), want ({:.3}, {:.3}))",
1163 prev_cx + shift_x,
1164 prev_cy + shift_y,
1165 );
1166 }
1167
1168 #[test]
1169 fn estimate_planar_homography_recovers_projective_matrix() {
1170 let h_true = [
1171 1.15, -0.18, 0.07,
1172 0.12, 0.94, -0.05,
1173 0.22, -0.14, 1.0,
1174 ];
1175 let src = [
1176 [0.1, 0.15],
1177 [0.85, 0.12],
1178 [0.9, 0.88],
1179 [0.15, 0.82],
1180 [0.5, 0.5],
1181 [0.32, 0.67],
1182 ];
1183 let dst: Vec<[f64; 2]> = src
1184 .iter()
1185 .map(|p| {
1186 let x = h_true[0] * p[0] + h_true[1] * p[1] + h_true[2];
1187 let y = h_true[3] * p[0] + h_true[4] * p[1] + h_true[5];
1188 let w = h_true[6] * p[0] + h_true[7] * p[1] + h_true[8];
1189 [x / w, y / w]
1190 })
1191 .collect();
1192
1193 let est = estimate_planar_homography(&src, &dst).expect("homography");
1194 for i in 0..9 {
1195 assert!(
1196 (est[i] - h_true[i]).abs() < 1e-6,
1197 "entry {i}: got {}, want {}",
1198 est[i],
1199 h_true[i]
1200 );
1201 }
1202 }
1203
1204 #[test]
1205 fn surface_tracker_warps_synthetic_trimesh_over_background() {
1206 // Two-triangle quad covering [0.25..0.5, 0.25..0.5] at ReferenceFrame=0,
1207 // translating to [0.5..0.75, 0.5..0.75] at frame 10!
1208 // Overlay is bright red solid; Input is solid blue.
1209 let src = r#"
1210Composition {
1211 CurrentTime = 10,
1212 RenderRange = { 0, 10 },
1213 GlobalRange = { 0, 10 },
1214 Tools = ordered() {
1215 BG = Background {
1216 Inputs = {
1217 Width = Input { Value = 64, },
1218 Height = Input { Value = 64, },
1219 TopLeftBlue = Input { Value = 1.0, },
1220 TopLeftAlpha = Input { Value = 1.0, },
1221 },
1222 },
1223 OV = Background {
1224 Inputs = {
1225 Width = Input { Value = 64, },
1226 Height = Input { Value = 64, },
1227 TopLeftRed = Input { Value = 1.0, },
1228 TopLeftAlpha = Input { Value = 1.0, },
1229 },
1230 },
1231 ST1Mesh = BezierSpline {
1232 KeyFrames = {
1233 [0] = { 0, Flags = { Linear = true }, Value = FuTriMesh {
1234 Vertices = { 0.25, 0.25, 0.50, 0.25, 0.50, 0.50, 0.25, 0.50 },
1235 Faces = { 0, 1, 2, 0, 2, 3 },
1236 PhotoWeights = { 1, 1, 1, 1 },
1237 } },
1238 [10] = { 1, Flags = { Linear = true }, Value = FuTriMesh {
1239 Vertices = { 0.50, 0.50, 0.75, 0.50, 0.75, 0.75, 0.50, 0.75 },
1240 Faces = { 0, 1, 2, 0, 2, 3 },
1241 PhotoWeights = { 1, 1, 1, 1 },
1242 } },
1243 },
1244 },
1245 ST1 = SurfaceTracker {
1246 Inputs = {
1247 ProcessStage = Input { Value = 2, },
1248 ReferenceFrame = Input { Value = 0, },
1249 OverlayPlacement = Input { Value = 1, },
1250 MeshCustom = Input { SourceOp = "ST1Mesh", Source = "Value", },
1251 WarpableCanvas = Input {
1252 Value = WarpableCanvas {
1253 Corners = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0 }
1254 },
1255 },
1256 Input = Input { SourceOp = "BG", Source = "Output", },
1257 Overlay = Input { SourceOp = "OV", Source = "Output", },
1258 },
1259 },
1260 },
1261}
1262"#;
1263 let comp = Comp::from_fusion_str(src).expect("parse SurfaceTracker comp");
1264 let Ok(mut eng) = Engine::new_headless() else {
1265 return;
1266 };
1267 let st_id = comp.find_node("ST1").unwrap();
1268 let (tex, stats) = eng.evaluate(&comp, st_id, 10.0);
1269 assert!(stats.unsupported_nodes.is_empty());
1270 let rgba = eng.readback_rgba(&tex).expect("readback");
1271
1272 // At frame 10, the warped red quad covers Fusion x in [0.5..0.75], y in [0.5..0.75].
1273 // In top-down pixel coords (64x64): x in [32..48], y in [16..32].
1274 let px = |x: usize, y: usize| -> [u8; 4] {
1275 let i = (y * 64 + x) * 4;
1276 [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
1277 };
1278 let inside = px(40, 24);
1279 let old_pos = px(24, 40);
1280 assert!(inside[0] > 240 && inside[2] < 15, "warped quad center should be red, got {inside:?}");
1281 assert!(old_pos[2] > 240 && old_pos[0] < 15, "original quad location should show blue BG, got {old_pos:?}");
1282
1283 // Midpoint frame 5 should linearly interpolate vertices to [0.375..0.625, 0.375..0.625] -> center (32, 32).
1284 let (tex5, _) = eng.evaluate(&comp, st_id, 5.0);
1285 let rgba5 = eng.readback_rgba(&tex5).expect("readback f5");
1286 let mid_idx = (32 * 64 + 32) * 4;
1287 assert!(
1288 rgba5[mid_idx] > 240 && rgba5[mid_idx + 2] < 15,
1289 "interpolated frame 5 center should be red, got {:?}",
1290 &rgba5[mid_idx..mid_idx + 4]
1291 );
1292 }
1293
1294 #[test]
1295 fn planar_transform_and_planar_tracker_modes_work() {
1296 // Track shifts current frame right by +0.25 in X relative to RefTime=0:
1297 // cur(x, y) -> ref(x - 0.25, y)
1298 // Row-vector 4x4 ToRef has m12 = -0.25, m13 = 0.0.
1299 let src = r#"
1300Composition {
1301 CurrentTime = 1,
1302 RenderRange = { 0, 1 },
1303 GlobalRange = { 0, 1 },
1304 Tools = ordered() {
1305 Patch = Background {
1306 Inputs = {
1307 Width = Input { Value = 64, },
1308 Height = Input { Value = 64, },
1309 TopLeftRed = Input { Value = 1.0, },
1310 TopLeftAlpha = Input { Value = 1.0, },
1311 },
1312 },
1313 MaskRect = RectangleMask {
1314 Inputs = {
1315 Width = Input { Value = 0.25, },
1316 Height = Input { Value = 0.25, },
1317 Center = Input { Value = { 0.25, 0.5 }, },
1318 },
1319 },
1320 Dot = Background {
1321 Inputs = {
1322 Width = Input { Value = 64, },
1323 Height = Input { Value = 64, },
1324 TopLeftGreen = Input { Value = 1.0, },
1325 TopLeftAlpha = Input { Value = 1.0, },
1326 EffectMask = Input { SourceOp = "MaskRect", Source = "Mask", },
1327 },
1328 },
1329 BlueBG = Background {
1330 Inputs = {
1331 Width = Input { Value = 64, },
1332 Height = Input { Value = 64, },
1333 TopLeftBlue = Input { Value = 1.0, },
1334 TopLeftAlpha = Input { Value = 1.0, },
1335 },
1336 },
1337 TrackSpline = BezierSpline {
1338 KeyFrames = {
1339 [0] = { 0, Flags = { Linear = true }, Value = Matrix {
1340 RefTime = 0,
1341 RefSize = { 64, 64 },
1342 RefAspect = { 1, 1 },
1343 ToRef = { [0] = 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
1344 } },
1345 [1] = { 1, Flags = { Linear = true }, Value = Matrix {
1346 RefTime = 0,
1347 RefSize = { 64, 64 },
1348 RefAspect = { 1, 1 },
1349 ToRef = { [0] = 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -0.25, 0, 0, 1 }
1350 } },
1351 },
1352 },
1353 PT_Fwd = Dimension.PlanarTransform {
1354 Inputs = {
1355 Track = Input { SourceOp = "TrackSpline", Source = "Value", },
1356 Input = Input { SourceOp = "Dot", Source = "Output", },
1357 },
1358 },
1359 PT_Inv = Dimension.PlanarTransform {
1360 Inputs = {
1361 Invert = Input { Value = 1, },
1362 Track = Input { SourceOp = "TrackSpline", Source = "Value", },
1363 Input = Input { SourceOp = "PT_Fwd", Source = "Output", },
1364 },
1365 },
1366 PTrk_Track = Dimension.PlanarTracker {
1367 Inputs = {
1368 OperationMode = Input { Value = FuID { "Track" }, },
1369 Track = Input { SourceOp = "TrackSpline", Source = "Value", },
1370 Background = Input { SourceOp = "BlueBG", Source = "Output", },
1371 },
1372 },
1373 PTrk_Steady = Dimension.PlanarTracker {
1374 Inputs = {
1375 OperationMode = Input { Value = FuID { "Steady" }, },
1376 Track = Input { SourceOp = "TrackSpline", Source = "Value", },
1377 Background = Input { SourceOp = "PT_Fwd", Source = "Output", },
1378 },
1379 },
1380 PTrk_CornerPin = Dimension.PlanarTracker {
1381 Inputs = {
1382 OperationMode = Input { Value = FuID { "CornerPin" }, },
1383 Track = Input { SourceOp = "TrackSpline", Source = "Value", },
1384 Background = Input { SourceOp = "BlueBG", Source = "Output", },
1385 CornerPin1 = Input { SourceOp = "Patch", Source = "Output", },
1386 CornerPinBottomLeft = Input { Value = { 0.1, 0.25 }, },
1387 CornerPinBottomRight = Input { Value = { 0.4, 0.25 }, },
1388 CornerPinTopRight = Input { Value = { 0.4, 0.75 }, },
1389 CornerPinTopLeft = Input { Value = { 0.1, 0.75 }, },
1390 },
1391 },
1392 },
1393}
1394"#;
1395 let comp = Comp::from_fusion_str(src).expect("parse Planar comp");
1396 let Ok(mut eng) = Engine::new_headless() else {
1397 return;
1398 };
1399 let px_at = |e: &mut Engine, name: &str, x: usize, y: usize| -> [u8; 4] {
1400 let (tex, stats) = e.evaluate(&comp, comp.find_node(name).unwrap(), 1.0);
1401 assert!(stats.unsupported_nodes.is_empty(), "{name} had unsupported: {:?}", stats.unsupported_nodes);
1402 let rgba = e.readback_rgba(&tex).unwrap();
1403 let i = (y * 64 + x) * 4;
1404 [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
1405 };
1406
1407 // Dot was centered at x=0.25 (px 16). PT_Fwd shifts it by +0.25 to x=0.50 (px 32).
1408 let fwd_shifted = px_at(&mut eng, "PT_Fwd", 32, 32);
1409 let fwd_old = px_at(&mut eng, "PT_Fwd", 16, 32);
1410 assert!(fwd_shifted[1] > 240, "PT_Fwd should move green dot to x=32, got {fwd_shifted:?}");
1411 assert!(fwd_old[1] < 15, "PT_Fwd old x=16 should be transparent, got {fwd_old:?}");
1412
1413 // PT_Inv inverts PT_Fwd back to x=0.25 (px 16).
1414 let inv_restored = px_at(&mut eng, "PT_Inv", 16, 32);
1415 assert!(inv_restored[1] > 240, "PT_Inv should restore green dot to x=16, got {inv_restored:?}");
1416
1417 // PlanarTracker Track mode passes through BlueBG.
1418 let trk = px_at(&mut eng, "PTrk_Track", 32, 32);
1419 assert!(trk[2] > 240, "PlanarTracker Track should pass through blue BG, got {trk:?}");
1420
1421 // PlanarTracker Steady mode locks PT_Fwd back to RefTime x=0.25 (px 16).
1422 let steady = px_at(&mut eng, "PTrk_Steady", 16, 32);
1423 assert!(steady[1] > 240, "PlanarTracker Steady should stabilize green dot back to x=16, got {steady:?}");
1424
1425 // PlanarTracker CornerPin places red quad [0.1..0.4] shifted by +0.25 -> [0.35..0.65] (center x=32) over blue BG.
1426 let cp_inside = px_at(&mut eng, "PTrk_CornerPin", 32, 32);
1427 let cp_outside = px_at(&mut eng, "PTrk_CornerPin", 8, 32);
1428 assert!(cp_inside[0] > 240 && cp_inside[2] < 15, "CornerPin interior should be red, got {cp_inside:?}");
1429 assert!(cp_outside[2] > 240 && cp_outside[0] < 15, "CornerPin exterior should be blue BG, got {cp_outside:?}");
1430 }
1431}
crates/model/src/comp.rs+8-1
......@@ -83,6 +83,11 @@ pub fn is_supported_tool(kind: &str) -> bool {
8383 | "PipeRouter"
8484 | "Fuse.Wireless"
8585 | "Tracker"
86 | "SurfaceTracker"
87 | "Dimension.PlanarTracker"
88 | "PlanarTracker"
89 | "Dimension.PlanarTransform"
90 | "PlanarTransform"
8691 | "MacroOperator"
8792 | "GroupOperator"
8893 | "TimeStretcher"
......@@ -610,7 +615,9 @@ impl Comp {
610615
611616pub fn default_main_input_port(kind: &str) -> &'static str {
612617 match kind {
613 "Merge" | "Dissolve" | "ChannelBoolean" => "Background",
618 "Merge" | "Dissolve" | "ChannelBoolean" | "Dimension.PlanarTracker" | "PlanarTracker" => {
619 "Background"
620 }
614621 "BitmapMask" => "Image",
615622 "Switch" => "Input0",
616623 "Fuse.Switch" | "Fuse.SwitchElse" => "Input1",
scripts/gen_compatibility.py+5-4
......@@ -210,7 +210,10 @@ TOOL_METADATA: Sequence[ToolMeta] = (
210210 ToolMeta("Fuse.SwitchElse", "Time, Routing & Utility", "Unit tests", "0.0%", "—"),
211211 ToolMeta("PipeRouter", "Time, Routing & Utility", "Suite comps", "0.0%", "—"),
212212 ToolMeta("Fuse.Wireless", "Time, Routing & Utility", "Suite comps", "0.0%", "—"),
213 ToolMeta("Tracker", "Time, Routing & Utility", "Suite comps", "0.0%", "Live optical tracking not implemented; evaluates baked `TrackerModifier` paths."),
213 ToolMeta("Tracker", "Time, Routing & Utility", "Suite comps", "0.0%", "Evaluates baked `TrackerModifier` paths; live NCC point & planar homography API in `engine::tracker`."),
214 ToolMeta("SurfaceTracker", "Time, Routing & Utility", "Suite comps", "0.1%–0.5%", "GPU 2D triangle-mesh warp (`FuTriMesh` + `WarpableCanvas`); live NCC & homography API in `engine::tracker`."),
215 ToolMeta("Dimension.PlanarTracker", "Time, Routing & Utility", "Unit tests", "0.0%", "Evaluates `Track` / `CornerPin` / `Steady` / `Stabilize` modes from baked `Matrix` tracks.", aliases=("PlanarTracker",)),
216 ToolMeta("Dimension.PlanarTransform", "Transform, Warp & Framing", "Unit tests", "0.0%", "Applies projective 3×3 `ToRef` homography splines (`Invert`, `Blend`, `EffectMask`).", aliases=("PlanarTransform",)),
214217 ToolMeta("MacroOperator", "Time, Routing & Utility", "Suite comps", "0.0%", "Internal subgraph is read-only in interactive Flow."),
215218 ToolMeta("GroupOperator", "Time, Routing & Utility", "Suite comps", "0.0%", "Internal subgraph is read-only in interactive Flow."),
216219 ToolMeta("Custom", "Time, Routing & Utility", "Suite comps", "0.1%–0.6%", "—"),
......@@ -248,9 +251,7 @@ class UnsupportedMeta:
248251
249252# Curated notes for prominent real-world unsupported / OFX / Resolve tools.
250253UNSUPPORTED_NOTES: Sequence[UnsupportedMeta] = (
251 UnsupportedMeta("SurfaceTracker", "Preserved lossless on save; passes through main image input in Flow.", 7),
252254 UnsupportedMeta("MagicMask", "Preserved lossless on save; passes through main image input in Flow.", 7),
253 UnsupportedMeta("PlanarTracker", "Preserved lossless on save; passes through main image input in Flow.", 7),
254255)
255256
256257
......@@ -571,7 +572,7 @@ def build_markdown(
571572 fusion_builtin_total = 378
572573 non_stock_builtin = {
573574 "GroupOperator", "MacroOperator", "PipeRouter", "InvertColor",
574 "PolylineStroke", "Multistroke", "OpticalFlow", "pDrag",
575 "PolylineStroke", "Multistroke", "OpticalFlow", "PlanarTracker", "PlanarTransform", "pDrag",
575576 "Fuse.AlphaWeightedNoise", "Fuse.CheckerPieceGenerator", "Fuse.Colorize",
576577 "Fuse.Cryptomatte", "Fuse.Crystallize", "Fuse.HexagonTiles", "Fuse.KScope", "Fuse.Outline",
577578 "Fuse.Switch", "Fuse.SwitchElse", "Fuse.XGlow", "Fuse.XfChroma",