1use super::remove_tools_recursive;
2use crate::comp::{Comp, InputBinding, NodeId, ParamValue, ensure_table_mut, find_raw_tool_mut, param_value_to_lua};
3use crate::lua_value::{LuaKey, LuaTable, LuaValue};
4use crate::spline::{BezierSpline, Keyframe};
5use std::collections::HashSet;
6
7/// Keyframe times closer than this are the same keyframe (matches the Inspector's `keyframe_state`).
8const KEYFRAME_EPS: f64 = 1e-4;
9
10
11impl Comp {
12 pub fn set_keyframe(
13 &mut self,
14 node: NodeId,
15 input: &str,
16 frame: f64,
17 value: f64,
18 ) -> Result<String, String> {
19 if node.0 >= self.nodes.len() {
20 return Err(format!("invalid node id {}", node.0));
21 }
22 if !frame.is_finite() || !value.is_finite() {
23 return Err("keyframe frame and value must be finite numbers".to_owned());
24 }
25
26 let existing_spline = self.nodes[node.0]
27 .inputs
28 .get(input)
29 .and_then(|b| b.source_op.clone())
30 .filter(|op| self.splines.contains_key(op));
31
32 let spline_name = if let Some(sp_name) = existing_spline {
33 let sp = self.splines.get_mut(&sp_name).expect("spline exists");
34 upsert_keyframe(sp, frame, value);
35 sp_name
36 } else {
37 let hint = format!("{}{}", self.nodes[node.0].name, input);
38 let sp_name = self.generate_unique_name("BezierSpline", Some(&hint));
39 let color = default_spline_color(&sp_name);
40 let spline = BezierSpline {
41 name: sp_name.clone(),
42 color,
43 keyframes: vec![Keyframe::new(frame, value)],
44 };
45 self.splines.insert(sp_name.clone(), spline);
46
47 let n = &mut self.nodes[node.0];
48 let entry = n.inputs.entry(input.to_owned()).or_insert(InputBinding {
49 value: None,
50 source_op: None,
51 source_output: None,
52 expression: None,
53 });
54 entry.source_op = Some(sp_name.clone());
55 entry.source_output = Some("Value".to_owned());
56
57 let in_tbl = ensure_table_mut(&mut n.raw, "Inputs", None);
58 let port_tbl = ensure_table_mut(in_tbl, input, Some("Input"));
59 port_tbl.set(
60 LuaKey::Str("SourceOp".to_owned()),
61 LuaValue::String(sp_name.clone()),
62 );
63 port_tbl.set(
64 LuaKey::Str("Source".to_owned()),
65 LuaValue::String("Value".to_owned()),
66 );
67
68 sp_name
69 };
70
71 self.revision += 1;
72 Ok(spline_name)
73 }
74
75 /// Removes the keyframe at `frame` from `spline_name`. Returns `true` if a keyframe was deleted.
76 /// Deleting a spline's last keyframe removes the spline and leaves every input it drove with
77 /// that keyframe's value as a static `Value`.
78 pub fn delete_keyframe(&mut self, spline_name: &str, frame: f64) -> bool {
79 let Some(sp) = self.splines.get_mut(spline_name) else {
80 return false;
81 };
82 let Some(pos) = sp
83 .keyframes
84 .iter()
85 .position(|kf| (kf.time - frame).abs() < KEYFRAME_EPS)
86 else {
87 return false;
88 };
89 let removed = sp.keyframes.remove(pos);
90 if sp.keyframes.is_empty() {
91 self.splines.remove(spline_name);
92 let value = ParamValue::Number(removed.value);
93 for node in &mut self.nodes {
94 for (port, binding) in &mut node.inputs {
95 if binding.source_op.as_deref() != Some(spline_name) {
96 continue;
97 }
98 binding.source_op = None;
99 binding.source_output = None;
100 binding.value = Some(value.clone());
101 freeze_raw_input(&mut node.raw, port, &value);
102 }
103 }
104
105 // Modifiers keep no node `raw`, so their links are fixed in the in-memory model and in
106 // `raw_root` by name.
107 let mut frozen: Vec<(String, String)> = Vec::new();
108 let modifier_inputs = self
109 .shakes
110 .iter_mut()
111 .map(|(name, m)| (name, &mut m.inputs))
112 .chain(self.expression_modifiers.iter_mut().map(|(name, m)| (name, &mut m.inputs)));
113 for (name, inputs) in modifier_inputs {
114 for (port, binding) in inputs {
115 if binding.source_op.as_deref() == Some(spline_name) {
116 binding.source_op = None;
117 binding.source_output = None;
118 binding.value = Some(value.clone());
119 frozen.push((name.clone(), port.clone()));
120 }
121 }
122 }
123 for (name, pp) in &mut self.poly_paths {
124 if pp.displacement_op.as_deref() == Some(spline_name) {
125 pp.displacement_op = None;
126 pp.displacement_value = removed.value;
127 frozen.push((name.clone(), "Displacement".to_owned()));
128 }
129 }
130 if let Some(tools) = self.raw_root.as_mut().and_then(|r| r.get_table_mut("Tools")) {
131 for (name, port) in &frozen {
132 if let Some(tool) = find_raw_tool_mut(tools, name) {
133 freeze_raw_input(tool, port, &value);
134 }
135 }
136 remove_tools_recursive(tools, &HashSet::from([spline_name.to_owned()]));
137 }
138 }
139 self.revision += 1;
140 true
141 }
142}
143
144/// Replaces the link on `tool.Inputs.<port>` with the static `value`.
145fn freeze_raw_input(tool: &mut LuaTable, port: &str, value: &ParamValue) {
146 let input = ensure_table_mut(ensure_table_mut(tool, "Inputs", None), port, Some("Input"));
147 input.remove(&LuaKey::Str("SourceOp".to_owned()));
148 input.remove(&LuaKey::Str("Source".to_owned()));
149 input.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(value));
150}
151
152fn upsert_keyframe(spline: &mut BezierSpline, frame: f64, value: f64) {
153 if let Some(existing) = spline
154 .keyframes
155 .iter_mut()
156 .find(|kf| (kf.time - frame).abs() < KEYFRAME_EPS)
157 {
158 // Handles are absolute coordinates, so they travel with the key.
159 let (dt, dv) = (frame - existing.time, value - existing.value);
160 existing.time = frame;
161 existing.value = value;
162 for handle in [&mut existing.lh, &mut existing.rh].into_iter().flatten() {
163 handle[0] += dt;
164 handle[1] += dv;
165 }
166 } else {
167 spline.keyframes.push(Keyframe::new(frame, value));
168 spline.sort();
169 }
170}
171
172fn default_spline_color(name: &str) -> [u8; 3] {
173 // Deterministic vivid Fusion-like spline palette based on name hash.
174 const PALETTE: &[[u8; 3]] = &[
175 [255, 128, 0],
176 [102, 204, 255],
177 [170, 238, 102],
178 [255, 102, 170],
179 [204, 153, 255],
180 [255, 221, 85],
181 ];
182 let hash = name
183 .bytes()
184 .fold(0usize, |acc, b| acc.wrapping_mul(31).wrapping_add(b as usize));
185 PALETTE[hash % PALETTE.len()]
186}
187
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192 use crate::edit::tests::sample_comp;
193
194 #[test]
195 fn updating_a_keyframe_moves_its_handles_with_it() {
196 let mut comp = sample_comp();
197 let bc = comp.find_node("BC1").unwrap();
198 comp.splines.get_mut("BC1Gain").unwrap().keyframes[1].lh = Some([20.0, 1.5]);
199 comp.splines.get_mut("BC1Gain").unwrap().keyframes[1].rh = Some([40.0, 2.5]);
200 comp.set_keyframe(bc, "Gain", 30.0, 3.0).unwrap();
201 let kf = &comp.splines["BC1Gain"].keyframes[1];
202 assert_eq!((kf.value, kf.lh, kf.rh), (3.0, Some([20.0, 2.5]), Some([40.0, 3.5])));
203 }
204
205 #[test]
206 fn deleting_the_last_keyframe_keeps_its_value_as_a_static_input() {
207 let mut comp = sample_comp();
208 let bc = comp.find_node("BC1").unwrap();
209 // Within the shared 1e-4 tolerance.
210 assert!(comp.delete_keyframe("BC1Gain", 0.00005));
211 assert!(comp.delete_keyframe("BC1Gain", 30.0));
212 assert!(!comp.splines.contains_key("BC1Gain"));
213 assert_eq!(comp.node(bc).connected_node("Gain"), None);
214 assert_eq!(comp.node(bc).static_number("Gain"), Some(2.0));
215
216 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
217 let r = saved.node(saved.find_node("BC1").unwrap());
218 assert_eq!(r.static_number("Gain"), Some(2.0));
219 assert!(!saved.to_fusion_string().contains("BC1Gain"));
220 }
221
222 #[test]
223 fn deleting_the_last_keyframe_unlinks_modifiers_that_used_the_spline() {
224 let src = r#"Composition { Tools = ordered() {
225 S = BezierSpline { KeyFrames = { [0] = { 3, Flags = { Linear = true } } } },
226 Sh = Shake { Inputs = { Amplitude = Input { SourceOp = "S", Source = "Value", }, }, },
227 E = Expression { Inputs = {
228 n1 = Input { SourceOp = "S", Source = "Value", },
229 NumberExpression = Input { Value = "n1", },
230 }, },
231 P = PolyPath { Inputs = { Displacement = Input { SourceOp = "S", Source = "Value", }, }, },
232 N = Transform { Inputs = { Size = Input { SourceOp = "E", Source = "NumberResult", }, }, },
233 } }"#;
234 let mut comp = Comp::from_fusion_str(src).unwrap();
235 assert!(comp.delete_keyframe("S", 0.0));
236 assert_eq!(comp.shakes["Sh"].inputs["Amplitude"].source_op, None);
237 assert_eq!(comp.expression_modifiers["E"].inputs["n1"].source_op, None);
238 assert_eq!(comp.poly_paths["P"].displacement_op, None);
239 assert_eq!(comp.poly_paths["P"].displacement_value, 3.0);
240
241 let text = comp.to_fusion_string();
242 assert!(!text.contains("\"S\""), "{text}");
243 let saved = Comp::from_fusion_str(&text).unwrap();
244 assert_eq!(saved.shakes["Sh"].inputs["Amplitude"].value, Some(ParamValue::Number(3.0)));
245 assert_eq!(saved.poly_paths["P"].displacement_value, 3.0);
246 let n = saved.node(saved.find_node("N").unwrap());
247 assert_eq!(saved.eval_number(n, "Size", 0.0, -1.0, &crate::expr::ExprEngine::new()), 3.0);
248 }
249}