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}