From a5e1d16ebe8cc3e59daf03d7bd093cb52249af67 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Tue, 1 Dec 2026 01:21:31 -0800 Subject: [PATCH] Scope macro-internal SourceOps, text inputs in expressions, history dirty-flag and atomic save fixes - Clear SourceOp wires that point into an unrelated macro on load (globe 10.0% -> 3.2% MAE); save keeps the original text. - Expose text inputs and `self` to expressions as { Value = ... } tables; follow bare Node.Param references through that input's own expression (technique001 4.0% -> 1.5%). - Always insert referenced nodes into the expression env and exempt _G like _ENV. - CompHistory forgets the saved depth once an unrecorded mutation diverges from it. - save_to_file: unique create_new temp, dangling symlinks, parent dir fsync; edited Loader timing inputs sync into Clips[1]. Assisted-by: claude-sonnet-5.5 --- crates/model/src/comp.rs | 3 + crates/model/src/comp/eval.rs | 92 +++++++++++++++------ crates/model/src/comp/load.rs | 50 ++++++++++++ crates/model/src/comp/save.rs | 136 ++++++++++++++++++++++++++++--- crates/model/src/edit/history.rs | 44 ++++++++++ crates/model/src/expr.rs | 33 ++++++-- 6 files changed, 313 insertions(+), 45 deletions(-) diff --git a/crates/model/src/comp.rs b/crates/model/src/comp.rs index aee797f0dc5798b3dc1b2fa026060a81f2025d32..ff1fd141dff3da3fb73248c3a109fc7e59cfa68e 100644 --- a/crates/model/src/comp.rs +++ b/crates/model/src/comp.rs @@ -431,6 +431,9 @@ pub struct Comp { pub shakes: HashMap, /// Standalone `Expression` modifiers keyed by modifier name (e.g. `"Expression1"`). pub expression_modifiers: HashMap, + /// `(internal node, port)` wires whose out-of-scope `SourceOp` into another macro was cleared + /// on load; the raw AST still carries the original text. + pub(crate) cross_macro_wires: HashSet<(String, String)>, /// Preserved raw root `Composition { ... }` Lua AST for lossless `.comp` roundtrip. pub raw_root: Option, /// Generation counter incremented whenever any node, wire, or spline mutates. diff --git a/crates/model/src/comp/eval.rs b/crates/model/src/comp/eval.rs index 6e6d35d575f0e29e14869f7aae1b13658023f22f..af163d6c8683560fbe578287b9147e9a82e62a3f 100644 --- a/crates/model/src/comp/eval.rs +++ b/crates/model/src/comp/eval.rs @@ -1,6 +1,6 @@ use super::math::eval_fusion_math_expr; use super::{ClsEntry, Comp, ExpressionModifier, MAX_EXPR_DEPTH, Node, ParamValue, ShakeModifier}; -use crate::expr::ExprEngine; +use crate::expr::{ExprEngine, ExprValue}; use crate::spline::Gradient; use std::cell::RefCell; use std::collections::{HashMap, HashSet}; @@ -12,11 +12,11 @@ thread_local! { static EXPR_MOD_MEMO: RefCell>>> = const { RefCell::new(None) }; } -/// Identifiers `expr` can look up, or `None` when `_ENV` allows lookups by computed name. +/// Identifiers `expr` can look up, or `None` when `_ENV`/`_G` allow lookups by computed name. fn referenced_names(expr: &str) -> Option> { let names: HashSet<&str> = expr.split(|c: char| !c.is_ascii_alphanumeric() && c != '_').filter(|t| !t.is_empty()).collect(); - (!names.contains("_ENV")).then_some(names) + (!names.contains("_ENV") && !names.contains("_G")).then_some(names) } struct ModMemoScope(bool); @@ -123,10 +123,19 @@ impl Comp { return default; }; if let Some(expr) = &binding.expression { - if let Some(v) = self.eval_expr_number(node, expr, time, expr_engine) { - if v.is_finite() { - return v; + // A bare `Node.Param` follows that input's own expression/animation instead of its baked value. + let referenced = expr.trim().split_once('.').and_then(|(n, p)| { + let ident = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'); + (ident(n) && ident(p)).then_some((n, p)) + }); + let v = match referenced.and_then(|(n, p)| Some((self.node(self.find_node(n)?), p))) { + Some((other, p)) if other.inputs.contains_key(p) && other.id != node.id => { + Some(self.eval_number_at(other, p, time, f64::NAN, expr_engine, depth + 1)) } + _ => self.eval_expr_number(node, expr, time, expr_engine), + }; + if let Some(v) = v.filter(|v| v.is_finite()) { + return v; } } if let Some(src) = &binding.source_op { @@ -431,29 +440,35 @@ impl Comp { expr_engine.eval_number(trimmed, time, &HashMap::new(), &HashMap::new(), &en) } - /// `node name -> numeric inputs` for the nodes `expr` can reach; every other node is skipped. - fn collect_node_env(&self, expr: &str, time: f64) -> HashMap> { + /// `node name -> numeric/text inputs` for the nodes `expr` can reach; every other node is skipped. + fn collect_node_env(&self, expr: &str, time: f64) -> HashMap> { let names = referenced_names(expr); - let mut env_nodes = HashMap::new(); - for n in &self.nodes { - if !names.as_ref().is_none_or(|s| s.contains(n.name.as_str())) { - continue; - } - let mut m = HashMap::new(); - for (k, b) in &n.inputs { - if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) { - m.insert(k.clone(), v); - } else if let Some(src) = &b.source_op { - if let Some(sp) = self.splines.get(src) { - m.insert(k.clone(), sp.eval(time)); - } + self.nodes + .iter() + .filter(|n| names.as_ref().is_none_or(|s| s.contains(n.name.as_str()))) + .map(|n| (n.name.clone(), self.node_expr_vars(n, time))) + .collect() + } + + fn node_expr_vars(&self, node: &Node, time: f64) -> HashMap { + let mut vars = HashMap::new(); + for (k, b) in &node.inputs { + match b.value.as_ref() { + Some(ParamValue::Number(v)) => { + vars.insert(k.clone(), ExprValue::Number(*v)); + continue; + } + Some(ParamValue::Text(t)) => { + vars.insert(k.clone(), ExprValue::Text(t.clone())); + continue; } + _ => {} } - if !m.is_empty() { - env_nodes.insert(n.name.clone(), m); + if let Some(sp) = b.source_op.as_ref().and_then(|src| self.splines.get(src)) { + vars.insert(k.clone(), ExprValue::Number(sp.eval(time))); } } - env_nodes + vars } fn build_expr_mod_vars( @@ -699,7 +714,7 @@ impl Comp { ) -> ( HashMap, HashMap, - HashMap>, + HashMap>, ) { let names = referenced_names(expr); let mut self_params = HashMap::new(); @@ -726,7 +741,11 @@ impl Comp { } } } - (self_params, self_points, self.collect_node_env(expr, time)) + let mut env_nodes = self.collect_node_env(expr, time); + if names.as_ref().is_none_or(|s| s.contains("self")) { + env_nodes.insert("self".to_owned(), self.node_expr_vars(node, time)); + } + (self_params, self_points, env_nodes) } fn eval_expr_number( @@ -785,4 +804,25 @@ mod tests { assert_eq!(comp.eval_number(probe, "Height", 3.0, 0.0, &engine), 42.0); assert!(start.elapsed() < std::time::Duration::from_millis(500), "{:?}", start.elapsed()); } + + #[test] + fn self_and_referenced_nodes_expose_text_inputs() { + let src = r##"Composition { Tools = ordered() { + TextA = TextPlus { Inputs = { + StyledText = Input { Value = "one two three", }, + SyncWord = Input { Value = 2, }, + End = Input { Expression = "(function(a,b) return #a + b end)(self.StyledText.Value, self.SyncWord)", }, + }, }, + Follower = TextPlus { Inputs = { End = Input { Expression = "TextA.End", }, }, }, + Echo = TextPlus { Inputs = { + Width = Input { Expression = "#tostring(TextA.StyledText)", }, + }, }, + } }"##; + let comp = Comp::from_fusion_str(src).unwrap(); + let engine = ExprEngine::new(); + let follower = comp.node(comp.find_node("Follower").unwrap()); + assert_eq!(comp.eval_number(follower, "End", 0.0, -1.0, &engine), 15.0); + let echo = comp.node(comp.find_node("Echo").unwrap()); + assert_eq!(comp.eval_number(echo, "Width", 0.0, -1.0, &engine), 13.0); + } } diff --git a/crates/model/src/comp/load.rs b/crates/model/src/comp/load.rs index da9fcf56763a300842f2f9250a5f2f9355a2dfce..00d82c39d49a6a789b529ee21b84f6ece9aa1219 100644 --- a/crates/model/src/comp/load.rs +++ b/crates/model/src/comp/load.rs @@ -113,6 +113,8 @@ impl Comp { } } + let cross_macro_wires = clear_cross_macro_wires(&mut nodes, &node_by_name); + // Apply InstanceInput defaults from MacroOperator/GroupOperator onto their inner target tools. for (target_op, target_param, val) in macro_defaults { if let Some(&nid) = node_by_name.get(&target_op) { @@ -284,6 +286,7 @@ impl Comp { text_cls, shakes, expression_modifiers, + cross_macro_wires, raw_root: Some(root.clone()), revision: NEXT_COMP_REVISION.fetch_add(REVISION_STRIDE, Ordering::Relaxed), }) @@ -291,6 +294,53 @@ impl Comp { } +/// Fusion resolves a macro-internal `SourceOp` only within the macro's own scope (itself, its +/// enclosing macros, its nested macros) or at top level; a name that only exists inside an +/// unrelated macro stays unconnected. Returns the `(node, port)` wires whose `source_op` was +/// cleared here so saving keeps the original text. +fn clear_cross_macro_wires(nodes: &mut [Node], node_by_name: &HashMap) -> HashSet<(String, String)> { + let mut owner: HashMap = HashMap::new(); + for m in nodes.iter().filter(|n| matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator")) { + let Some(inner) = m.raw.get_table("Tools") else { continue }; + for (key, _) in &inner.entries { + let LuaKey::Str(child) = key else { continue }; + if let Some(&cid) = node_by_name.get(child).filter(|&&c| nodes[c.0].internal) { + owner.insert(cid, m.id); + } + } + } + let encloses = |outer: NodeId, mut inner: NodeId| { + loop { + if inner == outer { + return true; + } + match owner.get(&inner) { + Some(&up) => inner = up, + None => return false, + } + } + }; + let mut cleared = Vec::new(); + for n in nodes.iter().filter(|n| n.internal) { + let Some(&n_scope) = owner.get(&n.id) else { continue }; + for (port, b) in &n.inputs { + let Some(&t) = b.source_op.as_ref().and_then(|s| node_by_name.get(s)) else { continue }; + if let Some(&t_scope) = owner.get(&t) { + if !encloses(t_scope, n_scope) && !encloses(n_scope, t_scope) { + cleared.push((n.id, port.clone())); + } + } + } + } + cleared + .into_iter() + .map(|(id, port)| { + nodes[id.0].inputs.get_mut(&port).expect("collected from this map").source_op = None; + (nodes[id.0].name.clone(), port) + }) + .collect() +} + fn is_non_inheritable_instance_port( name: &str, binding: &InputBinding, diff --git a/crates/model/src/comp/save.rs b/crates/model/src/comp/save.rs index 993248d346e763d23355965db0200a03cab33227..4a91ffb32ef8e8e0a881427793c469af79e118e6 100644 --- a/crates/model/src/comp/save.rs +++ b/crates/model/src/comp/save.rs @@ -3,7 +3,7 @@ use super::math::find_raw_tool_mut; use super::{BitDepth, Comp, InputBinding, Node, ParamValue, is_modifier_type}; use crate::lua_value::{LuaKey, LuaTable, LuaValue}; use crate::spline::{BezierSpline, read_vec2}; -use std::collections::{HashMap, VecDeque}; +use std::collections::{HashMap, HashSet, VecDeque}; use std::io::Write; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -201,6 +201,31 @@ impl Comp { tool_tbl.remove(&LuaKey::Str("PassThrough".to_owned())); } + // Loader timing edits made through `Inputs` land in the clip too (`Loop` is a count: 0 = loop). + if node.kind == "Loader" { + let edited = |port: &str| { + let now = node.static_number(port)?; + let before = tool_tbl.get_table("Inputs").and_then(|i| i.get_table(port)).map(parse_input_binding); + (before.and_then(|b| b.value?.as_f64()) != Some(now)).then_some(now) + }; + let updates = [ + ("GlobalStart", edited("GlobalIn").map(LuaValue::Number)), + ("GlobalEnd", edited("GlobalOut").map(LuaValue::Number)), + ("Loop", edited("Loop").map(|v| LuaValue::Number(if v > 0.5 { 0.0 } else { 1.0 }))), + ("Reverse", edited("Reverse").map(|v| LuaValue::Bool(v > 0.5))), + ]; + let clip = tool_tbl + .get_table_mut("Clips") + .and_then(|c| c.entries.iter_mut().find_map(|(_, v)| v.as_table_mut())); + if let Some(clip) = clip { + for (key, value) in updates { + if let Some(value) = value { + clip.set(LuaKey::Str(key.to_owned()), value); + } + } + } + } + // Group/Macro inputs hold InstanceInput wiring (synced by `sync_group_wiring`). if !is_group_kind(&node.kind) { let master_inputs = node @@ -208,7 +233,7 @@ impl Comp { .get_str("SourceOp") .and_then(|m| self.find_node(m)) .map(|mid| &self.nodes[mid.0].inputs); - sync_node_inputs(node, master_inputs, instance_defaults, tool_tbl); + sync_node_inputs(node, master_inputs, instance_defaults, &self.cross_macro_wires, tool_tbl); } } @@ -230,7 +255,11 @@ impl Comp { let path = path.as_ref(); let target = if std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) { - std::fs::canonicalize(path)? + // A dangling link is followed one hop so saving creates its target. + std::fs::canonicalize(path).or_else(|_| { + let hop = std::fs::read_link(path)?; + Ok::<_, std::io::Error>(path.parent().unwrap_or_else(|| Path::new(".")).join(hop)) + })? } else { path.to_path_buf() }; @@ -240,6 +269,7 @@ impl Comp { .and_then(|s| s.to_str()) .filter(|s| !s.is_empty()) .unwrap_or("comp"); + let seq = BACKUP_SEQ.fetch_add(1, Ordering::Relaxed); let backup_path = if path.exists() { let backup_dir = std::env::temp_dir().join("fission-backups"); @@ -248,7 +278,6 @@ impl Comp { .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_millis()) .unwrap_or(0); - let seq = BACKUP_SEQ.fetch_add(1, Ordering::Relaxed); let backup_file = backup_dir.join(format!("{stem}_{unix_millis}_{}_{seq}.comp.bak", std::process::id())); std::fs::copy(path, &backup_file)?; Some(backup_file) @@ -266,22 +295,30 @@ impl Comp { .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_nanos()) .unwrap_or(0); - let pid = std::process::id(); - let tmp_path = parent.join(format!(".{stem}.{pid}.{nanos}.tmp")); + let tmp_path = parent.join(format!(".{stem}.{}.{seq}.{nanos}.tmp", std::process::id())); let serialized = self.to_fusion_string(); - let written = std::fs::File::create(&tmp_path).and_then(|mut f| { - f.write_all(serialized.as_bytes())?; - f.sync_all() - }); + let written = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp_path) + .and_then(|mut f| { + f.write_all(serialized.as_bytes())?; + f.sync_all() + }); if let Err(e) = written { - let _ = std::fs::remove_file(&tmp_path); + // `create_new` failing means the name is someone else's file; never delete that. + if e.kind() != std::io::ErrorKind::AlreadyExists { + let _ = std::fs::remove_file(&tmp_path); + } return Err(e); } if let Err(e) = std::fs::rename(&tmp_path, path) { let _ = std::fs::remove_file(&tmp_path); return Err(e); } + // Best effort: persist the rename itself. + let _ = std::fs::File::open(parent).and_then(|dir| dir.sync_all()); Ok(backup_path) } @@ -433,6 +470,7 @@ fn sync_node_inputs( node: &Node, master_inputs: Option<&HashMap>, instance_defaults: &HashMap<(&str, &str), ParamValue>, + cross_macro_wires: &HashSet<(String, String)>, tool_tbl: &mut LuaTable, ) { // First remove any input present in raw `Inputs` that was explicitly removed from `node.inputs`. @@ -467,7 +505,13 @@ fn sync_node_inputs( let existing_binding = tool_tbl .get_table("Inputs") .and_then(|i| i.get_table(port)) - .map(parse_input_binding); + .map(parse_input_binding) + .map(|mut b| { + if binding.source_op.is_none() && cross_macro_wires.contains(&(node.name.clone(), port.clone())) { + b.source_op = None; + } + b + }); if let Some(orig) = existing_binding { if orig == *binding { @@ -688,4 +732,72 @@ mod tests { assert_eq!(std::fs::read_to_string(&backup).unwrap(), "old"); let _ = std::fs::remove_file(backup); } + + #[cfg(unix)] + #[test] + fn saving_through_a_dangling_symlink_creates_its_target() { + let dir = scratch("dangling"); + let real = dir.join("real.comp"); + let link = dir.join("link.comp"); + std::os::unix::fs::symlink("real.comp", &link).unwrap(); + let comp = Comp::from_fusion_str("Composition { Tools = ordered() { }, }").unwrap(); + assert!(comp.save_to_file(&link).unwrap().is_none()); + assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink()); + assert_eq!(std::fs::read_to_string(&real).unwrap(), comp.to_fusion_string()); + } + + const LOADER: &str = r#"Composition { + Tools = ordered() { + L = Loader { + Clips = { + Clip { + Filename = "a.0000.exr", + GlobalStart = 0, + GlobalEnd = 10, + Loop = 1, + }, + }, + Inputs = { + Loop = Input { Value = 0, }, + }, + }, + }, + }"#; + + #[test] + fn edited_loader_timing_inputs_land_in_the_clip() { + let mut comp = Comp::from_fusion_str(LOADER).unwrap(); + let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap(); + assert!(!saved.node(saved.find_node("L").unwrap()).clips[0].loop_clip); + + let l = comp.find_node("L").unwrap(); + comp.set_input_value(l, "Loop", ParamValue::Number(1.0)); + comp.set_input_value(l, "GlobalOut", ParamValue::Number(25.0)); + let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap(); + let clip = &saved.node(saved.find_node("L").unwrap()).clips[0]; + assert!(clip.loop_clip); + assert_eq!(clip.global_end, 25); + } + + #[test] + fn cleared_cross_macro_wire_keeps_its_source_op_on_save() { + let src = r#"Composition { + Tools = ordered() { + A = MacroOperator { + Tools = ordered() { + InA = Blur {}, + }, + }, + B = MacroOperator { + Tools = ordered() { + InB = Blur { Inputs = { Input = Input { SourceOp = "InA", Source = "Output", }, }, }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let in_b = comp.node(comp.find_node("InB").unwrap()); + assert_eq!(in_b.connected_node("Input"), None); + assert!(comp.to_fusion_string().contains(r#"SourceOp = "InA""#)); + } } diff --git a/crates/model/src/edit/history.rs b/crates/model/src/edit/history.rs index eb58b01b935a4213b901e0a525f2e0266f36ddcc..52a84bbbafd3c76b021d9d2e91ad2e44c137514f 100644 --- a/crates/model/src/edit/history.rs +++ b/crates/model/src/edit/history.rs @@ -118,6 +118,14 @@ impl CompHistory { self.saved_revision != Some(comp_revision) } + /// An unrecorded mutation at the saved depth makes the saved state unreachable: any entry + /// recorded from here on captures the mutated state, not the saved one. + fn forget_diverged_saved_depth(&mut self, depth: usize, state_revision: u64) { + if self.saved_undo_depth == Some(depth) && self.saved_revision != Some(state_revision) { + self.saved_undo_depth = None; + } + } + /// Undo/redo bump `comp.revision` even when they land back on the saved state. fn rebase_saved_revision(&mut self, comp_revision: u64) { if self.saved_undo_depth == Some(self.undo_stack.len()) { @@ -255,6 +263,7 @@ impl CompHistory { return false; }; let prev_rev = comp.revision; + self.forget_diverged_saved_depth(self.undo_stack.len() + 1, prev_rev); let redo_entry = HistoryEntry { label: entry.label, snapshot: comp.clone(), @@ -274,6 +283,7 @@ impl CompHistory { return false; }; let prev_rev = comp.revision; + self.forget_diverged_saved_depth(self.undo_stack.len(), prev_rev); let undo_entry = HistoryEntry { label: entry.label, snapshot: comp.clone(), @@ -287,6 +297,7 @@ impl CompHistory { } fn push_entry(&mut self, entry: HistoryEntry) { + self.forget_diverged_saved_depth(self.undo_stack.len(), entry.snapshot.revision); // Any saved state that lived in the redo branch is now unreachable. if let Some(saved_depth) = self.saved_undo_depth { if saved_depth > self.undo_stack.len() { @@ -448,6 +459,39 @@ mod tests { assert!(!history.is_dirty(&comp)); } + #[test] + fn unrecorded_mutation_at_saved_depth_is_never_clean_after_undo_redo() { + let mut comp = sample_comp(); + let mut history = CompHistory::new(); + let bg = comp.find_node("BG1").unwrap(); + + history.push_snapshot(&comp, "Move"); + comp.set_node_pos(bg, [1.0, 1.0]); + history.mark_saved(&comp); + + comp.set_node_pos(bg, [2.0, 2.0]); + assert!(history.is_dirty(&comp)); + assert!(history.undo(&mut comp)); + assert!(history.redo(&mut comp)); + assert_eq!(comp.node(bg).pos, [2.0, 2.0]); + assert!(history.is_dirty(&comp)); + } + + #[test] + fn unrecorded_mutation_at_saved_depth_is_never_clean_after_push_undo() { + let mut comp = sample_comp(); + let mut history = CompHistory::new(); + let bg = comp.find_node("BG1").unwrap(); + history.mark_saved(&comp); + + comp.set_node_pos(bg, [2.0, 2.0]); + history.push_snapshot(&comp, "Move"); + comp.set_node_pos(bg, [3.0, 3.0]); + assert!(history.undo(&mut comp)); + assert_eq!(comp.node(bg).pos, [2.0, 2.0]); + assert!(history.is_dirty(&comp)); + } + #[test] fn undo_and_redo_keep_the_live_file_identity() { let mut comp = sample_comp(); diff --git a/crates/model/src/expr.rs b/crates/model/src/expr.rs index 12192a42dc7b64cc8e7737498a2a57a8ea08090d..f5de8d085f9ac4747bce6bd2d3176cd7ca7ff56b 100644 --- a/crates/model/src/expr.rs +++ b/crates/model/src/expr.rs @@ -14,6 +14,14 @@ const INSTRUCTION_BUDGET: u64 = 50_000; const HOOK_STEP: u32 = 1000; const MEMORY_LIMIT: usize = 16 * 1024 * 1024; +/// An input readable from an expression. Text inputs surface as `{ Value = "..." }` tables that +/// also stringify, matching Fusion's `Node.StyledText.Value`. +#[derive(Clone, Debug, PartialEq)] +pub enum ExprValue { + Number(f64), + Text(String), +} + /// Expressions come from `.comp` files, so the VM is sandboxed: no `os`/`io`/`debug`/`package`, /// no code loading, and bounded instructions and memory per evaluation. pub struct ExprEngine { @@ -118,7 +126,7 @@ impl ExprEngine { time: f64, self_params: &HashMap, self_points: &HashMap, - env_nodes: &HashMap>, + env_nodes: &HashMap>, ) -> Option { let env = self.build_env(time, self_params, self_points, env_nodes).ok()?; self.instructions_used.store(0, Ordering::Relaxed); @@ -136,7 +144,7 @@ impl ExprEngine { } /// Evaluates a Fusion SimpleExpression returning a number. - /// `env_nodes` provides `node_name -> (param_name -> f64)` and `self_params` provides + /// `env_nodes` provides `node_name -> (param_name -> value)` and `self_params` provides /// unqualified parameter names on the current node. pub fn eval_number( &self, @@ -144,7 +152,7 @@ impl ExprEngine { time: f64, self_params: &HashMap, self_points: &HashMap, - env_nodes: &HashMap>, + env_nodes: &HashMap>, ) -> Option { let val = self.run(expr, time, self_params, self_points, env_nodes)?; match val { @@ -163,7 +171,7 @@ impl ExprEngine { time: f64, self_params: &HashMap, self_points: &HashMap, - env_nodes: &HashMap>, + env_nodes: &HashMap>, ) -> Option<[f64; 2]> { let val = self.run(expr, time, self_params, self_points, env_nodes)?; if let Value::Table(t) = val { @@ -181,13 +189,14 @@ impl ExprEngine { time: f64, self_params: &HashMap, self_points: &HashMap, - env_nodes: &HashMap>, + env_nodes: &HashMap>, ) -> Option { let val = self.run(expr, time, self_params, self_points, env_nodes)?; match val { Value::String(s) => Some(s.to_str().ok()?.to_owned()), Value::Number(n) => Some(format!("{n}")), Value::Integer(i) => Some(format!("{i}")), + Value::Table(t) => t.get::("Value").ok(), _ => None, } } @@ -197,7 +206,7 @@ impl ExprEngine { time: f64, self_params: &HashMap, self_points: &HashMap, - env_nodes: &HashMap>, + env_nodes: &HashMap>, ) -> mlua::Result { let env = self.lua.create_table()?; let mt = self.lua.create_table()?; @@ -219,10 +228,20 @@ impl ExprEngine { // Missing node fields default to 0 so expressions don't nil-crash. let zero_mt = self.lua.create_table()?; zero_mt.set("__index", self.lua.create_function(|_, _args: MultiValue| Ok(0.0_f64))?)?; + let text_mt = self.lua.create_table()?; + text_mt.set("__tostring", self.lua.create_function(|_, this: mlua::Table| this.get::("Value"))?)?; for (node_name, params) in env_nodes { let nt = self.lua.create_table()?; for (pk, pv) in params { - nt.set(pk.as_str(), *pv)?; + match pv { + ExprValue::Number(n) => nt.set(pk.as_str(), *n)?, + ExprValue::Text(s) => { + let text = self.lua.create_table()?; + text.set("Value", s.as_str())?; + text.set_metatable(Some(text_mt.clone())); + nt.set(pk.as_str(), text)?; + } + } } nt.set_metatable(Some(zero_mt.clone())); env.set(node_name.as_str(), nt)?; -- 2.54.1