1pub mod comp;
2pub mod edit;
3pub mod expr;
4pub mod lua_value;
5pub mod spline;
6
7pub use comp::{
8 BitDepth, ClipSpec, ClsEntry, Comp, InputBinding, Node, NodeId, ParamValue, PortRole, SaverSpec,
9 default_main_input_port, is_supported_tool,
10};
11pub use edit::{CompHistory, DEFAULT_MAX_HISTORY};
12pub use expr::ExprEngine;
13pub use lua_value::{LuaKey, LuaTable, LuaValue, ParseError, parse_lua};
14pub use spline::{BezierSpline, Gradient, GradientStop, HandleMode, KeyFlags, Keyframe, PolyPath, PolyPoint};
15
16#[cfg(test)]
17mod tests {
18 use super::*;
19 use std::path::Path;
20
21 #[test]
22 fn parses_all_337_real_fusion_comps() {
23 let mut paths = Vec::new();
24 fn collect(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
25 let Ok(rd) = std::fs::read_dir(dir) else { return };
26 for entry in rd.flatten() {
27 let p = entry.path();
28 if p.is_dir() {
29 collect(&p, out);
30 } else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("comp")) {
31 out.push(p);
32 }
33 }
34 }
35 collect(Path::new("/Users/clo/dev/compositor/private/samples"), &mut paths);
36 collect(Path::new("/Volumes/Project/trees/fusion"), &mut paths);
37 paths.sort();
38 assert!(!paths.is_empty(), "expected sample .comp files");
39
40 let mut failures = Vec::new();
41 let mut total_nodes = 0usize;
42 let mut total_splines = 0usize;
43 for p in &paths {
44 match Comp::from_fusion_file(p) {
45 Ok(comp) => {
46 total_nodes += comp.nodes.len();
47 total_splines += comp.splines.len();
48 }
49 Err(e) => failures.push(format!("{}: {e}", p.display())),
50 }
51 }
52 assert!(
53 failures.is_empty(),
54 "failed to parse {}/{} comps:\n{}",
55 failures.len(),
56 paths.len(),
57 failures.join("\n")
58 );
59 eprintln!(
60 "Parsed {}/{} real .comp files ({total_nodes} nodes, {total_splines} splines) cleanly!",
61 paths.len(),
62 paths.len()
63 );
64 }
65
66 #[test]
67 fn evaluates_20_falling_splines_and_expressions() {
68 let comp = Comp::from_fusion_file("/Volumes/Project/trees/fusion/20_falling.comp")
69 .expect("load 20_falling.comp");
70 let expr = ExprEngine::new();
71 assert_eq!(comp.width, 1920);
72 assert_eq!(comp.height, 1080);
73
74 let ts = comp.node(comp.find_node("TimeStretcher1_2").unwrap());
75 assert_eq!(comp.eval_number(ts, "SourceTime", 2200.0, 0.0, &expr), 2199.0);
76
77 let noise = comp.node(comp.find_node("Noise_3").unwrap());
78 assert_eq!(comp.eval_number(noise, "Seethe", 2200.0, 0.0, &expr), 733.0 * 42.0);
79
80 let merge19 = comp.node(comp.find_node("Merge19").unwrap());
81 let p0 = comp.eval_point(merge19, "Center", 2318.0, [0.5, 0.5], &expr);
82 let p1 = comp.eval_point(merge19, "Center", 2361.0, [0.5, 0.5], &expr);
83 assert!((p0[0] - p1[0]).abs() + (p0[1] - p1[1]).abs() > 1e-4);
84 }
85
86 #[test]
87 fn roundtrips_all_337_real_fusion_comps() {
88 let mut paths = Vec::new();
89 fn collect(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
90 let Ok(rd) = std::fs::read_dir(dir) else { return };
91 for entry in rd.flatten() {
92 let p = entry.path();
93 if p.is_dir() {
94 collect(&p, out);
95 } else if p
96 .extension()
97 .and_then(|e| e.to_str())
98 .is_some_and(|e| e.eq_ignore_ascii_case("comp"))
99 {
100 out.push(p);
101 }
102 }
103 }
104 collect(Path::new("/Users/clo/dev/compositor/private/samples"), &mut paths);
105 collect(Path::new("/Volumes/Project/trees/fusion"), &mut paths);
106 paths.sort();
107 assert!(!paths.is_empty(), "expected sample .comp files");
108
109 let mut failures = Vec::new();
110 for p in &paths {
111 let orig = match Comp::from_fusion_file(p) {
112 Ok(c) => c,
113 Err(e) => {
114 failures.push(format!("{}: load error: {e}", p.display()));
115 continue;
116 }
117 };
118 let serialized = orig.to_fusion_string();
119 let reloaded = match Comp::from_fusion_str(&serialized) {
120 Ok(c) => c,
121 Err(e) => {
122 failures.push(format!("{}: re-parse error: {e}", p.display()));
123 continue;
124 }
125 };
126
127 if orig.width != reloaded.width
128 || orig.height != reloaded.height
129 || (orig.fps - reloaded.fps).abs() > 1e-6
130 || orig.depth_full != reloaded.depth_full
131 || orig.render_range != reloaded.render_range
132 || orig.global_range != reloaded.global_range
133 {
134 failures.push(format!(
135 "{}: metadata mismatch: orig=({}x{} @{} {:?} rr={:?} gr={:?}) vs reloaded=({}x{} @{} {:?} rr={:?} gr={:?})",
136 p.display(),
137 orig.width, orig.height, orig.fps, orig.depth_full, orig.render_range, orig.global_range,
138 reloaded.width, reloaded.height, reloaded.fps, reloaded.depth_full, reloaded.render_range, reloaded.global_range,
139 ));
140 continue;
141 }
142
143 if orig.nodes.len() != reloaded.nodes.len() {
144 failures.push(format!(
145 "{}: node count mismatch: {} vs {}",
146 p.display(),
147 orig.nodes.len(),
148 reloaded.nodes.len()
149 ));
150 continue;
151 }
152
153 let orig_names: std::collections::HashSet<String> =
154 orig.node_by_name.keys().cloned().collect();
155 let rel_names: std::collections::HashSet<String> =
156 reloaded.node_by_name.keys().cloned().collect();
157
158 let mut node_err = None;
159 for (a, b) in orig.nodes.iter().zip(reloaded.nodes.iter()) {
160 if a.name != b.name
161 || a.kind != b.kind
162 || a.bypassed != b.bypassed
163 || a.internal != b.internal
164 || (a.pos[0] - b.pos[0]).abs() > 1e-3
165 || (a.pos[1] - b.pos[1]).abs() > 1e-3
166 {
167 node_err = Some(format!(
168 "{}: node mismatch {} vs {} (kind {:?}/{:?}, bypassed {}/{}, pos {:?}/{:?})",
169 p.display(),
170 a.name, b.name, a.kind, b.kind, a.bypassed, b.bypassed, a.pos, b.pos
171 ));
172 break;
173 }
174 let conns_a = a.image_connections(&orig_names);
175 let conns_b = b.image_connections(&rel_names);
176 if conns_a != conns_b {
177 node_err = Some(format!(
178 "{}: image_connections mismatch on {}: {:?} vs {:?}",
179 p.display(),
180 a.name, conns_a, conns_b
181 ));
182 break;
183 }
184 }
185 if let Some(err) = node_err {
186 failures.push(err);
187 continue;
188 }
189
190 if orig.splines.len() != reloaded.splines.len() {
191 failures.push(format!(
192 "{}: spline count mismatch: {} vs {}",
193 p.display(),
194 orig.splines.len(),
195 reloaded.splines.len()
196 ));
197 continue;
198 }
199 for (sname, sp_a) in &orig.splines {
200 let Some(sp_b) = reloaded.splines.get(sname) else {
201 failures.push(format!("{}: missing spline {sname}", p.display()));
202 break;
203 };
204 if sp_a.keyframes.is_empty() && sp_b.keyframes.is_empty() {
205 continue;
206 }
207 let t0 = sp_a.keyframes.first().map(|k| k.time).unwrap_or(0.0);
208 let t1 = sp_a.keyframes.last().map(|k| k.time).unwrap_or(0.0);
209 for step in 0..=4 {
210 let t = t0 + (t1 - t0) * (step as f64 / 4.0);
211 let va = sp_a.eval(t);
212 let vb = sp_b.eval(t);
213 let diff = (va - vb).abs();
214 if !(va.is_nan() && vb.is_nan()) && diff > 1e-5 * va.abs().max(1.0) {
215 failures.push(format!(
216 "{}: spline {sname} @ t={t} mismatch: {va} vs {vb}",
217 p.display()
218 ));
219 break;
220 }
221 }
222 }
223 }
224
225 assert!(
226 failures.is_empty(),
227 "roundtrip failed on {}/{} comps:\n{}",
228 failures.len(),
229 paths.len(),
230 failures.iter().take(20).cloned().collect::<Vec<_>>().join("\n")
231 );
232 eprintln!("Losslessly roundtripped {}/{} real .comp files!", paths.len(), paths.len());
233 }
234
235 #[test]
236 fn preserves_unknown_nodes_and_applies_edits_with_temp_backup() {
237 let src = r#"Composition {
238 CurrentTime = 10,
239 RenderRange = { 0, 100 },
240 GlobalRange = { 0, 100 },
241 Prefs = {
242 Comp = {
243 FrameFormat = {
244 Width = 1920,
245 Height = 1080,
246 Rate = 24,
247 DepthFull = 3,
248 },
249 },
250 },
251 Tools = {
252 BG1 = Background {
253 Inputs = {
254 Width = Input { Value = 1920, },
255 Height = Input { Value = 1080, },
256 TopLeftRed = Input { Value = 0.25, },
257 },
258 ViewInfo = OperatorInfo { Pos = { 100, 50 } },
259 },
260 OverlayBG = Background {
261 Inputs = {
262 TopLeftGreen = Input { Value = 0.8, },
263 },
264 ViewInfo = OperatorInfo { Pos = { 100, 200 } },
265 },
266 Mask1 = EllipseMask {
267 ViewInfo = OperatorInfo { Pos = { 250, 250 } },
268 },
269 SurfaceTracker1 = SurfaceTracker {
270 Inputs = {
271 Source = Input {
272 SourceOp = "BG1",
273 Source = "Output",
274 },
275 Overlay = Input {
276 SourceOp = "OverlayBG",
277 Source = "Output",
278 },
279 TrackingMask = Input {
280 SourceOp = "Mask1",
281 Source = "Mask",
282 },
283 MeshBlob = Input {
284 Value = TrackingMesh {
285 Vertices = { 0.1, 0.2, 0.3, 0.4 },
286 Meta = "line1\nline2\"quoted\"\\slash",
287 },
288 },
289 },
290 UserControls = ordered() {
291 CustomGain = {
292 INP_Default = 1.5,
293 LINKID_DataType = "Number",
294 },
295 },
296 ViewInfo = OperatorInfo { Pos = { 300, 100 }, Flags = { ShowName = true } },
297 },
298 BC1 = BrightnessContrast {
299 Inputs = {
300 Input = Input {
301 SourceOp = "SurfaceTracker1",
302 Source = "Output",
303 },
304 Gain = Input {
305 SourceOp = "BC1Gain",
306 Source = "Value",
307 },
308 },
309 ViewInfo = OperatorInfo { Pos = { 500, 100 } },
310 },
311 BC1Gain = BezierSpline {
312 SplineColor = { Red = 255, Green = 128, Blue = 0 },
313 KeyFrames = {
314 [0] = { 1, RH = { 10, 1 }, Flags = { Linear = true } },
315 [30] = { 2, LH = { 20, 2 }, Flags = { Linear = true } },
316 },
317 },
318 },
319}"#;
320
321 let mut comp = Comp::from_fusion_str(src).expect("parse synthetic comp");
322 assert!(!is_supported_tool("SurfaceAlembicMesh"));
323 assert!(is_supported_tool("MagicMask"));
324 assert!(is_supported_tool("AutoMatte"));
325 assert!(is_supported_tool("SurfaceTracker"));
326 assert!(is_supported_tool("BrightnessContrast"));
327 assert!(is_supported_tool("Renderer3D"));
328
329 // Verify unknown node connections surface all 3 ports with proper roles
330 let st_id = comp.find_node("SurfaceTracker1").expect("SurfaceTracker1");
331 let names: std::collections::HashSet<String> = comp.node_by_name.keys().cloned().collect();
332 let conns = comp.node(st_id).image_connections(&names);
333 assert_eq!(
334 conns,
335 vec![
336 ("Overlay".to_owned(), "OverlayBG".to_owned(), PortRole::Foreground),
337 ("Source".to_owned(), "BG1".to_owned(), PortRole::Background),
338 ("TrackingMask".to_owned(), "Mask1".to_owned(), PortRole::Mask),
339 ]
340 );
341
342 // Mutate a different node's position, bypass, wire, param, and a BezierSpline keyframe
343 let bc_id = comp.find_node("BC1").expect("BC1");
344 let bg_id = comp.find_node("BG1").expect("BG1");
345 {
346 let bc = comp.node_mut(bc_id);
347 bc.pos = [650.0, 125.0];
348 bc.bypassed = true;
349 bc.inputs.insert(
350 "Gamma".to_owned(),
351 InputBinding {
352 value: Some(ParamValue::Number(1.35)),
353 source_op: None,
354 source_output: None,
355 expression: None,
356 },
357 );
358 }
359 comp.connect(bg_id, bc_id, "EffectMask");
360 comp.splines
361 .get_mut("BC1Gain")
362 .unwrap()
363 .keyframes
364 .push(Keyframe::new(60.0, 3.5));
365
366 // Save to a fresh temp directory twice
367 let unique_dir = std::env::temp_dir().join(format!(
368 "fission_test_save_{}_{}",
369 std::process::id(),
370 std::time::SystemTime::now()
371 .duration_since(std::time::UNIX_EPOCH)
372 .unwrap()
373 .as_nanos()
374 ));
375 std::fs::create_dir_all(&unique_dir).unwrap();
376 let comp_path = unique_dir.join("test_shot.comp");
377
378 // First save: file does not exist yet -> no backup
379 let bak1 = comp.save_to_file(&comp_path).expect("first save");
380 assert!(bak1.is_none());
381
382 // Second save: file exists -> backup goes to temp_dir/fission-backups/, NOT next to comp
383 let bak2 = comp.save_to_file(&comp_path).expect("second save");
384 let bak2_path = bak2.expect("expected backup path on second save");
385 assert!(bak2_path.exists());
386 assert_eq!(
387 bak2_path.parent().unwrap(),
388 std::env::temp_dir().join("fission-backups")
389 );
390 // Ensure no .bak file next to test_shot.comp
391 let siblings: Vec<_> = std::fs::read_dir(&unique_dir)
392 .unwrap()
393 .flatten()
394 .map(|e| e.file_name().to_string_lossy().into_owned())
395 .collect();
396 assert_eq!(siblings, vec!["test_shot.comp".to_owned()]);
397
398 // Reload and verify edits persisted AND SurfaceTracker survived 100% intact
399 let reloaded = Comp::from_fusion_file(&comp_path).expect("reload saved comp");
400 let r_bc = reloaded.node(reloaded.find_node("BC1").unwrap());
401 assert_eq!(r_bc.pos, [650.0, 125.0]);
402 assert!(r_bc.bypassed);
403 assert_eq!(r_bc.static_number("Gamma"), Some(1.35));
404 assert_eq!(r_bc.connected_node("EffectMask"), Some("BG1"));
405
406 let r_sp = reloaded.splines.get("BC1Gain").expect("BC1Gain spline");
407 assert_eq!(r_sp.keyframes.len(), 3);
408 assert!((r_sp.eval(60.0) - 3.5).abs() < 1e-6);
409
410 let r_st = reloaded.node(reloaded.find_node("SurfaceTracker1").unwrap());
411 assert_eq!(r_st.kind, "SurfaceTracker");
412 let r_names: std::collections::HashSet<String> =
413 reloaded.node_by_name.keys().cloned().collect();
414 assert_eq!(r_st.image_connections(&r_names), conns);
415 // Verify custom nested MeshBlob and UserControls survived verbatim
416 let mesh = r_st
417 .raw
418 .get_table("Inputs")
419 .and_then(|i| i.get_table("MeshBlob"))
420 .and_then(|m| m.get_table("Value"))
421 .expect("MeshBlob Value");
422 assert_eq!(mesh.tag.as_deref(), Some("TrackingMesh"));
423 assert_eq!(mesh.get_str("Meta"), Some("line1\nline2\"quoted\"\\slash"));
424 assert!(r_st.raw.get_table("UserControls").is_some());
425 // Verify unedited UserControl default was NOT injected into raw Inputs
426 assert!(
427 r_st.raw
428 .get_table("Inputs")
429 .and_then(|i| i.get("CustomGain"))
430 .is_none()
431 );
432
433 let _ = std::fs::remove_dir_all(&unique_dir);
434 let _ = std::fs::remove_file(&bak2_path);
435 }
436
437 #[test]
438 fn saver_spec_frame_paths() {
439 let make = |filename: &str| SaverSpec {
440 node_id: NodeId(0),
441 name: "Saver1".to_owned(),
442 upstream: None,
443 filename: filename.to_owned(),
444 range: [0, 100],
445 sequence_start: None,
446 };
447
448 assert_eq!(
449 make("/renders/foo_0000.png").frame_path(42),
450 std::path::PathBuf::from("/renders/foo_0042.png")
451 );
452 assert_eq!(
453 make("/renders/0000.png").frame_path(7),
454 std::path::PathBuf::from("/renders/0007.png")
455 );
456 assert_eq!(
457 make("/renders/render.png").frame_path(12),
458 std::path::PathBuf::from("/renders/render0012.png")
459 );
460 assert_eq!(
461 make("foo_000000.exr").frame_path(1001),
462 std::path::PathBuf::from("foo_001001.exr")
463 );
464
465 let comp = Comp::from_fusion_file("/Volumes/Project/trees/fusion/20_falling.comp")
466 .expect("load 20_falling.comp");
467 let savers = comp.savers();
468 assert!(!savers.is_empty(), "expected Saver in 20_falling.comp");
469 let s = &savers[0];
470 assert_eq!(s.name, "Saver1");
471 assert!(s.upstream.is_some());
472 assert_eq!(s.range, comp.render_range);
473 assert_eq!(
474 s.frame_path(2130),
475 std::path::PathBuf::from("/Volumes/Project/trees/FusionRender/2130.png")
476 );
477 }
478}