authoravatarclover caruso<git@paperclover.net>2026-11-30 21:05:52-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 21:16:22-08:00
logb3672ee106de333dc201bbe7e1d8652394308ab5
treedf2db1f23f738a6bedaa70e8dded1e3fc4a5026a
parentdc58400a09b01759dbca8cbdc58df0c74cd0c41f
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Fix Lua pcall sandbox/isolation, multi-input group save, expr blowup, rename/delete/defaults P0s

Assisted-by: claude-sonnet-5.5

10 files changed, 519 insertions(+), 107 deletions(-)

crates/model/src/comp.rs+9-1
......@@ -600,9 +600,17 @@ impl Comp {
600600
601601pub fn default_main_input_port(kind: &str) -> &'static str {
602602 match kind {
603 "Merge" => "Background",
603 "Merge" | "Dissolve" | "ChannelBoolean" => "Background",
604 "BitmapMask" => "Image",
605 "Switch" => "Input0",
606 "Fuse.Switch" => "Input1",
607 "Merge3D" => "SceneInput1",
608 "Renderer3D" | "Transform3D" | "ReplaceMaterial3D" | "Override3D" | "ReplaceNormals3D"
609 | "Displace3D" | "Duplicate3D" => "SceneInput",
610 "ImagePlane3D" | "TextureTransformOperator" => "MaterialInput",
604611 "Fuse.Colorize" | "Fuse.Outline" => "Image",
605612 "Custom" => "Image1",
613 "MacroOperator" | "GroupOperator" => "MainInput1",
606614 _ => "Input",
607615 }
608616}
crates/model/src/comp/eval.rs+89-42
......@@ -2,8 +2,50 @@ use super::math::eval_fusion_math_expr;
22use super::{ClsEntry, Comp, ExpressionModifier, MAX_EXPR_DEPTH, Node, ParamValue, ShakeModifier};
33use crate::expr::ExprEngine;
44use crate::spline::Gradient;
5use std::cell::RefCell;
56use std::collections::HashMap;
67
8/// `(modifier address, output tag, time bits)`.
9type ModMemoKey = (usize, u8, u64);
10
11thread_local! {
12 static EXPR_MOD_MEMO: RefCell<Option<HashMap<ModMemoKey, Option<[f64; 2]>>>> = const { RefCell::new(None) };
13}
14
15struct ModMemoScope(bool);
16
17impl Drop for ModMemoScope {
18 fn drop(&mut self) {
19 if self.0 {
20 EXPR_MOD_MEMO.with_borrow_mut(|m| *m = None);
21 }
22 }
23}
24
25/// Runs `compute` once per key within the outermost modifier evaluation on this thread, which
26/// keeps fanned-out modifier chains linear. Re-entering an unfinished key (a cycle) yields `None`.
27fn memoized_modifier(key: ModMemoKey, compute: impl FnOnce() -> Option<[f64; 2]>) -> Option<[f64; 2]> {
28 let _scope = ModMemoScope(EXPR_MOD_MEMO.with_borrow_mut(|m| {
29 let outermost = m.is_none();
30 m.get_or_insert_default();
31 outermost
32 }));
33 let hit = EXPR_MOD_MEMO.with_borrow_mut(|m| {
34 let m = m.as_mut().expect("scope installs the memo");
35 let hit = m.get(&key).copied();
36 if hit.is_none() {
37 m.insert(key, None);
38 }
39 hit
40 });
41 if let Some(done) = hit {
42 return done;
43 }
44 let value = compute();
45 EXPR_MOD_MEMO.with_borrow_mut(|m| m.as_mut().expect("scope installs the memo").insert(key, value));
46 value
47}
48
749impl Comp {
850 /// Evaluates an animated `Polyline` spline (`BezierSpline` whose keyframes carry `Value = Polyline { ... }`).
951 pub fn eval_polyline_spline(&self, name: &str, time: f64) -> Option<Vec<crate::spline::PolyPoint>> {
......@@ -493,18 +535,21 @@ impl Comp {
493535 if depth >= MAX_EXPR_DEPTH {
494536 return None;
495537 }
496 let (vars, pts) = self.build_expr_mod_vars(em, time, expr_engine, depth);
497 let key = match source_output {
498 Some("X") => "PointExpressionX",
499 Some("Y") => "PointExpressionY",
500 _ => "NumberExpression",
538 let (tag, key) = match source_output {
539 Some("X") => (1, "PointExpressionX"),
540 Some("Y") => (2, "PointExpressionY"),
541 _ => (0, "NumberExpression"),
501542 };
502 let formula = em
503 .inputs
504 .get(key)
505 .and_then(|b| b.value.as_ref())
506 .and_then(ParamValue::as_str)?;
507 self.eval_expr_mod_formula(formula, time, &vars, &pts, expr_engine)
543 memoized_modifier((em as *const _ as usize, tag, time.to_bits()), || {
544 let (vars, pts) = self.build_expr_mod_vars(em, time, expr_engine, depth);
545 let formula = em
546 .inputs
547 .get(key)
548 .and_then(|b| b.value.as_ref())
549 .and_then(ParamValue::as_str)?;
550 self.eval_expr_mod_formula(formula, time, &vars, &pts, expr_engine).map(|v| [v, 0.0])
551 })
552 .map(|v| v[0])
508553 }
509554
510555 fn eval_expr_mod_point(
......@@ -517,38 +562,40 @@ impl Comp {
517562 if depth >= MAX_EXPR_DEPTH {
518563 return None;
519564 }
520 let (vars, pts) = self.build_expr_mod_vars(em, time, expr_engine, depth);
521 let fx = em
522 .inputs
523 .get("PointExpressionX")
524 .and_then(|b| b.value.as_ref())
525 .and_then(ParamValue::as_str);
526 let fy = em
527 .inputs
528 .get("PointExpressionY")
529 .and_then(|b| b.value.as_ref())
530 .and_then(ParamValue::as_str);
531 if fx.is_some() || fy.is_some() {
532 let x = fx
533 .and_then(|s| self.eval_expr_mod_formula(s, time, &vars, &pts, expr_engine))
534 .unwrap_or(0.5);
535 let y = fy
536 .and_then(|s| self.eval_expr_mod_formula(s, time, &vars, &pts, expr_engine))
537 .unwrap_or(0.5);
538 return Some([x, y]);
539 }
540 if let Some(fp) = em
541 .inputs
542 .get("PointExpression")
543 .and_then(|b| b.value.as_ref())
544 .and_then(ParamValue::as_str)
545 {
546 let (_, _, en) = self.collect_global_expr_env(time);
547 if let Some(pt) = expr_engine.eval_point(fp, time, &vars, &pts, &en) {
548 return Some(pt);
565 memoized_modifier((em as *const _ as usize, 3, time.to_bits()), || {
566 let (vars, pts) = self.build_expr_mod_vars(em, time, expr_engine, depth);
567 let fx = em
568 .inputs
569 .get("PointExpressionX")
570 .and_then(|b| b.value.as_ref())
571 .and_then(ParamValue::as_str);
572 let fy = em
573 .inputs
574 .get("PointExpressionY")
575 .and_then(|b| b.value.as_ref())
576 .and_then(ParamValue::as_str);
577 if fx.is_some() || fy.is_some() {
578 let x = fx
579 .and_then(|s| self.eval_expr_mod_formula(s, time, &vars, &pts, expr_engine))
580 .unwrap_or(0.5);
581 let y = fy
582 .and_then(|s| self.eval_expr_mod_formula(s, time, &vars, &pts, expr_engine))
583 .unwrap_or(0.5);
584 return Some([x, y]);
585 }
586 if let Some(fp) = em
587 .inputs
588 .get("PointExpression")
589 .and_then(|b| b.value.as_ref())
590 .and_then(ParamValue::as_str)
591 {
592 let (_, _, en) = self.collect_global_expr_env(time);
593 if let Some(pt) = expr_engine.eval_point(fp, time, &vars, &pts, &en) {
594 return Some(pt);
595 }
549596 }
550 }
551 None
597 None
598 })
552599 }
553600
554601 pub fn eval_text(
crates/model/src/comp/load.rs+2-9
......@@ -144,13 +144,8 @@ impl Comp {
144144 if let Some(ext_src) = &inner_in.source_op {
145145 // Only connect if ext_src is a visible (non-internal) flow node
146146 if node_by_name.get(ext_src).is_some_and(|&id| !snap_map.is_empty() && id != n.id) {
147 let port_name = if in_name.starts_with("MainInput") || in_name == "Input" {
148 "Input".to_owned()
149 } else {
150 in_name.clone()
151 };
152147 flow_wires.insert(
153 port_name,
148 in_name.clone(),
154149 InputBinding {
155150 value: None,
156151 source_op: Some(ext_src.clone()),
......@@ -163,9 +158,7 @@ impl Comp {
163158 }
164159 }
165160 }
166 if !flow_wires.is_empty() {
167 n.inputs = flow_wires;
168 }
161 n.inputs.extend(flow_wires);
169162 }
170163 }
171164
crates/model/src/comp/save.rs+1-6
......@@ -372,12 +372,7 @@ fn sync_group_wiring(node: &Node, group_tbl: &mut LuaTable) {
372372 .filter_map(|(k, v)| {
373373 let LuaKey::Str(in_name) = k else { return None };
374374 let t = v.as_table()?;
375 let port = if in_name.starts_with("MainInput") || in_name == "Input" {
376 "Input".to_owned()
377 } else {
378 in_name.clone()
379 };
380 Some((port, t.get_str("SourceOp")?.to_owned(), t.get_str("Source")?.to_owned()))
375 Some((in_name.clone(), t.get_str("SourceOp")?.to_owned(), t.get_str("Source")?.to_owned()))
381376 })
382377 .collect()
383378 })
crates/model/src/comp/tests.rs+101-4
......@@ -474,28 +474,125 @@ mod expression_modifier_tests {
474474 fn nested_group_edits_and_wiring_survive_save() {
475475 let mut comp = Comp::from_fusion_str(GROUP_COMP).unwrap();
476476 let group = comp.find_node("Group1").unwrap();
477 assert_eq!(comp.node(group).connected_node("Input"), Some("BG"));
477 assert_eq!(comp.node(group).connected_node("MainInput1"), Some("BG"));
478478
479479 comp.delete_nodes(&[comp.find_node("Inner3").unwrap()]);
480480 let inner2 = comp.find_node("Inner2").unwrap();
481481 assert!(comp.set_input_value(inner2, "Size", ParamValue::Number(2.5)));
482482 let (group, bg2) = (comp.find_node("Group1").unwrap(), comp.find_node("BG2").unwrap());
483 comp.connect_output(bg2, "Output", group, "Input").unwrap();
483 comp.connect_output(bg2, "Output", group, "MainInput1").unwrap();
484484
485485 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
486486 let inner2 = saved.node(saved.find_node("Inner2").unwrap());
487487 assert_eq!(inner2.static_number("Size"), Some(2.5));
488488 assert!(saved.find_node("Inner3").is_none());
489489 assert_eq!(saved.node(saved.find_node("Inner1").unwrap()).connected_node("Input"), Some("BG2"));
490 assert_eq!(saved.node(saved.find_node("Group1").unwrap()).connected_node("Input"), Some("BG2"));
490 assert_eq!(saved.node(saved.find_node("Group1").unwrap()).connected_node("MainInput1"), Some("BG2"));
491491 // The exposed `Default` stays on the InstanceInput instead of leaking onto Inner1.
492492 let text = comp.to_fusion_string();
493493 assert_eq!(text.matches("Value = 3").count(), 0, "{text}");
494494
495495 let mut comp = saved;
496496 let group = comp.find_node("Group1").unwrap();
497 assert!(comp.disconnect(group, "Input"));
497 assert!(comp.disconnect(group, "MainInput1"));
498498 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
499499 assert_eq!(saved.node(saved.find_node("Inner1").unwrap()).connected_node("Input"), None);
500500 }
501
502 const MULTI_INPUT_GROUP: &str = r#"Composition {
503 Tools = ordered() {
504 BG = Background { },
505 BG2 = Background { },
506 Group1 = GroupOperator {
507 Inputs = {
508 MainInput1 = InstanceInput { SourceOp = "M", Source = "Background", },
509 MainInput2 = InstanceInput { SourceOp = "M", Source = "Foreground", },
510 XBlurSize = InstanceInput { SourceOp = "B", Source = "XBlurSize", },
511 },
512 Outputs = {
513 MainOutput1 = InstanceOutput { SourceOp = "B", Source = "Output", },
514 },
515 Tools = ordered() {
516 SizeSpline = BezierSpline {
517 KeyFrames = {
518 [0] = { 1, Flags = { Linear = true, }, },
519 [10] = { 5, Flags = { Linear = true, }, },
520 },
521 },
522 M = Merge {
523 Inputs = {
524 Background = Input { SourceOp = "BG", Source = "Output", },
525 Foreground = Input { SourceOp = "BG2", Source = "Output", },
526 },
527 },
528 B = Blur {
529 Inputs = {
530 XBlurSize = Input { SourceOp = "SizeSpline", Source = "Value", },
531 Input = Input { SourceOp = "M", Source = "Output", },
532 },
533 },
534 },
535 },
536 },
537 }"#;
538
539 #[test]
540 fn multi_input_group_keeps_each_wire_distinct_across_save() {
541 let mut comp = Comp::from_fusion_str(MULTI_INPUT_GROUP).unwrap();
542 let group = comp.find_node("Group1").unwrap();
543 assert_eq!(comp.node(group).connected_node("MainInput1"), Some("BG"));
544 assert_eq!(comp.node(group).connected_node("MainInput2"), Some("BG2"));
545 let tools = |t: &LuaTable| t.get_table("Tools").unwrap().to_fusion_string();
546 assert_eq!(tools(&comp.sync_to_raw_ast()), tools(comp.raw_root.as_ref().unwrap()));
547
548 let (bg, bg2) = (comp.find_node("BG").unwrap(), comp.find_node("BG2").unwrap());
549 comp.connect_output(bg2, "Output", group, "MainInput1").unwrap();
550 comp.connect_output(bg, "Output", group, "MainInput2").unwrap();
551 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
552 let merge = saved.node(saved.find_node("M").unwrap());
553 assert_eq!(merge.connected_node("Background"), Some("BG2"));
554 assert_eq!(merge.connected_node("Foreground"), Some("BG"));
555 }
556
557 #[test]
558 fn group_wire_edit_keeps_animated_exposed_input() {
559 let mut comp = Comp::from_fusion_str(MULTI_INPUT_GROUP).unwrap();
560 let (group, bg2) = (comp.find_node("Group1").unwrap(), comp.find_node("BG2").unwrap());
561 assert!(comp.node(group).inputs.contains_key("XBlurSize"));
562 comp.connect_output(bg2, "Output", group, "MainInput1").unwrap();
563 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
564 let blur = saved.node(saved.find_node("B").unwrap());
565 assert_eq!(blur.connected_node("XBlurSize"), Some("SizeSpline"));
566 assert!(saved.splines.contains_key("SizeSpline"));
567 let merge = saved.node(saved.find_node("M").unwrap());
568 assert_eq!(merge.connected_node("Background"), Some("BG2"));
569 assert_eq!(merge.connected_node("Foreground"), Some("BG2"));
570 }
571
572 #[test]
573 fn fanned_out_expression_modifier_chain_evaluates_linearly() {
574 const LEN: usize = 12;
575 let mut src = String::from(
576 r#"Composition { Tools = ordered() {
577 N = Transform { Inputs = { Size = Input { SourceOp = "E0", Source = "NumberResult", }, }, },"#,
578 );
579 for i in 0..LEN - 1 {
580 let next = format!(r#"Input {{ SourceOp = "E{}", Source = "NumberResult", }}"#, i + 1);
581 src += &format!(
582 r#"E{i} = Expression {{ Inputs = {{ n1 = {next}, n2 = {next}, n3 = {next},
583 NumberExpression = Input {{ Value = "n1 + n2 + n3", }}, }}, }},"#
584 );
585 }
586 src += &format!(
587 r#"E{} = Expression {{ Inputs = {{ n1 = Input {{ Value = 1, }},
588 NumberExpression = Input {{ Value = "n1", }}, }}, }}, }} }}"#,
589 LEN - 1
590 );
591 let comp = Comp::from_fusion_str(&src).unwrap();
592 let n = comp.node(comp.find_node("N").unwrap());
593 let start = std::time::Instant::now();
594 let v = comp.eval_number(n, "Size", 0.0, -1.0, &ExprEngine::new());
595 assert_eq!(v, 3f64.powi(LEN as i32 - 1));
596 assert!(start.elapsed() < std::time::Duration::from_millis(100), "{:?}", start.elapsed());
597 }
501598}
crates/model/src/edit.rs+77-29
......@@ -167,6 +167,17 @@ impl Comp {
167167 id
168168 }
169169
170 /// Maps each group-private node to the innermost group that owns it.
171 fn group_owners(&self) -> HashMap<usize, usize> {
172 let mut owners = HashMap::new();
173 for g in (0..self.nodes.len()).filter(|&g| is_group_kind(&self.nodes[g].kind)) {
174 for kid in self.group_children(g) {
175 owners.entry(kid).or_insert(g);
176 }
177 }
178 owners
179 }
180
170181 /// Indices of the internal nodes owned by the Group/Macro at `idx`, including nested groups'
171182 /// contents. Nodes load in post-order, so they are the contiguous internal block before `idx`.
172183 fn group_children(&self, idx: usize) -> Vec<usize> {
......@@ -250,13 +261,41 @@ impl Comp {
250261 }
251262
252263 let deleted_names: Vec<String> = doomed.iter().map(|&i| self.nodes[i].name.clone()).collect();
253 let deleted_name_set: HashSet<String> = deleted_names.iter().cloned().collect();
254 let deleted_internal: HashSet<String> = doomed
264 let to_delete: HashSet<usize> = doomed.into_iter().collect();
265
266 // Names are scoped: a group-private tool shadows a same-named top-level tool inside its group.
267 let owner_of = self.group_owners();
268 let mut by_scope: HashMap<(Option<usize>, &str), usize> = HashMap::new();
269 for (i, node) in self.nodes.iter().enumerate() {
270 by_scope.insert((owner_of.get(&i).copied(), node.name.as_str()), i);
271 }
272 let mut dead_sources: Vec<HashSet<String>> = self
273 .nodes
255274 .iter()
256 .filter(|&&i| self.nodes[i].internal)
275 .enumerate()
276 .map(|(i, node)| {
277 let scope = owner_of.get(&i).copied();
278 node.inputs
279 .values()
280 .filter_map(|b| b.source_op.as_deref())
281 .filter(|src| {
282 let target = by_scope.get(&(scope, *src)).or_else(|| by_scope.get(&(None, *src)));
283 target.is_some_and(|t| to_delete.contains(t))
284 })
285 .map(str::to_owned)
286 .collect()
287 })
288 .collect();
289 let deleted_top_level: HashSet<String> = to_delete
290 .iter()
291 .filter(|&&i| !self.nodes[i].internal)
257292 .map(|&i| self.nodes[i].name.clone())
258293 .collect();
259 let to_delete: HashSet<usize> = doomed.into_iter().collect();
294 // Private tools deleted on their own live in a surviving group's raw `Tools`.
295 let deleted_private: Vec<(String, String)> = to_delete
296 .iter()
297 .filter_map(|i| Some((self.nodes[*owner_of.get(i)?].name.clone(), self.nodes[*i].name.clone())))
298 .collect();
260299
261300 // Collect modifier names referenced by the nodes being deleted (candidates for pruning).
262301 let mut candidate_modifiers: HashSet<String> = HashSet::new();
......@@ -267,6 +306,7 @@ impl Comp {
267306 // Compact `self.nodes` while building an old_idx -> Option<new_id> remap.
268307 let old_len = self.nodes.len();
269308 let mut remap: Vec<Option<NodeId>> = vec![None; old_len];
309 let mut kept_dead_sources = Vec::new();
270310 let old_nodes = std::mem::take(&mut self.nodes);
271311 let mut new_nodes = Vec::with_capacity(old_len - to_delete.len());
272312 for (old_idx, mut node) in old_nodes.into_iter().enumerate() {
......@@ -277,20 +317,17 @@ impl Comp {
277317 remap[old_idx] = Some(new_id);
278318 node.id = new_id;
279319 new_nodes.push(node);
320 kept_dead_sources.push(std::mem::take(&mut dead_sources[old_idx]));
280321 }
281322
282323 // Fix `macro_output` and unwire any inputs pointing to deleted nodes.
283 for node in &mut new_nodes {
324 for (node, dead) in new_nodes.iter_mut().zip(&kept_dead_sources) {
284325 if let Some(old_mo) = node.macro_output {
285326 node.macro_output = remap.get(old_mo.0).copied().flatten();
286327 }
287328 let mut unwired_ports = Vec::new();
288329 for (port, binding) in &mut node.inputs {
289 if binding
290 .source_op
291 .as_ref()
292 .is_some_and(|s| deleted_name_set.contains(s))
293 {
330 if binding.source_op.as_ref().is_some_and(|s| dead.contains(s)) {
294331 binding.source_op = None;
295332 binding.source_output = None;
296333 unwired_ports.push(port.clone());
......@@ -359,11 +396,15 @@ impl Comp {
359396 // group-private nodes wherever they are nested.
360397 if let Some(tools) = self.raw_root.as_mut().and_then(|r| r.get_table_mut("Tools")) {
361398 tools.entries.retain(|(k, _)| match k {
362 LuaKey::Str(name) => !deleted_name_set.contains(name),
399 LuaKey::Str(name) => !deleted_top_level.contains(name),
363400 _ => true,
364401 });
365 let nested: HashSet<String> = pruned_modifiers.union(&deleted_internal).cloned().collect();
366 remove_tools_recursive(tools, &nested);
402 for (group, child) in &deleted_private {
403 if let Some(inner) = find_raw_tool_mut(tools, group).and_then(|g| g.get_table_mut("Tools")) {
404 inner.entries.retain(|(k, _)| !matches!(k, LuaKey::Str(name) if name == child));
405 }
406 }
407 remove_tools_recursive(tools, &pruned_modifiers);
367408 }
368409
369410 self.revision += 1;
......@@ -395,11 +436,7 @@ impl Comp {
395436
396437 // A private (group-internal) tool is only visible inside its group; a top-level tool is
397438 // visible everywhere except inside groups that define a tool of the same name.
398 let owner = if self.nodes[id.0].internal {
399 (0..self.nodes.len()).skip(id.0 + 1).find(|&g| self.group_children(g).contains(&id.0))
400 } else {
401 None
402 };
439 let owner = self.group_owners().get(&id.0).copied();
403440 let affected: Vec<usize> = match owner {
404441 Some(g) => self.group_children(g),
405442 None => {
......@@ -415,6 +452,7 @@ impl Comp {
415452 };
416453 let scope_name = owner.map(|g| self.nodes[g].name.clone());
417454
455 let renames = HashMap::from([(old_name.clone(), trimmed.to_owned())]);
418456 self.nodes[id.0].name = trimmed.to_owned();
419457 if self.node_by_name.get(&old_name) == Some(&id) {
420458 self.node_by_name.remove(&old_name);
......@@ -427,21 +465,30 @@ impl Comp {
427465 if binding.source_op.as_deref() == Some(old_name.as_str()) {
428466 binding.source_op = Some(trimmed.to_owned());
429467 }
468 if let Some(expr) = &mut binding.expression {
469 *expr = rename_expression_idents(expr, &renames);
470 }
430471 }
431472 rewrite_source_op_in_scope(&mut node.raw, &old_name, trimmed, false);
432473 }
433
434 let renames = HashMap::from([(old_name.clone(), trimmed.to_owned())]);
435474 if owner.is_none() {
436475 for shake in self.shakes.values_mut() {
437476 for binding in shake.inputs.values_mut() {
438477 if binding.source_op.as_deref() == Some(old_name.as_str()) {
439478 binding.source_op = Some(trimmed.to_owned());
440479 }
480 if let Some(expr) = &mut binding.expression {
481 *expr = rename_expression_idents(expr, &renames);
482 }
441483 }
442484 }
443485 }
444486 for em in self.expression_modifiers.values_mut() {
487 for binding in em.inputs.values_mut() {
488 if let Some(expr) = &mut binding.expression {
489 *expr = rename_expression_idents(expr, &renames);
490 }
491 }
445492 for key in EXPRESSION_FORMULA_INPUTS {
446493 if let Some(ParamValue::Text(formula)) = em.inputs.get_mut(*key).and_then(|b| b.value.as_mut()) {
447494 *formula = rename_expression_idents(formula, &renames);
......@@ -769,7 +816,7 @@ pub(super) fn collect_source_ops_in_table(tbl: &LuaTable, out: &mut HashSet<Stri
769816 }
770817}
771818
772/// Rewrites `SourceOp = old_name` in `tbl`, skipping nested groups that define their own tool
819/// Rewrites `SourceOp = old_name` and inline `Expression` identifiers in `tbl`, skipping nested groups that define their own tool
773820/// called `old_name` (inside them the name refers to that private tool). `is_scope_root` exempts
774821/// `tbl` itself from that check.
775822fn rewrite_source_op_in_scope(tbl: &mut LuaTable, old_name: &str, new_name: &str, is_scope_root: bool) {
......@@ -777,15 +824,16 @@ fn rewrite_source_op_in_scope(tbl: &mut LuaTable, old_name: &str, new_name: &str
777824 return;
778825 }
779826 for (k, v) in &mut tbl.entries {
780 if matches!(k, LuaKey::Str(key) if key == "SourceOp") {
781 if let LuaValue::String(s) = v {
782 if s == old_name {
783 *s = new_name.to_owned();
784 }
827 match (k, &mut *v) {
828 (LuaKey::Str(key), LuaValue::String(s)) if key == "SourceOp" && s == old_name => {
829 *s = new_name.to_owned();
785830 }
786 }
787 if let Some(sub) = v.as_table_mut() {
788 rewrite_source_op_in_scope(sub, old_name, new_name, false);
831 (LuaKey::Str(key), LuaValue::String(s)) if key == "Expression" => {
832 let renames = HashMap::from([(old_name.to_owned(), new_name.to_owned())]);
833 *s = rename_expression_idents(s, &renames);
834 }
835 (_, LuaValue::Table(sub)) => rewrite_source_op_in_scope(sub, old_name, new_name, false),
836 _ => {}
789837 }
790838 }
791839}
crates/model/src/edit/defaults.rs+8-7
......@@ -67,7 +67,7 @@ pub(super) fn default_inputs_for_kind(kind: &str, width: u32, height: u32) -> Ve
6767 "Blur" => vec![fuid("Filter", "Fast Gaussian"), num("XBlurSize", 1.0)],
6868 "Glow" => vec![num("XGlowSize", 10.0), num("Glow", 0.8)],
6969 "SoftGlow" => vec![
70 fuid("Filter", "Fast Gaussian"),
70 fuid("Filter", "Gaussian"),
7171 num("Gain", 2.0),
7272 num("XGlowSize", 10.0),
7373 ],
......@@ -129,8 +129,8 @@ pub(super) fn default_inputs_for_kind(kind: &str, width: u32, height: u32) -> Ve
129129 num("Height", h),
130130 num("UseFrameFormatSettings", 1.0),
131131 txt("StyledText", ""),
132 txt("Font", "Open Sans"),
133 txt("Style", "Bold"),
132 txt("Font", "Helvetica Neue"),
133 txt("Style", "Regular"),
134134 num("Size", 0.08),
135135 pt("Center", 0.5, 0.5),
136136 ],
......@@ -140,7 +140,7 @@ pub(super) fn default_inputs_for_kind(kind: &str, width: u32, height: u32) -> Ve
140140 num("Type", 0.0),
141141 num("XRefraction", 0.0),
142142 num("YRefraction", 0.0),
143 num("RefractionStrength", 0.0),
143 num("RefractionStrength", 0.05),
144144 ],
145145 "FastNoise" => vec![
146146 num("Width", w),
......@@ -152,8 +152,9 @@ pub(super) fn default_inputs_for_kind(kind: &str, width: u32, height: u32) -> Ve
152152 num("Seethe", 0.0),
153153 ],
154154 "PipeRouter" | "Underlay" => vec![],
155 "Switch" | "Fuse.Switch" => vec![num("Source", 0.0)],
156 "TimeStretcher" => vec![num("SourceTime", 0.0), num("InterpolateBetweenFrames", 0.0)],
155 "Switch" => vec![num("Source", 0.0)],
156 "Fuse.Switch" => vec![num("Which", 1.0)],
157 "TimeStretcher" => vec![num("SourceTime", 0.0), num("InterpolateBetweenFrames", 1.0)],
157158 "TimeSpeed" => vec![num("Speed", 1.0), num("Delay", 0.0)],
158159 "Renderer3D" => vec![
159160 num("Width", w),
......@@ -161,7 +162,7 @@ pub(super) fn default_inputs_for_kind(kind: &str, width: u32, height: u32) -> Ve
161162 num("UseFrameFormatSettings", 1.0),
162163 fuid("RendererType", "RendererOpenGL"),
163164 ],
164 "Camera3D" => vec![num("FLength", 24.0), num("PlaneOfFocus", 5.0)],
165 "Camera3D" => vec![num("FLength", 35.0), num("PlaneOfFocus", 5.0)],
165166 "Merge3D" => vec![num("PassThroughLights", 1.0)],
166167 "Transform3D" => vec![num("Transform3DOp.Scale.X", 1.0)],
167168 "ImagePlane3D" => vec![
crates/model/src/edit/keyframes.rs+70-6
......@@ -1,6 +1,6 @@
11use super::remove_tools_recursive;
2use crate::comp::{Comp, InputBinding, NodeId, ParamValue, ensure_table_mut, param_value_to_lua};
3use crate::lua_value::{LuaKey, LuaValue};
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};
44use crate::spline::{BezierSpline, Keyframe};
55use std::collections::HashSet;
66
......@@ -98,13 +98,41 @@ impl Comp {
9898 binding.source_op = None;
9999 binding.source_output = None;
100100 binding.value = Some(value.clone());
101 let port_tbl = ensure_table_mut(ensure_table_mut(&mut node.raw, "Inputs", None), port, Some("Input"));
102 port_tbl.remove(&LuaKey::Str("SourceOp".to_owned()));
103 port_tbl.remove(&LuaKey::Str("Source".to_owned()));
104 port_tbl.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(&value));
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()));
105128 }
106129 }
107130 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 }
108136 remove_tools_recursive(tools, &HashSet::from([spline_name.to_owned()]));
109137 }
110138 }
......@@ -113,6 +141,14 @@ impl Comp {
113141 }
114142}
115143
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
116152fn upsert_keyframe(spline: &mut BezierSpline, frame: f64, value: f64) {
117153 if let Some(existing) = spline
118154 .keyframes
......@@ -182,4 +218,32 @@ mod tests {
182218 assert_eq!(r.static_number("Gain"), Some(2.0));
183219 assert!(!saved.to_fusion_string().contains("BC1Gain"));
184220 }
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 }
185249}
crates/model/src/edit/tests.rs+98
......@@ -357,3 +357,101 @@ use std::path::Path;
357357 },
358358 },
359359}"#;
360
361 #[test]
362 fn rename_rewrites_inline_input_expressions() {
363 let src = r#"Composition { Tools = ordered() {
364 Blur1 = Blur { Inputs = { XBlurSize = Input { Value = 4, }, }, },
365 T1 = Transform { Inputs = { Size = Input { Expression = "Blur1.XBlurSize * 2", }, }, },
366 } }"#;
367 let mut comp = Comp::from_fusion_str(src).unwrap();
368 let engine = ExprEngine::new();
369 let size = |c: &Comp| c.eval_number(c.node(c.find_node("T1").unwrap()), "Size", 0.0, -1.0, &engine);
370 assert_eq!(size(&comp), 8.0);
371
372 let blur = comp.find_node("Blur1").unwrap();
373 comp.rename_node(blur, "Soft").unwrap();
374 let expression = |c: &Comp| {
375 c.node(c.find_node("T1").unwrap()).inputs["Size"].expression.clone()
376 };
377 assert_eq!(expression(&comp).as_deref(), Some("Soft.XBlurSize * 2"));
378 assert_eq!(size(&comp), 8.0);
379
380 let text = comp.to_fusion_string();
381 assert!(!text.contains("Blur1"), "{text}");
382 let saved = Comp::from_fusion_str(&text).unwrap();
383 assert_eq!(expression(&saved).as_deref(), Some("Soft.XBlurSize * 2"));
384 assert_eq!(size(&saved), 8.0);
385 }
386
387 const SHADOWED_GROUP: &str = r#"Composition { Tools = ordered() {
388 Blur1 = Blur { },
389 C = Transform { Inputs = { Input = Input { SourceOp = "Blur1", Source = "Output", }, }, },
390 Group1 = GroupOperator {
391 Outputs = { MainOutput1 = InstanceOutput { SourceOp = "T", Source = "Output", }, },
392 Tools = ordered() {
393 Blur1 = Blur { },
394 T = Transform { Inputs = { Input = Input { SourceOp = "Blur1", Source = "Output", }, }, },
395 },
396 },
397 } }"#;
398
399 #[test]
400 fn deleting_a_group_keeps_same_named_top_level_tools_and_wires() {
401 let mut comp = Comp::from_fusion_str(SHADOWED_GROUP).unwrap();
402 comp.delete_nodes(&[comp.find_node("Group1").unwrap()]);
403 assert!(comp.find_node("T").is_none());
404 let c = comp.node(comp.find_node("C").unwrap());
405 assert_eq!(c.connected_node("Input"), Some("Blur1"));
406
407 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
408 assert!(saved.find_node("Blur1").is_some());
409 assert_eq!(saved.node(saved.find_node("C").unwrap()).connected_node("Input"), Some("Blur1"));
410 }
411
412 #[test]
413 fn deleting_a_private_tool_only_unwires_its_own_group() {
414 let mut comp = Comp::from_fusion_str(SHADOWED_GROUP).unwrap();
415 let private = comp.nodes.iter().find(|n| n.internal && n.name == "Blur1").unwrap().id;
416 comp.delete_nodes(&[private]);
417 let (c, t) = (comp.find_node("C").unwrap(), comp.find_node("T").unwrap());
418 assert_eq!(comp.node(c).connected_node("Input"), Some("Blur1"));
419 assert_eq!(comp.node(t).connected_node("Input"), None);
420
421 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
422 assert_eq!(saved.nodes.iter().filter(|n| n.name == "Blur1").count(), 1);
423 assert_eq!(saved.node(saved.find_node("C").unwrap()).connected_node("Input"), Some("Blur1"));
424 }
425
426 #[test]
427 fn default_ports_and_tool_defaults_match_the_engine() {
428 for (kind, port) in [
429 ("Merge", "Background"),
430 ("Dissolve", "Background"),
431 ("ChannelBoolean", "Background"),
432 ("BitmapMask", "Image"),
433 ("Switch", "Input0"),
434 ("Fuse.Switch", "Input1"),
435 ("Merge3D", "SceneInput1"),
436 ("Renderer3D", "SceneInput"),
437 ("Duplicate3D", "SceneInput"),
438 ("ImagePlane3D", "MaterialInput"),
439 ("TextureTransformOperator", "MaterialInput"),
440 ("Fuse.Outline", "Image"),
441 ("Custom", "Image1"),
442 ("GroupOperator", "MainInput1"),
443 ("Blur", "Input"),
444 ] {
445 assert_eq!(default_main_input_port(kind), port, "{kind}");
446 }
447 let defaults = |kind| defaults::default_inputs_for_kind(kind, 1920, 1080);
448 let has = |kind, key: &str, v: ParamValue| defaults(kind).contains(&(key.to_owned(), v));
449 assert!(has("Fuse.Switch", "Which", ParamValue::Number(1.0)));
450 assert!(has("Switch", "Source", ParamValue::Number(0.0)));
451 assert!(has("Camera3D", "FLength", ParamValue::Number(35.0)));
452 assert!(has("TimeStretcher", "InterpolateBetweenFrames", ParamValue::Number(1.0)));
453 assert!(has("Displace", "RefractionStrength", ParamValue::Number(0.05)));
454 assert!(has("TextPlus", "Font", ParamValue::Text("Helvetica Neue".into())));
455 assert!(has("TextPlus", "Style", ParamValue::Text("Regular".into())));
456 assert!(has("SoftGlow", "Filter", ParamValue::FuId("Gaussian".into())));
457 }
crates/model/src/expr.rs+64-3
......@@ -6,7 +6,7 @@
66use mlua::{HookTriggers, Lua, LuaOptions, MultiValue, StdLib, Value, VmState};
77use std::collections::HashMap;
88use std::sync::Arc;
9use std::sync::atomic::{AtomicU64, Ordering};
9use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
1010
1111/// VM instructions one expression evaluation may execute before it is aborted.
1212const INSTRUCTION_BUDGET: u64 = 50_000;
......@@ -19,6 +19,8 @@ const MEMORY_LIMIT: usize = 16 * 1024 * 1024;
1919pub struct ExprEngine {
2020 lua: Lua,
2121 instructions_used: Arc<AtomicU64>,
22 /// Latched once the budget is exceeded so every later hook call also errors.
23 aborted: Arc<AtomicBool>,
2224}
2325
2426impl Default for ExprEngine {
......@@ -67,16 +69,38 @@ impl ExprEngine {
6769 let _ = lua.load(init).exec();
6870
6971 let globals = lua.globals();
72 // Stdlib tables become write-protected proxies so no evaluation can alter them for the next.
73 let read_only = lua
74 .create_function(|_, _: MultiValue| -> mlua::Result<()> {
75 Err(mlua::Error::runtime("attempt to modify a read-only table"))
76 })
77 .expect("function creates");
78 for name in ["math", "string", "table"] {
79 let real: mlua::Table = globals.get(name).expect("stdlib table exists");
80 let proxy = lua.create_table().expect("table creates");
81 let mt = lua.create_table().expect("table creates");
82 mt.set("__index", real).expect("table sets");
83 mt.set("__newindex", read_only.clone()).expect("table sets");
84 proxy.set_metatable(Some(mt));
85 globals.set(name, proxy).expect("global sets");
86 }
87 // `pcall`/`xpcall` would swallow the budget error; the rest reach shared tables or metatables.
7088 for name in [
7189 "dofile", "loadfile", "load", "require", "collectgarbage", "os", "io", "debug", "package",
90 "pcall", "xpcall", "rawget", "rawset", "rawequal", "getmetatable", "setmetatable", "_G",
7291 ] {
7392 let _ = globals.set(name, Value::Nil);
7493 }
7594
7695 let instructions_used = Arc::new(AtomicU64::new(0));
96 let aborted = Arc::new(AtomicBool::new(false));
7797 let counter = Arc::clone(&instructions_used);
98 let latch = Arc::clone(&aborted);
7899 lua.set_hook(HookTriggers::new().every_nth_instruction(HOOK_STEP), move |_, _| {
79 if counter.fetch_add(u64::from(HOOK_STEP), Ordering::Relaxed) >= INSTRUCTION_BUDGET {
100 if latch.load(Ordering::Relaxed)
101 || counter.fetch_add(u64::from(HOOK_STEP), Ordering::Relaxed) >= INSTRUCTION_BUDGET
102 {
103 latch.store(true, Ordering::Relaxed);
80104 Err(mlua::Error::runtime("expression instruction budget exceeded"))
81105 } else {
82106 Ok(VmState::Continue)
......@@ -84,7 +108,7 @@ impl ExprEngine {
84108 });
85109 lua.set_memory_limit(MEMORY_LIMIT).expect("memory limit applies");
86110
87 Self { lua, instructions_used }
111 Self { lua, instructions_used, aborted }
88112 }
89113
90114 /// Evaluates `expr` in a fresh environment with a fresh instruction budget.
......@@ -98,6 +122,7 @@ impl ExprEngine {
98122 ) -> Option<Value> {
99123 let env = self.build_env(time, self_params, self_points, env_nodes).ok()?;
100124 self.instructions_used.store(0, Ordering::Relaxed);
125 self.aborted.store(false, Ordering::Relaxed);
101126 self.lua.load(&Self::expr_chunk(expr)).set_environment(env).eval().ok()
102127 }
103128
......@@ -257,4 +282,40 @@ mod tests {
257282 // Budget resets per evaluation, so the engine stays usable.
258283 assert_eq!(eval("1 + 1"), Some(2.0));
259284 }
285
286 #[test]
287 fn pcall_cannot_swallow_the_budget() {
288 let engine = ExprEngine::new();
289 let e = HashMap::new();
290 let eval = |src: &str| engine.eval_number(src, 0.0, &HashMap::new(), &HashMap::new(), &e);
291 let start = std::time::Instant::now();
292 assert_eq!(eval(":while true do pcall(function() while true do end end) end"), None);
293 assert_eq!(eval(":while true do xpcall(function() while true do end end, print) end"), None);
294 assert!(start.elapsed() < std::time::Duration::from_millis(50), "{:?}", start.elapsed());
295 assert_eq!(eval("1 + 1"), Some(2.0));
296 }
297
298 #[test]
299 fn evaluations_cannot_mutate_shared_state() {
300 let engine = ExprEngine::new();
301 let e = HashMap::new();
302 let eval = |src: &str| engine.eval_number(src, 0.0, &HashMap::new(), &HashMap::new(), &e);
303 for src in [
304 ":math.floor = function() return 42 end; return 1",
305 ":string.upper = function() return 42 end; return 1",
306 ":table.insert = nil; return 1",
307 ":_G.leak = 1; return 1",
308 ":getmetatable('').__index.upper = nil; return 1",
309 ":setmetatable(math, nil); return 1",
310 ] {
311 assert_eq!(eval(src), None, "{src}");
312 }
313 assert_eq!(eval(":floor = function() return 42 end; return floor(1.5)"), Some(42.0));
314 assert_eq!(eval("floor(1.5)"), Some(1.0));
315 assert_eq!(eval("math.floor(1.5)"), Some(1.0));
316 assert_eq!(eval("leak"), None);
317 let upper = engine.eval_string("('a'):upper()", 0.0, &HashMap::new(), &HashMap::new(), &e);
318 assert_eq!(upper.as_deref(), Some("A"));
319 assert_eq!(eval("string.len('abc') + select('#', table.unpack({1, 2}))"), Some(5.0));
320 }
260321}