authoravatarclover caruso<git@paperclover.net>2026-12-01 05:39:03-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 06:26:56-08:00
log8cd212451d5213a9a3f96ccdfb9756f9ab15d994
tree9f55d542dd9dd027049d30864244a45bb167cfbf
parentf2a1716264a84ca38dc64149525f356134a5ff47
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Review pass 4: inspector, flow, expr/save, media and web fixes

- inspector: no panic on empty color edits, scrub coalesces on the control's primary channel, typed numbers commit to the node they were typed into (also on deselect), pages rebuild on structural change only, one catalog thread, expression badge on Point/Text rows - flow: rewire detaches after a 4px drag, keeps the wire's source output, pointer cancel and sanitize close open history groups, handle reach from rendered ports, SwitchElse/DeltaKeyer/ CheckerPieceGenerator port tables - model: expr depth/token caps, NaN comparisons, %.14g formatting, integer //,% by zero, trailing ';'; Loader timing saves into the first real clip - engine/web: EXR decode from virtual bytes, unique-basename virtual matching with 512 MiB cap, web_time Instant on wasm, surface reconfigure/retry, alpha mode, size clamp, GPU error surfacing Assisted-by: claude-sonnet-5.5

13 files changed, 842 insertions(+), 150 deletions(-)

crates/app/src/inspector/controls.rs+25-26
......@@ -14,32 +14,31 @@ const BOX_H: f32 = 20.0;
1414
1515pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
1616 let channels = def.channels.as_slice();
17 let animatable = match def.kind {
17 let keys = match def.kind {
1818 Kind::Slider | Kind::Screw | Kind::Range | Kind::Color | Kind::Checkbox | Kind::Toggles => true,
1919 Kind::Segmented | Kind::Combo => !def.fuid,
2020 Kind::Point | Kind::Text => false,
2121 };
22 let marks = if animatable { channels } else { &[] };
2322 match def.kind {
2423 Kind::Slider => {
2524 let ch = &channels[0];
2625 let sub = sub_labels(&ch.id);
2726 let height = px(if sub.is_some() { ROW_H + 14.0 } else { ROW_H });
28 row(ui, cx, &def.label, &ch.id, marks, height, |ui, cx| {
27 row(ui, cx, &def.label, &ch.id, channels, keys, height, |ui, cx| {
2928 let value = cx.number(ch);
3029 let mut spec = ui::Slider::new(value as f32, ch.scale[0] as f32, ch.scale[1] as f32, cx.default_of(ch) as f32);
3130 spec.step = ch.integer.then_some(1.0);
3231 spec.sub_labels = sub;
3332 spec.label = &def.label;
3433 if let Some(next) = ui::slider(ui, ("sld", cx.node.0, ch.id.as_str()), spec) {
35 cx.write_numbers(&def.label, &[(ch, f64::from(next))], true);
34 cx.write_numbers(&def.label, &[(ch, f64::from(next))], Some(&ch.id));
3635 }
3736 number_box(ui, cx, ch, None, value, px(52.0));
3837 });
3938 }
4039 Kind::Screw => {
4140 let ch = &channels[0];
42 row(ui, cx, &def.label, &ch.id, marks, px(ROW_H), |ui, cx| {
41 row(ui, cx, &def.label, &ch.id, channels, keys, px(ROW_H), |ui, cx| {
4342 let value = cx.number(ch);
4443 let mut spec = ui::ScrewControl::new(value as f32, cx.default_of(ch) as f32);
4544 spec.sensitivity = ((ch.scale[1] - ch.scale[0]) / 360.0).max(0.001) as f32;
......@@ -47,14 +46,14 @@ pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
4746 spec.width = fill();
4847 spec.label = &def.label;
4948 if let Some(next) = ui::screw_control(ui, ("scw", cx.node.0, ch.id.as_str()), spec) {
50 cx.write_numbers(&def.label, &[(ch, f64::from(next))], true);
49 cx.write_numbers(&def.label, &[(ch, f64::from(next))], Some(&ch.id));
5150 }
5251 number_box(ui, cx, ch, None, value, px(52.0));
5352 });
5453 }
5554 Kind::Range => {
5655 let [start, end] = [&channels[0], &channels[1]];
57 row(ui, cx, &def.label, &start.id, marks, px(ROW_H), |ui, cx| {
56 row(ui, cx, &def.label, &start.id, channels, keys, px(ROW_H), |ui, cx| {
5857 let [s, e] = [cx.number(start), cx.number(end)];
5958 let mut spec = ui::RangeSlider::new(
6059 s as f32,
......@@ -72,7 +71,7 @@ pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
7271 .filter(|&(_, old, new)| moved(old, new))
7372 .map(|(ch, _, new)| (ch, f64::from(new)))
7473 .collect();
75 cx.write_numbers(&def.label, &edits, true);
74 cx.write_numbers(&def.label, &edits, Some(&start.id));
7675 }
7776 number_box(ui, cx, start, None, s, px(44.0));
7877 number_box(ui, cx, end, None, e, px(44.0));
......@@ -81,26 +80,26 @@ pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
8180 Kind::Color => color(ui, cx, def),
8281 Kind::Checkbox => {
8382 let ch = &channels[0];
84 row(ui, cx, &def.label, &ch.id, marks, px(ROW_H), |ui, cx| {
83 row(ui, cx, &def.label, &ch.id, channels, keys, px(ROW_H), |ui, cx| {
8584 let on = cx.number(ch) >= 0.5;
8685 if checkbox(ui, ("chk", cx.node.0, ch.id.as_str()), on, &def.label) {
87 cx.write_numbers(&def.label, &[(ch, f64::from(u8::from(!on)))], false);
86 cx.write_numbers(&def.label, &[(ch, f64::from(u8::from(!on)))], None);
8887 }
8988 spacer(ui);
9089 });
9190 }
92 Kind::Toggles => row(ui, cx, &def.label, &channels[0].id, marks, px(ROW_H), |ui, cx| {
91 Kind::Toggles => row(ui, cx, &def.label, &channels[0].id, channels, keys, px(ROW_H), |ui, cx| {
9392 for (ch, name) in channels.iter().zip(&def.entries) {
9493 let on = cx.number(ch) >= 0.5;
9594 if toggle_button(ui, cx, ("tgl", cx.node.0, ch.id.as_str()), name, on) {
96 cx.write_numbers(name, &[(ch, f64::from(u8::from(!on)))], false);
95 cx.write_numbers(name, &[(ch, f64::from(u8::from(!on)))], None);
9796 }
9897 }
9998 spacer(ui);
10099 }),
101100 Kind::Segmented => {
102101 let ch = &channels[0];
103 row(ui, cx, &def.label, &ch.id, marks, px(ROW_H + 2.0), |ui, cx| {
102 row(ui, cx, &def.label, &ch.id, channels, keys, px(ROW_H + 2.0), |ui, cx| {
104103 let segments: Vec<_> = def.entries.iter().map(|e| ui::MultiSegment::text(e)).collect();
105104 let mut spec = ui::SegmentedControl::new(&segments, choice_index(cx, def));
106105 spec.width = fill();
......@@ -112,7 +111,7 @@ pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
112111 }
113112 Kind::Combo => {
114113 let ch = &channels[0];
115 row(ui, cx, &def.label, &ch.id, marks, px(ROW_H + 6.0), |ui, cx| {
114 row(ui, cx, &def.label, &ch.id, channels, keys, px(ROW_H + 6.0), |ui, cx| {
116115 let current = choice_index(cx, def);
117116 let items: Vec<_> = def
118117 .entries
......@@ -129,7 +128,7 @@ pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
129128 }
130129 Kind::Point => {
131130 let ch = &channels[0];
132 row(ui, cx, &def.label, &ch.id, marks, px(ROW_H), |ui, cx| {
131 row(ui, cx, &def.label, &ch.id, channels, keys, px(ROW_H), |ui, cx| {
133132 let point = cx.point(ch);
134133 for (axis, name) in ["X", "Y"].into_iter().enumerate() {
135134 ui.leaf(name, Spec { size: [px(10.0), fill()], text: Some(name), font_size: Some(10.0), color: Some(cx.p.text_dim), center: true, ..Spec::default() });
......@@ -151,8 +150,8 @@ fn spacer(ui: &mut Ui) {
151150 ui.leaf("pad", Spec { size: [px(0.0), fill()], ..Spec::default() });
152151}
153152
154/// Label column, `body`, then the expression badge and keyframe diamond of `marks`.
155fn row(ui: &mut Ui, cx: &mut Cx, label: &str, key: impl std::hash::Hash, marks: &[Channel], height: ui::Extent, body: impl FnOnce(&mut Ui, &mut Cx)) {
153/// Label column, `body`, then the expression badge of `marks` and, when `keys`, their keyframe diamond.
154fn row(ui: &mut Ui, cx: &mut Cx, label: &str, key: impl std::hash::Hash, marks: &[Channel], keys: bool, height: ui::Extent, body: impl FnOnce(&mut Ui, &mut Cx)) {
156155 ui.open(
157156 ("row", cx.node.0, key),
158157 Spec { size: [fill(), height], axis: ui::Axis::X, gap: 6.0, pad: [4.0, 1.0], ..Spec::default() },
......@@ -169,7 +168,7 @@ fn row(ui: &mut Ui, cx: &mut Cx, label: &str, key: impl std::hash::Hash, marks:
169168 if cx.has_expression(marks) {
170169 expression_badge(ui);
171170 }
172 if marks.is_empty() {
171 if !keys {
173172 ui.leaf("mark-gap", Spec { size: [px(MARK_W), fill()], ..Spec::default() });
174173 } else {
175174 let state = cx.key_state(marks);
......@@ -185,7 +184,7 @@ fn number_box(ui: &mut Ui, cx: &mut Cx, ch: &Channel, axis: Option<usize>, value
185184 let id = ui.id(("num", cx.node.0, ch.id.as_str(), axis));
186185 let focused = ui.focused() == Some(id);
187186 if focused && cx.edit.number.as_ref().is_none_or(|e| e.id != id) {
188 cx.edit.number = Some(NumberEdit { id, buf: format_value(ch, value), channel: ch.clone(), axis });
187 cx.edit.number = Some(NumberEdit { id, node: cx.node, buf: format_value(ch, value), channel: ch.clone(), axis });
189188 ui.focus_all(id);
190189 }
191190 let mut shown;
......@@ -289,7 +288,7 @@ fn write_choice(cx: &mut Cx, def: &ControlDef, index: usize) {
289288 if def.fuid {
290289 cx.write_value(&def.label, &ch.id, ParamValue::FuId(def.entries[index].clone()));
291290 } else {
292 cx.write_numbers(&def.label, &[(ch, index as f64)], false);
291 cx.write_numbers(&def.label, &[(ch, index as f64)], None);
293292 }
294293}
295294
......@@ -297,7 +296,7 @@ fn write_choice(cx: &mut Cx, def: &ControlDef, index: usize) {
297296fn color(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
298297 let channels = def.channels.as_slice();
299298 let current: Vec<f64> = channels.iter().map(|ch| cx.number(ch)).collect();
300 row(ui, cx, &def.label, ("group", &channels[0].id), channels, ui::children(), |ui, cx| {
299 row(ui, cx, &def.label, ("group", &channels[0].id), channels, true, ui::children(), |ui, cx| {
301300 let rgba = [0, 1, 2, 3].map(|i| current.get(i).map_or(1.0, |v| v.clamp(0.0, 1.0) as f32));
302301 let mut spec = ui::ColorPicker::new(rgba);
303302 spec.width = fill();
......@@ -308,19 +307,19 @@ fn color(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
308307 .iter()
309308 .zip(next)
310309 .zip(rgba)
311 .filter(|((_, new), old)| (new - old).abs() > 1e-6)
310 .filter(|((_, new), old)| (new - old).abs() > 1e-4)
312311 .map(|((ch, new), _)| (ch, f64::from(new)))
313312 .collect();
314 cx.write_numbers(&def.label, &edits, true);
313 cx.write_numbers(&def.label, &edits, Some(&channels[0].id));
315314 }
316315 });
317316 for (ch, name) in channels.iter().zip(["Red", "Green", "Blue", "Alpha"]) {
318 row(ui, cx, name, &ch.id, &[], px(ROW_H), |ui, cx| {
317 row(ui, cx, name, &ch.id, &[], false, px(ROW_H), |ui, cx| {
319318 let value = cx.number(ch);
320319 let mut spec = ui::Slider::new(value as f32, 0.0, 1.0, cx.default_of(ch) as f32);
321320 spec.label = name;
322321 if let Some(next) = ui::slider(ui, ("clr-sld", cx.node.0, ch.id.as_str()), spec) {
323 cx.write_numbers(&def.label, &[(ch, f64::from(next))], true);
322 cx.write_numbers(&def.label, &[(ch, f64::from(next))], Some(&ch.id));
324323 }
325324 number_box(ui, cx, ch, None, value, px(52.0));
326325 });
......@@ -330,7 +329,7 @@ fn color(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
330329/// A text well; edits apply live and fold into one undo step until it loses the keys.
331330fn text(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) {
332331 let ch = &def.channels[0];
333 row(ui, cx, &def.label, &ch.id, &[], px(ROW_H), |ui, cx| {
332 row(ui, cx, &def.label, &ch.id, &def.channels, false, px(ROW_H), |ui, cx| {
334333 let id = ui.id(("txt", cx.node.0, ch.id.as_str()));
335334 let focused = ui.focused() == Some(id);
336335 let model = cx.comp.node(cx.node).static_str(&ch.id).unwrap_or(&def.default_text).to_owned();
crates/app/src/inspector/edit.rs+15-8
......@@ -13,6 +13,8 @@ pub(super) const SCRUB_GRACE: Duration = Duration::from_millis(350);
1313/// A numeric box being typed into; it commits when it loses the keys.
1414pub(super) struct NumberEdit {
1515 pub id: ui::Id,
16 /// The node the box was focused on; selection may move on before the commit.
17 pub node: NodeId,
1618 pub buf: String,
1719 pub channel: Channel,
1820 /// `Some(0|1)` edits one axis of a Point input.
......@@ -76,11 +78,14 @@ impl Cx<'_> {
7678 }
7779 }
7880
79 /// Writes numbers, as a keyframe where the input is animated. A `drag` folds into one undo
80 /// step per input until it rests; anything else is its own step.
81 pub fn write_numbers(&mut self, label: &str, edits: &[(&Channel, f64)], drag: bool) {
82 if drag {
83 let key = format!("scrub:{}:{}", self.node.0, edits[0].0.id);
81 /// Writes numbers, as a keyframe where the input is animated. A drag, named by its control's
82 /// primary channel, folds into one undo step until it rests; anything else is its own step.
83 pub fn write_numbers(&mut self, label: &str, edits: &[(&Channel, f64)], drag: Option<&str>) {
84 if edits.is_empty() {
85 return;
86 }
87 if let Some(primary) = drag {
88 let key = format!("scrub:{}:{primary}", self.node.0);
8489 self.history.push_coalesced(self.comp, format!("Adjust {label}"), key);
8590 self.edit.last_scrub = Some(self.now);
8691 } else {
......@@ -105,12 +110,13 @@ impl Cx<'_> {
105110 self.actions.push(InspectorAction::ParamEdited(self.node));
106111 }
107112
108 /// Commits a numeric box once it has lost the keys.
113 /// Commits a numeric box once it has lost the keys, onto the node it was typed into.
109114 pub fn commit_number(&mut self, edit: NumberEdit) {
110115 let Ok(value) = edit.buf.trim().parse::<f64>() else { return };
111 if !value.is_finite() {
116 if !value.is_finite() || edit.node.0 >= self.comp.nodes.len() {
112117 return;
113118 }
119 let selected = std::mem::replace(&mut self.node, edit.node);
114120 let ch = &edit.channel;
115121 match edit.axis {
116122 Some(axis) => {
......@@ -118,8 +124,9 @@ impl Cx<'_> {
118124 point[axis] = value;
119125 self.write_value(&ch.id, &ch.id, ParamValue::Point(point));
120126 }
121 None => self.write_numbers(&ch.id, &[(ch, value)], false),
127 None => self.write_numbers(&ch.id, &[(ch, value)], None),
122128 }
129 self.node = selected;
123130 }
124131
125132 /// Keys every channel at the current frame, or removes those keys when all already have one.
crates/app/src/inspector/mod.rs+57-8
......@@ -65,11 +65,11 @@ impl InspectorPalette {
6565 }
6666}
6767
68/// Pages for the selected node's own `UserControls` and stray inputs, rebuilt when the comp
69/// revision moves.
68/// Pages for the selected node's own `UserControls` and stray inputs, rebuilt when the node's
69/// shape (see [`pages_key`]) changes rather than on every value edit.
7070struct NodePages {
7171 node: NodeId,
72 revision: u64,
72 key: u64,
7373 pages: Vec<Page>,
7474}
7575
......@@ -90,9 +90,11 @@ pub struct InspectorState {
9090impl InspectorState {
9191 pub fn new(theme: &ui::Theme) -> Self {
9292 // Parse the catalog off the UI thread; frames wait on it with a placeholder.
93 std::thread::spawn(|| {
94 catalog::catalog();
95 });
93 if catalog::ready().is_none() {
94 std::thread::spawn(|| {
95 catalog::catalog();
96 });
97 }
9698 Self {
9799 palette: InspectorPalette::from_theme(theme),
98100 expr: ExprEngine::new(),
......@@ -133,6 +135,7 @@ impl InspectorState {
133135 ui::Spec { size: [ui::fill(), ui::fill()], axis: ui::Axis::Y, fill: Some(p.bg), ..ui::Spec::default() },
134136 );
135137 let Some(node_id) = selected.filter(|id| id.0 < comp.nodes.len()) else {
138 self.commit_orphans(comp, history, &mut actions);
136139 chrome::empty_state(ui, p);
137140 chrome::footer(ui, p, stats);
138141 ui.close();
......@@ -152,8 +155,9 @@ impl InspectorState {
152155 .or_insert_with(|| dynamic::curated_layout(&kind).unwrap_or_default()),
153156 };
154157
155 if self.node_pages.as_ref().is_none_or(|n| n.node != node_id || n.revision != comp.revision) {
156 self.node_pages = Some(NodePages { node: node_id, revision: comp.revision, pages: node_pages(comp, node_id, layout) });
158 let key = pages_key(comp, node_id);
159 if self.node_pages.as_ref().is_none_or(|n| n.node != node_id || n.key != key) {
160 self.node_pages = Some(NodePages { node: node_id, key, pages: node_pages(comp, node_id, layout) });
157161 }
158162 let dynamic_pages = self.node_pages.as_ref().map_or(&[][..], |n| n.pages.as_slice());
159163
......@@ -215,6 +219,24 @@ impl InspectorState {
215219 actions
216220 }
217221
222 /// With nothing selected no box can keep the keys, so a typed value lands where it was typed.
223 fn commit_orphans(&mut self, comp: &mut Comp, history: &mut CompHistory, actions: &mut Vec<InspectorAction>) {
224 self.edit.text = None;
225 let Some(number) = self.edit.number.take() else { return };
226 let mut cx = edit::Cx {
227 comp,
228 history,
229 actions,
230 node: number.node,
231 frame: 0.0,
232 now: std::time::Instant::now(),
233 p: self.palette,
234 expr: &self.expr,
235 edit: &mut self.edit,
236 };
237 cx.commit_number(number);
238 }
239
218240 fn loading(&self, ui: &mut ui::Ui, p: InspectorPalette, stats: &EvalStats, actions: Vec<InspectorAction>) -> Vec<InspectorAction> {
219241 ui.leaf(
220242 "insp-loading",
......@@ -244,6 +266,33 @@ fn settle_edits(ui: &mut ui::Ui, cx: &mut edit::Cx) {
244266 }
245267}
246268
269/// What `node_pages` reads, minus values: kind, `UserControls` ids, and each input's name,
270/// value type and whether it is driven or wired. Order-independent over the input map.
271fn pages_key(comp: &Comp, node: NodeId) -> u64 {
272 use std::hash::{Hash, Hasher};
273 let hash = |item: &dyn Fn(&mut std::hash::DefaultHasher)| {
274 let mut h = std::hash::DefaultHasher::new();
275 item(&mut h);
276 h.finish()
277 };
278 let n = comp.node(node);
279 let controls = n.raw.get_table("UserControls").map_or(0, |t| {
280 t.entries.iter().fold(t.entries.len() as u64, |acc, (key, _)| match key {
281 model::LuaKey::Str(id) => acc.wrapping_add(hash(&|h| id.hash(h))),
282 _ => acc,
283 })
284 });
285 let inputs = n.inputs.iter().fold(0u64, |acc, (key, b)| {
286 let wired = b.source_op.as_deref().is_some_and(|op| comp.node_by_name.contains_key(op));
287 acc.wrapping_add(hash(&|h| {
288 key.hash(h);
289 b.value.as_ref().map(std::mem::discriminant).hash(h);
290 (b.expression.is_some(), b.source_op.is_some(), wired).hash(h);
291 }))
292 });
293 hash(&|h| (&n.kind, controls, inputs).hash(h))
294}
295
247296/// The node's `UserControls` (one page per `ICS_ControlPage`) and inputs no catalog row covers.
248297fn node_pages(comp: &Comp, node: NodeId, layout: &ToolLayout) -> Vec<Page> {
249298 let mut by_page: Vec<(String, Vec<catalog::InputDef>)> = Vec::new();
crates/app/src/inspector/tests.rs+80
......@@ -441,4 +441,84 @@ mod catalog_layout {
441441 assert!(h.history.undo(&mut h.comp));
442442 assert_eq!(h.number("Blend"), Some(0.2));
443443 }
444
445 fn type_into(h: &mut Harness, well: [f32; 4], text: &str) {
446 h.click(center(well));
447 for ch in text.chars() {
448 let key = winit::keyboard::Key::Character(ch.to_string().into());
449 h.ui.event(ui::Event::Key { key, text: Some(ch.to_string()), modifiers: Default::default() });
450 h.frame(16);
451 }
452 }
453
454 /// A color drag that moves no RGB channel (alpha on an RGB-only group, hue on gray) reaches
455 /// `write_numbers` with nothing to write.
456 #[test]
457 fn empty_edits_write_nothing_and_never_panic() {
458 let mut h = Harness::new("Background", 0);
459 let (node, mut actions) = (h.node, Vec::new());
460 let channel = &find("Background", "TopLeftRed").channels[0];
461 let mut edit = super::super::edit::EditState::default();
462 let mut cx = super::super::edit::Cx {
463 comp: &mut h.comp,
464 history: &mut h.history,
465 actions: &mut actions,
466 node,
467 frame: 0.0,
468 now: h.at,
469 p: h.state.palette,
470 expr: &h.state.expr,
471 edit: &mut edit,
472 };
473 cx.write_numbers("Color", &[], Some(&channel.id));
474 cx.write_numbers("Color", &[], None);
475 assert!(actions.is_empty() && edit.last_scrub.is_none());
476 assert!(!h.history.undo(&mut h.comp));
477 }
478
479 #[test]
480 fn typed_value_commits_to_the_node_it_was_typed_into() {
481 let mut h = Harness::new("Blur", 0);
482 h.comp = Comp::from_fusion_str("Composition { Tools = ordered() { Blur1 = Blur {}, Merge1 = Merge {}, }, }").expect("comp");
483 h.node = h.comp.find_node("Blur1").expect("blur");
484 h.frame(0);
485 let well = h.rect(0, "XBlurSize", ("num", h.node.0, "XBlurSize", None::<usize>));
486 type_into(&mut h, well, "7");
487 let blur = h.node;
488
489 h.node = h.comp.find_node("Merge1").expect("merge");
490 h.frame(16);
491 h.frame(16);
492 assert_eq!(h.comp.node(blur).static_number("XBlurSize"), Some(7.0));
493 assert!(h.comp.node(h.node).inputs.values().all(|b| b.value.is_none()), "Merge1 was touched");
494 }
495
496 #[test]
497 fn typed_value_commits_to_its_node_on_deselect() {
498 let mut h = Harness::new("Blur", 0);
499 let well = h.rect(0, "XBlurSize", ("num", h.node.0, "XBlurSize", None::<usize>));
500 type_into(&mut h, well, "9");
501 h.at += std::time::Duration::from_millis(16);
502 h.ui.begin([360.0, 900.0], 1.0, h.at);
503 let pane = ui::Id::ROOT.child(PANE);
504 h.state.build_ui(&mut h.ui, pane, &mut h.comp, &mut h.history, None, 0.0, &engine::EvalStats::default());
505 h.ui.end();
506 assert_eq!(h.number("XBlurSize"), Some(9.0));
507 assert!(h.state.edit.number.is_none());
508 }
509
510 #[test]
511 fn pages_are_not_rebuilt_by_value_edits() {
512 let mut h = Harness::new("Merge", 2);
513 let key = |h: &Harness| h.state.node_pages.as_ref().map(|n| n.key);
514 h.comp.set_input_value(h.node, "Blend", model::ParamValue::Number(0.2));
515 h.frame(16);
516 let before = key(&h);
517 h.comp.set_input_value(h.node, "Blend", model::ParamValue::Number(0.7));
518 h.frame(16);
519 assert_eq!(key(&h), before);
520 h.comp.set_input_value(h.node, "Stray", model::ParamValue::Number(1.0));
521 h.frame(16);
522 assert_ne!(key(&h), before);
523 }
444524}
crates/engine/src/media.rs+91-24
......@@ -58,29 +58,60 @@ struct VirtualFile {
5858/// In-memory files that shadow the filesystem for still and sequence loading, since `wasm32` has no `std::fs`.
5959static VIRTUAL_FILES: RwLock<Vec<VirtualFile>> = RwLock::new(Vec::new());
6060
61/// Total bytes registered virtual files may hold, so dropping a huge folder cannot exhaust the tab.
62const MAX_VIRTUAL_BYTES: usize = 512 * 1024 * 1024;
63
64/// `path`'s components with `.`, empty and resolved `..` segments removed.
6165fn path_parts(path: &Path) -> Vec<String> {
62 path.to_string_lossy()
63 .split(['/', '\\'])
64 .filter(|p| !p.is_empty() && *p != ".")
65 .map(str::to_owned)
66 .collect()
66 let mut parts: Vec<String> = Vec::new();
67 for part in path.to_string_lossy().split(['/', '\\']) {
68 match part {
69 "" | "." => {}
70 ".." => {
71 parts.pop();
72 }
73 _ => parts.push(part.to_owned()),
74 }
75 }
76 parts
77}
78
79/// The registered file whose path shares the most trailing components with `want`, so a comp's
80/// absolute `Loader` path still finds a file dropped under a relative one. Exact case wins over
81/// case-insensitive; a tie (`/A/bg.png` vs `/B/bg.png` for `bg.png`) matches nothing.
82fn find_virtual<'a>(files: &'a [VirtualFile], want: &[String]) -> Option<&'a VirtualFile> {
83 let exact = |a: &String, b: &String| a == b;
84 let folded = |a: &String, b: &String| a.to_lowercase() == b.to_lowercase();
85 [&exact as &dyn Fn(&String, &String) -> bool, &folded].into_iter().find_map(|same| {
86 let shared = |f: &VirtualFile| f.parts.iter().rev().zip(want.iter().rev()).take_while(|(a, b)| same(a, b)).count();
87 let best = files.iter().map(shared).max().filter(|&n| n > 0)?;
88 let mut tied = files.iter().filter(|f| shared(f) == best);
89 match (tied.next(), tied.next()) {
90 (Some(file), None) => Some(Some(file)),
91 _ => Some(None),
92 }
93 })?
6794}
6895
69/// Bytes of the virtual file sharing the longest run of trailing path components with `path`, so a
70/// comp's absolute `Loader` path still finds a file registered under a dropped folder's relative path.
7196fn virtual_bytes(path: &Path) -> Option<Arc<[u8]>> {
7297 let files = VIRTUAL_FILES.read().ok()?;
7398 if files.is_empty() {
7499 return None;
75100 }
76 let want = path_parts(path);
77 let shared = |f: &VirtualFile| f.parts.iter().rev().zip(want.iter().rev()).take_while(|(a, b)| a == b).count();
78 files
79 .iter()
80 .map(|f| (shared(f), f))
81 .filter(|(n, _)| *n > 0)
82 .max_by_key(|(n, _)| *n)
83 .map(|(_, f)| Arc::clone(&f.bytes))
101 find_virtual(&files, &path_parts(path)).map(|f| Arc::clone(&f.bytes))
102}
103
104/// Adds or replaces `parts`, refusing when `files` would then hold more than `cap` bytes.
105fn insert_capped(files: &mut Vec<VirtualFile>, cap: usize, parts: Vec<String>, bytes: Arc<[u8]>) -> bool {
106 let held: usize = files.iter().filter(|f| f.parts != parts).map(|f| f.bytes.len()).sum();
107 if held.saturating_add(bytes.len()) > cap {
108 return false;
109 }
110 match files.iter_mut().find(|f| f.parts == parts) {
111 Some(existing) => existing.bytes = bytes,
112 None => files.push(VirtualFile { parts, bytes }),
113 }
114 true
84115}
85116
86117fn path_exists(path: &Path) -> bool {
......@@ -128,15 +159,11 @@ impl MediaCache {
128159 }
129160 }
130161
131 /// Registers `bytes` as the file at `path` for every `MediaCache` in the process.
132 pub fn insert_virtual_bytes(path: impl AsRef<Path>, bytes: impl Into<Arc<[u8]>>) {
133 let parts = path_parts(path.as_ref());
134 let bytes = bytes.into();
135 let Ok(mut files) = VIRTUAL_FILES.write() else { return };
136 match files.iter_mut().find(|f| f.parts == parts) {
137 Some(existing) => existing.bytes = bytes,
138 None => files.push(VirtualFile { parts, bytes }),
139 }
162 /// Registers `bytes` as the file at `path` for every `MediaCache` in the process. `false`
163 /// when the files held would pass [`MAX_VIRTUAL_BYTES`], leaving the registry unchanged.
164 pub fn insert_virtual_bytes(path: impl AsRef<Path>, bytes: impl Into<Arc<[u8]>>) -> bool {
165 let Ok(mut files) = VIRTUAL_FILES.write() else { return false };
166 insert_capped(&mut files, MAX_VIRTUAL_BYTES, path_parts(path.as_ref()), bytes.into())
140167 }
141168
142169 pub fn clear_virtual_bytes() {
......@@ -955,4 +982,44 @@ mod tests {
955982 assert!(path_exists(Path::new("elsewhere/vf_seq.0002.png")));
956983 assert!(!path_exists(Path::new("vf_proj/vf_seq.0003.png")));
957984 }
985
986 fn file(path: &str, len: usize) -> VirtualFile {
987 VirtualFile { parts: path_parts(Path::new(path)), bytes: vec![0; len].into() }
988 }
989
990 fn found<'a>(files: &'a [VirtualFile], path: &str) -> Option<&'a [String]> {
991 find_virtual(files, &path_parts(Path::new(path))).map(|f| f.parts.as_slice())
992 }
993
994 #[test]
995 fn virtual_paths_normalize_dots_and_separators() {
996 assert_eq!(path_parts(Path::new("/a/./b/../c\\d.png")), ["a", "c", "d.png"]);
997 assert_eq!(path_parts(Path::new("../../x.png")), ["x.png"]);
998 }
999
1000 #[test]
1001 fn virtual_matching_prefers_exact_and_rejects_ambiguous_basenames() {
1002 let files = [file("A/bg.png", 1), file("B/bg.png", 1), file("only.png", 1), file("Proj/Seq.exr", 1)];
1003 assert_eq!(found(&files, "/x/A/bg.png"), Some(&["A".to_owned(), "bg.png".to_owned()][..]));
1004 assert_eq!(found(&files, "/x/../B/./bg.png").map(<[String]>::len), Some(2));
1005 assert_eq!(found(&files, "/C/bg.png"), None, "two files share the basename");
1006 assert_eq!(found(&files, "bg.png"), None);
1007 assert!(found(&files, "/deep/elsewhere/only.png").is_some());
1008 assert!(found(&files, "/proj/seq.EXR").is_some(), "case-insensitive fallback");
1009 assert_eq!(found(&files, "/a/missing.png"), None);
1010 }
1011
1012 #[test]
1013 fn virtual_files_stop_at_the_memory_cap() {
1014 let mut files = Vec::new();
1015 let put = |files: &mut Vec<VirtualFile>, name: &str, len: usize| {
1016 insert_capped(files, 10, path_parts(Path::new(name)), vec![0; len].into())
1017 };
1018 assert!(put(&mut files, "a", 6));
1019 assert!(!put(&mut files, "b", 5));
1020 assert!(put(&mut files, "b", 4));
1021 assert!(put(&mut files, "a", 6), "replacing a file frees its old bytes");
1022 assert!(!put(&mut files, "a", 7));
1023 assert_eq!(files.iter().map(|f| f.bytes.len()).sum::<usize>(), 10);
1024 }
9581025}
crates/engine/src/media/exr.rs+31-2
......@@ -150,13 +150,24 @@ pub(super) fn decode_exr_rgba(
150150 blue_name: Option<&str>,
151151 alpha_name: Option<&str>,
152152 post_multiply: bool,
153) -> Option<DecodedImage> {
154 let names = [red_name, green_name, blue_name, alpha_name];
155 match super::virtual_bytes(path) {
156 Some(bytes) => decode_exr_from(std::io::Cursor::new(bytes), names, post_multiply),
157 None => decode_exr_from(std::io::BufReader::new(std::fs::File::open(path).ok()?), names, post_multiply),
158 }
159}
160
161fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(
162 reader: R,
163 [red_name, green_name, blue_name, alpha_name]: [Option<&str>; 4],
164 post_multiply: bool,
153165) -> Option<DecodedImage> {
154166 use ::exr::block::reader::ChunksReader;
155167 use ::exr::meta::attribute::SampleType;
156168 use ::exr::prelude::*;
157169
158 let file = std::fs::File::open(path).ok()?;
159 let chunks_reader = ::exr::block::read(std::io::BufReader::new(file), false).ok()?;
170 let chunks_reader = ::exr::block::read(reader, false).ok()?;
160171 let first_header = chunks_reader.headers().first()?;
161172 let w = first_header.layer_size.width();
162173 let h = first_header.layer_size.height();
......@@ -278,3 +289,21 @@ pub(super) fn decode_exr_rgba(
278289 rgba_f32: Some(Arc::new(raw_f32)),
279290 })
280291}
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296 use crate::media::MediaCache;
297
298 #[test]
299 fn dropped_exr_bytes_decode_without_a_file_on_disk() {
300 let pixels = image::Rgba32FImage::from_pixel(2, 1, image::Rgba([2.5, 0.5, 0.0, 1.0]));
301 let mut out = std::io::Cursor::new(Vec::new());
302 image::DynamicImage::ImageRgba32F(pixels).write_to(&mut out, image::ImageFormat::OpenExr).unwrap();
303 assert!(MediaCache::insert_virtual_bytes("vexr_drop/frame.exr", out.into_inner()));
304
305 let decoded = decode_exr_rgba(Path::new("/not/on/disk/vexr_drop/frame.exr"), None, None, None, None, false).unwrap();
306 assert_eq!(decoded.size, [2, 1]);
307 assert_eq!(&decoded.rgba_f32.unwrap()[..4], &[2.5, 0.5, 0.0, 1.0]);
308 }
309}
crates/engine/src/profile.rs+3
......@@ -3,7 +3,10 @@
33use model::{Comp, NodeId};
44use std::collections::HashMap;
55use std::fmt::Write as _;
6#[cfg(not(target_arch = "wasm32"))]
67use std::time::Instant;
8#[cfg(target_arch = "wasm32")]
9use web_time::Instant;
710
811/// Profiling telemetry for a single node lookup or evaluation within a frame.
912#[derive(Clone, Debug, PartialEq)]
crates/flow/src/lib.rs+197-12
......@@ -77,10 +77,36 @@ struct ModalTransform {
7777#[derive(Clone, Debug)]
7878struct WireDrag {
7979 src: NodeId,
80 /// The output the wire leaves: the detached binding's own, else the source tool's default.
81 src_output: String,
8082 cursor_local: [f32; 2],
8183 target: Option<DropTarget>,
8284 /// Set when dragging an existing connected input off to disconnect/rewire.
8385 detached_from: Option<(NodeId, String)>,
86 /// Press point of a rewire drag that has not yet moved [`DETACH_DRAG`]; the wire stays
87 /// connected until it does, so a plain click changes nothing.
88 pending: Option<[f32; 2]>,
89}
90
91impl WireDrag {
92 /// Whether this drag has detached its wire inside an open history group.
93 fn owns_group(&self) -> bool {
94 self.detached_from.is_some() && self.pending.is_none()
95 }
96}
97
98/// Screen pixels a pressed input triangle must travel before its wire detaches.
99const DETACH_DRAG: f32 = 4.0;
100
101/// Output a wire from a `kind` tool leaves by: masks and materials have their own.
102fn default_output(kind: &str) -> &'static str {
103 if kind.ends_with("Mask") {
104 "Mask"
105 } else if kind.starts_with("Mtl") {
106 "MaterialOutput"
107 } else {
108 "Output"
109 }
84110}
85111
86112#[derive(Clone, Debug)]
......@@ -182,6 +208,8 @@ pub struct FlowView {
182208 hovered_wire: Option<WireRef>,
183209 modal: Option<ModalTransform>,
184210 wire_drag: Option<WireDrag>,
211 /// A gesture that owned a history group was dropped without its history; the next input closes it.
212 orphaned_group: bool,
185213 box_select: Option<BoxSelect>,
186214 panning: Option<([f32; 2], [f32; 2])>,
187215 lmb_drag_node: Option<(NodeId, [f32; 2], bool)>,
......@@ -208,6 +236,7 @@ impl FlowView {
208236 hovered_wire: None,
209237 modal: None,
210238 wire_drag: None,
239 orphaned_group: false,
211240 box_select: None,
212241 panning: None,
213242 lmb_drag_node: None,
......@@ -282,8 +311,7 @@ impl FlowView {
282311 self.hovered_node = None;
283312 self.hovered_handle = None;
284313 self.hovered_wire = None;
285 self.modal = None;
286 self.wire_drag = None;
314 self.abandon_gestures();
287315 self.box_select = None;
288316 self.lmb_drag_node = None;
289317 self.last_click = None;
......@@ -310,12 +338,17 @@ impl FlowView {
310338 }
311339 self.hovered_handle = None;
312340 self.hovered_wire = None;
313 self.modal = None;
314 self.wire_drag = None;
341 self.abandon_gestures();
315342 self.lmb_drag_node = None;
316343 self.last_click = None;
317344 }
318345
346 /// Drops in-flight gestures that have no history to cancel through.
347 fn abandon_gestures(&mut self) {
348 let wire = self.wire_drag.take().is_some_and(|wd| wd.owns_group());
349 self.orphaned_group |= self.modal.take().is_some() || wire;
350 }
351
319352 /// Computes a clean world-space spawn position for a newly added node.
320353 pub fn spawn_position(&self, comp: &Comp, is_generator: bool) -> [f32; 2] {
321354 if let Some(sel_id) = self.primary.filter(|id| id.0 < comp.nodes.len()) {
......@@ -499,11 +532,20 @@ impl FlowView {
499532
500533 /// Drops an in-flight wire drag; a detached input is wired back.
501534 fn cancel_wire_drag(&mut self, comp: &mut Comp, history: &mut CompHistory, actions: &mut Vec<FlowAction>) {
502 if self.wire_drag.take().is_some_and(|wd| wd.detached_from.is_some()) && history.cancel_group(comp) {
535 if self.wire_drag.take().is_some_and(|wd| wd.owns_group()) && history.cancel_group(comp) {
503536 actions.push(FlowAction::GraphMutated(None));
504537 }
505538 }
506539
540 /// Ends every held gesture, as the window losing focus must.
541 fn cancel_gestures(&mut self, comp: &mut Comp, history: &mut CompHistory, actions: &mut Vec<FlowAction>) {
542 self.cancel_modal(comp, history);
543 self.cancel_wire_drag(comp, history, actions);
544 self.panning = None;
545 self.box_select = None;
546 self.lmb_drag_node = None;
547 }
548
507549 fn handle_key(
508550 &mut self,
509551 comp: &mut Comp,
......@@ -699,8 +741,12 @@ impl FlowView {
699741 ) -> Vec<FlowAction> {
700742 let mut actions = Vec::new();
701743 self.pointer_local = [pointer_window[0] - rect[0], pointer_window[1] - rect[1]];
744 if std::mem::take(&mut self.orphaned_group) {
745 history.commit_group(comp);
746 }
702747
703748 match event {
749 ui::Event::PointerCancelled => self.cancel_gestures(comp, history, &mut actions),
704750 ui::Event::PointerMoved(p) => {
705751 self.pointer_local = [p[0] - rect[0], p[1] - rect[1]];
706752 if let Some((start_p, start_pan)) = self.panning {
......@@ -711,6 +757,17 @@ impl FlowView {
711757 } else if self.modal.is_some() {
712758 self.apply_modal(comp, modifiers.shift_key());
713759 } else if self.wire_drag.is_some() {
760 if let Some(wd) = &mut self.wire_drag {
761 if let Some((press, (dst, port))) = wd.pending.zip(wd.detached_from.as_ref()) {
762 if (press[0] - self.pointer_local[0]).hypot(press[1] - self.pointer_local[1]) <= DETACH_DRAG {
763 return actions;
764 }
765 history.begin_group(comp, "Rewire");
766 comp.disconnect(*dst, port);
767 actions.push(FlowAction::GraphMutated(Some(*dst)));
768 wd.pending = None;
769 }
770 }
714771 let hit = self.hit_drop_target(comp, self.pointer_local);
715772 if let Some(wd) = &mut self.wire_drag {
716773 wd.cursor_local = self.pointer_local;
......@@ -788,25 +845,27 @@ impl FlowView {
788845 } else if let Some((src, None)) = handle {
789846 self.wire_drag = Some(WireDrag {
790847 src,
848 src_output: default_output(&comp.node(src).kind).to_owned(),
791849 cursor_local: self.pointer_local,
792850 target: None,
793851 detached_from: None,
852 pending: None,
794853 });
795 } else if let Some((dst, Some(port), src)) = handle.and_then(|(dst, port)| {
854 } else if let Some((dst, port, src)) = handle.and_then(|(dst, port)| {
796855 let port = port?;
797856 let src = self.upstream_of(comp, comp.node(dst), port)?;
798 Some((dst, Some(port.to_owned()), src))
857 Some((dst, port.to_owned(), src))
799858 }) {
800859 // Dragging a connected triangle detaches it: drop on another triangle to move
801860 // the wire, or on empty canvas to disconnect.
802 history.begin_group(comp, "Rewire");
803 comp.disconnect(dst, &port);
804 actions.push(FlowAction::GraphMutated(Some(dst)));
861 let src_output = comp.node(dst).inputs[&port].source_output.clone();
805862 self.wire_drag = Some(WireDrag {
806863 src,
864 src_output: src_output.unwrap_or_else(|| default_output(&comp.node(src).kind).to_owned()),
807865 cursor_local: self.pointer_local,
808866 target: None,
809867 detached_from: Some((dst, port)),
868 pending: Some(self.pointer_local),
810869 });
811870 } else if let Some(nid) = self.hit_node(comp, self.pointer_local) {
812871 let double = self.last_click.is_some_and(|(t, prev)| prev == nid && at.duration_since(t) <= DOUBLE_CLICK);
......@@ -851,7 +910,7 @@ impl FlowView {
851910 self.confirm_modal(comp, history, &mut actions);
852911 }
853912 }
854 if let Some(wd) = self.wire_drag.take() {
913 if let Some(wd) = self.wire_drag.take().filter(|wd| wd.pending.is_none()) {
855914 let detached = wd.detached_from.is_some();
856915 let target = self.hit_drop_target(comp, self.pointer_local).map(|(node, port)| (node, port.to_owned()));
857916 if let Some((dst, port)) = target {
......@@ -864,7 +923,7 @@ impl FlowView {
864923 if !detached {
865924 history.begin_group(comp, "Connect");
866925 }
867 match comp.connect_output(wd.src, "Output", dst, &port) {
926 match comp.connect_output(wd.src, &wd.src_output, dst, &port) {
868927 Ok(()) => {
869928 history.commit_group(comp);
870929 actions.push(FlowAction::GraphMutated(Some(dst)));
......@@ -1286,7 +1345,10 @@ mod tests {
12861345 ModifiersState::empty(),
12871346 );
12881347 assert!(flow.wire_drag.is_some());
1348 assert_eq!(source(&comp, merge, "Background").as_deref(), Some("BG1"), "a bare press detaches nothing");
1349 flow.input(&mut comp, &mut history, ui::Event::PointerMoved([port[0] + 30.0, port[1] + 30.0]), rect, [port[0] + 30.0, port[1] + 30.0], ModifiersState::empty());
12891350 assert!(comp.node(merge).inputs["Background"].source_op.is_none());
1351 assert!(history.in_group());
12901352
12911353 let acts = key(&mut flow, &mut comp, &mut history, Key::Named(NamedKey::Escape), ModifiersState::empty());
12921354 assert!(flow.wire_drag.is_none());
......@@ -1460,4 +1522,127 @@ mod tests {
14601522 assert!(flow.modal.is_some());
14611523 assert!(history.in_group());
14621524 }
1525
1526 fn button(pressed: bool) -> ui::Event {
1527 ui::Event::Button { button: MouseButton::Left, pressed, at: Instant::now() }
1528 }
1529
1530 #[test]
1531 fn clicking_a_connected_triangle_without_dragging_changes_nothing() {
1532 let (mut comp, mut flow, mut history) = wire_flow();
1533 let merge = id(&comp, "Merge1");
1534 let tri = input_center(&flow, &comp, merge, "Background");
1535 let revision = comp.revision;
1536 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(tri), tri);
1537 send(&mut flow, &mut comp, &mut history, button(true), tri);
1538 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved([tri[0] + 2.0, tri[1]]), tri);
1539 assert!(!history.in_group());
1540 send(&mut flow, &mut comp, &mut history, button(false), [tri[0] + 2.0, tri[1]]);
1541 assert!(flow.wire_drag.is_none());
1542 assert_eq!(source(&comp, merge, "Background").as_deref(), Some("BG1"));
1543 assert_eq!(comp.revision, revision);
1544 assert!(!history.can_undo() && !history.in_group());
1545 }
1546
1547 #[test]
1548 fn rewiring_keeps_the_wires_own_output() {
1549 let mut comp = Comp::from_fusion_str(
1550 r#"Composition {
1551 Tools = ordered() {
1552 Ellipse1 = EllipseMask { ViewInfo = OperatorInfo { Pos = { 0, 0 } }, },
1553 Checker = Fuse.CheckerPieceGenerator { ViewInfo = OperatorInfo { Pos = { 0, 80 } }, },
1554 Mtl1 = MtlBlinn { ViewInfo = OperatorInfo { Pos = { 0, 160 } }, },
1555 Merge1 = Merge {
1556 Inputs = {
1557 Foreground = Input { SourceOp = "Checker", Source = "ExtraScale" },
1558 EffectMask = Input { SourceOp = "Ellipse1", Source = "Mask" },
1559 },
1560 ViewInfo = OperatorInfo { Pos = { 160, 0 } },
1561 },
1562 Blur1 = Blur { ViewInfo = OperatorInfo { Pos = { 160, 120 } }, },
1563 Blur2 = Blur { ViewInfo = OperatorInfo { Pos = { 160, 240 } }, },
1564 },
1565 }"#,
1566 )
1567 .expect("parse comp");
1568 let mut flow = FlowView::new(&ui::Theme::new(&theme::KNIFE, true));
1569 (flow.size, flow.pan, flow.zoom) = ([800.0, 600.0], [80.0, 60.0], 1.0);
1570 let mut history = CompHistory::new();
1571 let (merge, blur, blur2) = (id(&comp, "Merge1"), id(&comp, "Blur1"), id(&comp, "Blur2"));
1572 let output = |comp: &Comp, node: NodeId, port: &str| comp.node(node).inputs[port].source_output.clone();
1573
1574 let body = flow.world_to_local(comp.node(blur).pos);
1575 let from = input_center(&flow, &comp, merge, "Foreground");
1576 drag(&mut flow, &mut comp, &mut history, from, body);
1577 assert_eq!(output(&comp, blur, "Input").as_deref(), Some("ExtraScale"));
1578
1579 let from = input_center(&flow, &comp, merge, "EffectMask");
1580 let to = input_center(&flow, &comp, blur, "EffectMask");
1581 drag(&mut flow, &mut comp, &mut history, from, to);
1582 assert_eq!(output(&comp, blur, "EffectMask").as_deref(), Some("Mask"));
1583
1584 // A fresh wire picks the output its source tool has.
1585 let body = flow.world_to_local(comp.node(blur2).pos);
1586 for (name, expected) in [("Ellipse1", "Mask"), ("Mtl1", "MaterialOutput"), ("Checker", "Output")] {
1587 let from = output_center(&flow, &comp, id(&comp, name));
1588 drag(&mut flow, &mut comp, &mut history, from, body);
1589 assert_eq!(output(&comp, blur2, "Input").as_deref(), Some(expected), "{name}");
1590 }
1591 }
1592
1593 #[test]
1594 fn losing_pointer_focus_cancels_an_open_rewire_or_modal() {
1595 let (mut comp, mut flow, mut history) = wire_flow();
1596 let merge = id(&comp, "Merge1");
1597 let tri = input_center(&flow, &comp, merge, "Background");
1598 let far = [tri[0] + 40.0, tri[1] + 40.0];
1599 send(&mut flow, &mut comp, &mut history, button(true), tri);
1600 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(far), far);
1601 assert!(history.in_group() && source(&comp, merge, "Background").is_none());
1602
1603 send(&mut flow, &mut comp, &mut history, ui::Event::PointerCancelled, far);
1604 assert!(flow.wire_drag.is_none() && !history.in_group() && !history.can_undo());
1605 assert_eq!(source(&comp, merge, "Background").as_deref(), Some("BG1"));
1606
1607 flow.selected.insert(merge);
1608 flow.primary = Some(merge);
1609 key(&mut flow, &mut comp, &mut history, Key::Character("g".into()), ModifiersState::empty());
1610 assert!(flow.modal.is_some() && history.in_group());
1611 send(&mut flow, &mut comp, &mut history, ui::Event::PointerCancelled, far);
1612 assert!(flow.modal.is_none() && !history.in_group());
1613 }
1614
1615 #[test]
1616 fn sanitizing_mid_gesture_does_not_leave_the_history_group_open() {
1617 let (mut comp, mut flow, mut history) = wire_flow();
1618 let merge = id(&comp, "Merge1");
1619 flow.selected.insert(merge);
1620 flow.primary = Some(merge);
1621 key(&mut flow, &mut comp, &mut history, Key::Character("g".into()), ModifiersState::empty());
1622 assert!(history.in_group());
1623 flow.sanitize_ids(&comp);
1624 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved([5.0, 5.0]), [5.0, 5.0]);
1625 assert!(!history.in_group());
1626 }
1627
1628 #[test]
1629 fn port_tables_follow_fusion() {
1630 let comp = Comp::from_fusion_str(
1631 "Composition { Tools = ordered() { Else = Fuse.SwitchElse {}, Key = DeltaKeyer {}, Checker = Fuse.CheckerPieceGenerator {}, }, }",
1632 )
1633 .expect("parse comp");
1634 let mut flow = FlowView::new(&ui::Theme::new(&theme::KNIFE, true));
1635 flow.zoom = 1.0;
1636 let ports = |name: &str| {
1637 let mut found = Vec::new();
1638 flow.for_each_input(&comp, comp.node(id(&comp, name)), |s| found.push((s.port, s.color)));
1639 found
1640 };
1641 let names = |name: &str| ports(name).into_iter().map(|(p, _)| p).collect::<Vec<_>>();
1642 assert_eq!(names("Else"), ["Input1", "Input2", "EffectMask"]);
1643 assert_eq!(names("Key"), ["Input", "EffectMask", "Garbage.Matte", "Solid.Matte"]);
1644 assert_eq!(names("Checker"), ["EffectMask"]);
1645 assert!(ports("Key").iter().filter(|(p, _)| p.ends_with(".Matte")).all(|(_, c)| *c == ports::GRAY));
1646 }
1647
14631648}
crates/flow/src/ports.rs+12-7
......@@ -17,7 +17,7 @@ const STUB: f32 = 6.0;
1717const YELLOW: [f32; 4] = [0.91, 0.77, 0.23, 1.0];
1818const GREEN: [f32; 4] = [0.42, 0.75, 0.23, 1.0];
1919const BLUE: [f32; 4] = [0.23, 0.63, 0.91, 1.0];
20const GRAY: [f32; 4] = [0.80, 0.81, 0.86, 1.0];
20pub(crate) const GRAY: [f32; 4] = [0.80, 0.81, 0.86, 1.0];
2121const PURPLE: [f32; 4] = [0.72, 0.50, 0.92, 1.0];
2222
2323static SCENE_INPUTS: [&str; 32] = [
......@@ -116,9 +116,10 @@ fn table(n: &Node) -> (Table, Class) {
116116 match n.kind.as_str() {
117117 "Merge" | "Dissolve" | "ChannelBoolean" => (Table::Fixed(&["Background", "Foreground", "EffectMask"]), TwoInput),
118118 "Displace" => (Table::Fixed(&["Input", "Foreground", "EffectMask"]), TwoInput),
119 "Background" | "FastNoise" | "TextPlus" | "Loader" | "EllipseMask" | "RectangleMask" | "PolylineMask" => {
120 (Table::Fixed(&["EffectMask"]), Generator)
121 }
119 "Background" | "FastNoise" | "TextPlus" | "Loader" | "EllipseMask" | "RectangleMask" | "PolylineMask"
120 | "Fuse.CheckerPieceGenerator" => (Table::Fixed(&["EffectMask"]), Generator),
121 "Fuse.SwitchElse" => (Table::Fixed(&["Input1", "Input2", "EffectMask"]), Single),
122 "DeltaKeyer" => (Table::Fixed(&["Input", "EffectMask", "Garbage.Matte", "Solid.Matte"]), Single),
122123 "Renderer3D" | "Transform3D" | "ReplaceMaterial3D" | "Override3D" | "ReplaceNormals3D" | "Displace3D" | "Duplicate3D" => {
123124 (Table::Fixed(&["SceneInput"]), Single)
124125 }
......@@ -187,7 +188,7 @@ fn port_color(n: &Node, port: &str) -> [f32; 4] {
187188 "Input1" if n.kind == "Switch" && zero_indexed(n) => GREEN,
188189 "Input1" => YELLOW,
189190 "Input2" | "SceneInput2" => GREEN,
190 "GarbageMatte" | "SolidMatte" => GRAY,
191 "GarbageMatte" | "SolidMatte" | "Garbage.Matte" | "Solid.Matte" => GRAY,
191192 _ => match PortRole::from_input_name(port) {
192193 PortRole::Background => YELLOW,
193194 PortRole::Foreground => GREEN,
......@@ -362,8 +363,12 @@ impl FlowView {
362363 /// Extra pixels around a node's rect that its handles can reach.
363364 fn handle_reach(&self, n: &Node) -> f32 {
364365 let m = Metrics::at(self.zoom);
365 let grow = if matches!(table(n).0, Table::Grow(_)) { n.inputs.len() as f32 * 4.5 } else { 0.0 };
366 HIT_IN + m.tri_len + 4.0 + grow
366 let r = self.node_rect_local(n.pos);
367 let mut ports = 0_usize;
368 each_port(n, table(n).0, |_| ports += 1);
369 // One edge carrying every port spreads them past the node's shorter side.
370 let spread = (ports.saturating_sub(1) as f32 * (2.0 * m.tri_half + 1.0) - (r[2] - r[0]).min(r[3] - r[1])) * 0.5;
371 HIT_IN + m.tri_len + 4.0 + spread.max(0.0)
367372 }
368373
369374 /// Output square (`None` port) or input triangle under `local`. A node body always wins.
crates/model/src/comp/save.rs+37-3
......@@ -214,9 +214,10 @@ impl Comp {
214214 ("Loop", edited("Loop").map(|v| LuaValue::Number(if v > 0.5 { 0.0 } else { 1.0 }))),
215215 ("Reverse", edited("Reverse").map(|v| LuaValue::Bool(v > 0.5))),
216216 ];
217 let clip = tool_tbl
218 .get_table_mut("Clips")
219 .and_then(|c| c.entries.iter_mut().find_map(|(_, v)| v.as_table_mut()));
217 // The first clip proper, as `node.clips.first()` (what the engine plays) is.
218 let clip = tool_tbl.get_table_mut("Clips").and_then(|c| {
219 c.entries.iter_mut().find_map(|(_, v)| v.as_table_mut().filter(|t| t.get_str("Filename").is_some()))
220 });
220221 if let Some(clip) = clip {
221222 for (key, value) in updates {
222223 if let Some(value) = value {
......@@ -779,6 +780,39 @@ mod tests {
779780 assert_eq!(clip.global_end, 25);
780781 }
781782
783 #[test]
784 fn loader_timing_edits_land_in_the_first_clip_of_a_multi_clip_loader() {
785 let src = r#"Composition {
786 Tools = ordered() {
787 L = Loader {
788 Clips = {
789 Note = { Comment = "not a clip", },
790 Clip {
791 Filename = "a.0000.exr",
792 GlobalStart = 0,
793 GlobalEnd = 10,
794 },
795 Clip {
796 Filename = "b.0000.exr",
797 GlobalStart = 11,
798 GlobalEnd = 30,
799 },
800 },
801 },
802 },
803 }"#;
804 let mut comp = Comp::from_fusion_str(src).unwrap();
805 let l = comp.find_node("L").unwrap();
806 comp.set_input_value(l, "GlobalOut", ParamValue::Number(25.0));
807 comp.set_input_value(l, "Reverse", ParamValue::Number(1.0));
808 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
809 let clips = &saved.node(saved.find_node("L").unwrap()).clips;
810 assert_eq!(clips.len(), 2);
811 assert_eq!((clips[0].global_end, clips[0].reverse), (25, true));
812 assert_eq!((clips[1].global_start, clips[1].global_end, clips[1].reverse), (11, 30, false));
813 assert!(comp.to_fusion_string().contains("Comment = \"not a clip\""));
814 }
815
782816 #[test]
783817 fn cleared_cross_macro_wire_keeps_its_source_op_on_save() {
784818 let src = r#"Composition {
crates/model/src/expr.rs+202-17
......@@ -11,6 +11,32 @@ pub enum ExprValue {
1111 Text(String),
1212}
1313
14/// Lua's `tostring` for a float: C `%.14g`, so `0.1 + 0.2` reads `0.3` and `3.0` reads `3`.
15fn format_number(n: f64) -> String {
16 if !n.is_finite() {
17 return if n.is_nan() { "nan" } else if n > 0.0 { "inf" } else { "-inf" }.to_owned();
18 }
19 let sci = format!("{:.13e}", n.abs());
20 let (mantissa, exp) = sci.split_once('e').expect("`{:e}` always has an exponent");
21 let exp: i32 = exp.parse().expect("exponent is an integer");
22 let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
23 let digits = digits.trim_end_matches('0');
24 let digits = if digits.is_empty() { "0" } else { digits };
25 let sign = if n.is_sign_negative() { "-" } else { "" };
26 let (head, tail) = digits.split_at(1);
27 if !(-4..14).contains(&exp) {
28 let point = if tail.is_empty() { "" } else { "." };
29 return format!("{sign}{head}{point}{tail}e{}{:02}", if exp < 0 { '-' } else { '+' }, exp.abs());
30 }
31 if exp < 0 {
32 return format!("{sign}0.{}{digits}", "0".repeat(exp.unsigned_abs() as usize - 1));
33 }
34 let int_len = exp as usize + 1;
35 let padded = format!("{digits:0<int_len$}");
36 let (int, frac) = padded.split_at(int_len);
37 format!("{sign}{int}{}{frac}", if frac.is_empty() { "" } else { "." })
38}
39
1440#[cfg(not(target_arch = "wasm32"))]
1541mod lua {
1642 use super::ExprValue;
......@@ -73,6 +99,8 @@ mod lua {
7399 tanh = function(x) local e = math.exp(2*x); return (e - 1) / (e + 1) end
74100 iif = function(cond, a, b) if cond and cond ~= 0 then return a else return b end end
75101 Point = function(x, y) return { X = x or 0, Y = y or 0, [1] = x or 0, [2] = y or 0 } end
102 local lua_tostring = tostring
103 tostring = function(v) if type(v) == "number" then return string.format("%.14g", v) end return lua_tostring(v) end
76104 Text = function(s) return tostring(s or "") end
77105 clamp = function(x, lo, hi) if x < lo then return lo elseif x > hi then return hi else return x end end
78106 mix = function(a, b, t) return a + (b - a) * t end
......@@ -197,7 +225,7 @@ mod lua {
197225 let val = self.run(expr, time, self_params, self_points, env_nodes)?;
198226 match val {
199227 Value::String(s) => Some(s.to_str().ok()?.to_owned()),
200 Value::Number(n) => Some(format!("{n}")),
228 Value::Number(n) => Some(super::format_number(n)),
201229 Value::Integer(i) => Some(format!("{i}")),
202230 Value::Table(t) => t.get::<String>("Value").ok(),
203231 _ => None,
......@@ -354,6 +382,7 @@ mod pure {
354382 use std::collections::HashMap;
355383
356384 const MAX_DEPTH: usize = 64;
385 const MAX_TOKENS: usize = 2048;
357386 const MATH_FNS: &[&str] = &[
358387 "abs", "acos", "asin", "atan", "ceil", "cos", "deg", "exp", "floor", "fmod", "log", "max", "min", "rad",
359388 "sin", "sqrt", "tan",
......@@ -365,7 +394,8 @@ mod pure {
365394
366395 #[derive(Clone, Debug, PartialEq)]
367396 enum Tok {
368 Num(f64),
397 /// `true` for a Lua integer literal, which divides by zero as an error rather than `inf`.
398 Num(f64, bool),
369399 Str(String),
370400 Name(String),
371401 Op(&'static str),
......@@ -390,19 +420,22 @@ mod pure {
390420 i += 1;
391421 }
392422 let digits: String = chars[start + 2..i].iter().collect();
393 toks.push(Tok::Num(u64::from_str_radix(&digits, 16).ok()? as f64));
423 toks.push(Tok::Num(u64::from_str_radix(&digits, 16).ok()? as f64, true));
394424 continue;
395425 }
396426 while chars.get(i).is_some_and(char::is_ascii_digit) {
397427 i += 1;
398428 }
429 let mut integer = true;
399430 if chars.get(i) == Some(&'.') && chars.get(i + 1) != Some(&'.') {
431 integer = false;
400432 i += 1;
401433 while chars.get(i).is_some_and(char::is_ascii_digit) {
402434 i += 1;
403435 }
404436 }
405437 if matches!(chars.get(i), Some('e' | 'E')) {
438 integer = false;
406439 i += 1;
407440 if matches!(chars.get(i), Some('+' | '-')) {
408441 i += 1;
......@@ -411,7 +444,8 @@ mod pure {
411444 i += 1;
412445 }
413446 }
414 toks.push(Tok::Num(chars[start..i].iter().collect::<String>().parse().ok()?));
447 let value: f64 = chars[start..i].iter().collect::<String>().parse().ok()?;
448 toks.push(Tok::Num(value, integer && value < 2f64.powi(63)));
415449 } else if c.is_alphabetic() || c == '_' {
416450 let start = i;
417451 while chars.get(i).is_some_and(|c| c.is_alphanumeric() || *c == '_') {
......@@ -453,6 +487,8 @@ mod pure {
453487 Nil,
454488 Bool(bool),
455489 Num(f64),
490 /// An integer literal.
491 Int(f64),
456492 Str(String),
457493 Name(String),
458494 Index(Box<Ast>, Box<Ast>),
......@@ -500,23 +536,34 @@ mod pure {
500536 Some((op, left, right))
501537 }
502538
503 fn expr(&mut self, min_bp: u8) -> Option<Ast> {
539 /// One more level of tree height, which nesting and every left-associative link add alike,
540 /// so recursive eval and drop stay bounded.
541 fn descend(&mut self) -> Option<()> {
504542 self.depth += 1;
505 let ast = if self.depth > MAX_DEPTH { None } else { self.binary(min_bp) };
506 self.depth -= 1;
507 ast
543 (self.depth <= MAX_DEPTH).then_some(())
544 }
545
546 fn expr(&mut self, min_bp: u8) -> Option<Ast> {
547 let outer = self.depth;
548 self.descend()?;
549 let ast = self.binary(min_bp)?;
550 self.depth = outer;
551 Some(ast)
508552 }
509553
510554 fn binary(&mut self, min_bp: u8) -> Option<Ast> {
555 let outer = self.depth;
511556 let mut lhs = self.unary()?;
512557 while let Some((op, left, right)) = self.binary_op() {
513558 if left < min_bp {
514559 break;
515560 }
516561 self.pos += 1;
562 self.descend()?;
517563 let rhs = self.expr(right)?;
518564 lhs = Ast::Bin(op, Box::new(lhs), Box::new(rhs));
519565 }
566 self.depth = outer;
520567 Some(lhs)
521568 }
522569
......@@ -533,7 +580,8 @@ mod pure {
533580
534581 fn postfix(&mut self) -> Option<Ast> {
535582 let mut node = match self.toks.get(self.pos)?.clone() {
536 Tok::Num(n) => Ast::Num(n),
583 Tok::Num(n, true) => Ast::Int(n),
584 Tok::Num(n, false) => Ast::Num(n),
537585 Tok::Str(s) => Ast::Str(s),
538586 Tok::Name(n) => match n.as_str() {
539587 "nil" => Ast::Nil,
......@@ -553,18 +601,22 @@ mod pure {
553601 Tok::Op(_) => return None,
554602 };
555603 self.pos += 1;
604 let outer = self.depth;
556605 loop {
557606 if self.eat_op(".") {
607 self.descend()?;
558608 let Some(Tok::Name(key)) = self.peek().cloned() else { return None };
559609 self.pos += 1;
560610 node = Ast::Index(Box::new(node), Box::new(Ast::Str(key)));
561611 } else if self.eat_op("[") {
612 self.descend()?;
562613 let key = self.expr(0)?;
563614 if !self.eat_op("]") {
564615 return None;
565616 }
566617 node = Ast::Index(Box::new(node), Box::new(key));
567618 } else if self.eat_op("(") {
619 self.descend()?;
568620 let mut args = Vec::new();
569621 if !self.eat_op(")") {
570622 loop {
......@@ -579,6 +631,7 @@ mod pure {
579631 }
580632 node = Ast::Call(Box::new(node), args);
581633 } else {
634 self.depth = outer;
582635 return Some(node);
583636 }
584637 }
......@@ -613,13 +666,23 @@ mod pure {
613666 }
614667 }
615668
669 /// What `..` accepts: numbers and strings.
616670 fn text(&self) -> Option<String> {
617671 match self {
618 Val::Num(n) => Some(format!("{n}")),
672 Val::Num(n) => Some(super::format_number(*n)),
619673 Val::Str(s) | Val::Text(s) => Some(s.clone()),
620674 _ => None,
621675 }
622676 }
677
678 /// Lua's `tostring`, which also names `nil` and booleans.
679 fn tostring(&self) -> Option<String> {
680 match self {
681 Val::Nil => Some("nil".to_owned()),
682 Val::Bool(b) => Some(b.to_string()),
683 other => other.text(),
684 }
685 }
623686 }
624687
625688 struct Scope<'a> {
......@@ -655,7 +718,7 @@ mod pure {
655718 Some(match ast {
656719 Ast::Nil => Val::Nil,
657720 Ast::Bool(b) => Val::Bool(*b),
658 Ast::Num(n) => Val::Num(*n),
721 Ast::Num(n) | Ast::Int(n) => Val::Num(*n),
659722 Ast::Str(s) => Val::Str(s.clone()),
660723 Ast::Name(n) => self.name(n),
661724 Ast::Neg(a) => Val::Num(-self.eval(a)?.num()?),
......@@ -674,11 +737,28 @@ mod pure {
674737 let a = self.eval(a)?;
675738 if a.truthy() { a } else { self.eval(b)? }
676739 }
677 Ast::Bin(op, a, b) => binary(op, self.eval(a)?, self.eval(b)?)?,
740 Ast::Bin(op, a, b) => {
741 let (a_val, b_val) = (self.eval(a)?, self.eval(b)?);
742 // Lua 5.4 errors on integer `//` and `%` by zero; floats give `inf`/`nan`.
743 if matches!(*op, "//" | "%") && b_val.num() == Some(0.0) && is_integer(a) && is_integer(b) {
744 return None;
745 }
746 binary(op, a_val, b_val)?
747 }
678748 })
679749 }
680750 }
681751
752 /// Whether Lua 5.4 types `ast` as an integer: integer literals and `+ - * // %` of them.
753 fn is_integer(ast: &Ast) -> bool {
754 match ast {
755 Ast::Int(_) => true,
756 Ast::Neg(a) => is_integer(a),
757 Ast::Bin("+" | "-" | "*" | "//" | "%", a, b) => is_integer(a) && is_integer(b),
758 _ => false,
759 }
760 }
761
682762 fn index<'a>(base: Val<'a>, key: Val<'a>) -> Option<Val<'a>> {
683763 Some(match (base, key) {
684764 (Val::Node(fields), key) => match key {
......@@ -708,7 +788,7 @@ mod pure {
708788 fn binary<'a>(op: &str, a: Val<'a>, b: Val<'a>) -> Option<Val<'a>> {
709789 use std::cmp::Ordering;
710790 let ordering = |a: &Val, b: &Val| match (a, b) {
711 (Val::Num(a), Val::Num(b)) => a.partial_cmp(b).map(Some),
791 (Val::Num(a), Val::Num(b)) => Some(a.partial_cmp(b)),
712792 (Val::Str(a), Val::Str(b)) => Some(Some(a.cmp(b))),
713793 _ => None,
714794 };
......@@ -790,7 +870,8 @@ mod pure {
790870 }
791871 "mix" => Val::Num(arg(0)? + (arg(1)? - arg(0)?) * arg(2)?),
792872 "Point" => Val::Point([arg(0).unwrap_or(0.0), arg(1).unwrap_or(0.0)]),
793 "Text" | "tostring" => Val::Str(args.first().map_or(Some(String::new()), Val::text)?),
873 "tostring" => Val::Str(args.first()?.tostring()?),
874 "Text" => Val::Str(args.first().filter(|a| a.truthy()).map_or(Some(String::new()), Val::tostring)?),
794875 "tonumber" => args.first()?.num().map_or(Val::Nil, Val::Num),
795876 _ => return None,
796877 })
......@@ -814,10 +895,15 @@ mod pure {
814895 read: impl FnOnce(Val) -> Option<R>,
815896 ) -> Option<R> {
816897 let body = match expr.trim_start().strip_prefix(':') {
817 Some(stmt) => stmt.trim_start().strip_prefix("return ")?,
898 Some(stmt) => {
899 let value = stmt.trim_start().strip_prefix("return ")?.trim_end();
900 value.strip_suffix(';').unwrap_or(value)
901 }
818902 None => expr,
819903 };
820 let mut parser = Parser { toks: lex(body)?, pos: 0, depth: 0 };
904 // Every AST node consumes a token, so this also caps the tree's size.
905 let toks = lex(body).filter(|t| t.len() <= MAX_TOKENS)?;
906 let mut parser = Parser { toks, pos: 0, depth: 0 };
821907 let ast = parser.expr(0)?;
822908 if parser.pos != parser.toks.len() {
823909 return None;
......@@ -943,8 +1029,86 @@ mod pure {
9431029 assert_eq!(num(src, 0.0), None, "{src:?}");
9441030 }
9451031 assert_eq!(num(":return time * 2", 2.0), Some(4.0));
1032 assert_eq!(num(":return time * 2;", 2.0), Some(4.0));
9461033 assert_eq!(num(&"(".repeat(200), 0.0), None);
9471034 }
1035
1036 #[test]
1037 fn long_chains_are_bounded_instead_of_overflowing_the_stack() {
1038 let sum = |terms: usize| vec!["1"; terms].join("+");
1039 assert_eq!(num(&sum(40), 0.0), Some(40.0));
1040 for terms in [100, 10_000, 200_000] {
1041 assert_eq!(num(&sum(terms), 0.0), None, "{terms} terms");
1042 }
1043 let path = |links: usize| format!("Ctl{}", ".Size".repeat(links));
1044 assert_eq!(num(&path(1), 0.0), Some(0.25));
1045 assert_eq!(num(&path(100), 0.0), None);
1046 assert_eq!(num(&format!("max({})", vec!["1"; 5000].join(",")), 0.0), None);
1047 assert_eq!(num(&format!("{}1{}", "-".repeat(500), ""), 0.0), None);
1048 }
1049
1050 #[test]
1051 fn nan_compares_false_instead_of_failing() {
1052 for (src, want) in [("0/0 < 1", 0.0), ("0/0 >= 1", 0.0), ("0/0 <= 0/0", 0.0), ("0/0 == 0/0", 0.0), ("0/0 ~= 0/0", 1.0)] {
1053 assert_eq!(num(src, 0.0), Some(want), "{src}");
1054 }
1055 }
1056
1057 #[test]
1058 fn integer_division_by_zero_errors_but_float_gives_inf() {
1059 assert_eq!(num("1 // 0", 0.0), None);
1060 assert_eq!(num("1 % 0", 0.0), None);
1061 assert_eq!(num("(2 + 3) % (1 - 1)", 0.0), None);
1062 assert_eq!(num("1.0 // 0", 0.0), Some(f64::INFINITY));
1063 assert_eq!(num("1 // 0.0", 0.0), Some(f64::INFINITY));
1064 assert_eq!(num("time // 0", 2.0), Some(f64::INFINITY));
1065 assert!(num("time % 0", 2.0).is_some_and(f64::is_nan));
1066 }
1067
1068 #[test]
1069 fn tostring_names_nil_and_booleans() {
1070 let e = ExprEngine::new();
1071 let (p, q, n) = (HashMap::new(), HashMap::new(), nodes());
1072 let s = |src: &str| e.eval_string(src, 0.0, &p, &q, &n);
1073 assert_eq!(s("tostring(true)").as_deref(), Some("true"));
1074 assert_eq!(s("tostring(false)").as_deref(), Some("false"));
1075 assert_eq!(s("tostring(nil)").as_deref(), Some("nil"));
1076 assert_eq!(s("Text(nil)").as_deref(), Some(""));
1077 assert_eq!(s("Text(false)").as_deref(), Some(""));
1078 assert_eq!(s("'a' .. nil"), None);
1079 assert_eq!(s("0.1 + 0.2").as_deref(), Some("0.3"));
1080 }
1081 }
1082}
1083
1084#[cfg(test)]
1085mod tests {
1086 use super::format_number;
1087
1088 #[test]
1089 fn numbers_format_like_c_percent_14g() {
1090 for (n, want) in [
1091 (3.0, "3"),
1092 (-0.0, "-0"),
1093 (0.0, "0"),
1094 (0.1 + 0.2, "0.3"),
1095 (1.0 / 3.0, "0.33333333333333"),
1096 (2.5, "2.5"),
1097 (100.0, "100"),
1098 (123456789012345.0, "1.2345678901234e+14"),
1099 (99999999999999.0, "99999999999999"),
1100 (1e15, "1e+15"),
1101 (2f64.powi(53), "9.007199254741e+15"),
1102 (1e100, "1e+100"),
1103 (0.0001, "0.0001"),
1104 (0.00001, "1e-05"),
1105 (-1234.5, "-1234.5"),
1106 (f64::INFINITY, "inf"),
1107 (f64::NEG_INFINITY, "-inf"),
1108 (f64::NAN, "nan"),
1109 ] {
1110 assert_eq!(format_number(n), want, "{n:e}");
1111 }
9481112 }
9491113}
9501114
......@@ -980,6 +1144,13 @@ mod parity {
9801144 "max(1, time, 3) + min(time, 9) + abs(-time) + ceil(time) + sqrt(time)",
9811145 "cosh(time) + sinh(time) + tanh(time) + deg(1) + rad(90)",
9821146 "time ~= 2.5",
1147 "0/0 < 1",
1148 "0/0 >= 1",
1149 "1 // 0",
1150 "1 % 0",
1151 "time // 0",
1152 "1.0 % 0 < 1",
1153 ":return time * 2;",
9831154 "'10' + 1",
9841155 "Nope.Size",
9851156 "1 +",
......@@ -988,10 +1159,24 @@ mod parity {
9881159 let l = lua.eval_number(args.0, args.1, args.2, args.3, args.4);
9891160 let p = pure.eval_number(args.0, args.1, args.2, args.3, args.4);
9901161 match (l, p) {
991 (Some(l), Some(p)) => assert!((l - p).abs() < 1e-9 || (l.is_nan() && p.is_nan()), "{src} @ {time}: {l} vs {p}"),
1162 (Some(l), Some(p)) => assert!(l == p || (l - p).abs() < 1e-9 || (l.is_nan() && p.is_nan()), "{src} @ {time}: {l} vs {p}"),
9921163 _ => assert_eq!(l, p, "{src} @ {time}"),
9931164 }
9941165 }
9951166 }
9961167 }
1168
1169 #[test]
1170 fn pure_formats_numbers_like_lua() {
1171 let nodes = HashMap::new();
1172 let (lua, pure) = (ExprEngine::new(), pure::ExprEngine::new());
1173 for src in [
1174 "0.1 + 0.2", "3.0", "time", "1e15", "2^53", "1e100", "0.00001", "1/3", "-0.0", "7 // 2", "100 * 1.0",
1175 "tostring(true)", "tostring(nil)", "Text(nil)", "Text(time)", "123456789.123456789",
1176 ] {
1177 let l = lua.eval_string(src, 2.0, &HashMap::new(), &HashMap::new(), &nodes);
1178 let p = pure.eval_string(src, 2.0, &HashMap::new(), &HashMap::new(), &nodes);
1179 assert_eq!(l, p, "{src}");
1180 }
1181 }
9971182}
crates/web/index.html+16-7
......@@ -189,18 +189,25 @@ function tick(now) {
189189 $('scrub').value = frame;
190190 }
191191 if (dirty || frame !== lastDrawn) {
192 let ms;
192193 try {
193 evalMs = app.render(frame);
194 ms = app.render(frame);
194195 } catch (e) {
195196 broken = true;
196197 fail(`Render failed: ${e.message ?? e}. Reload the page; details are in the console.`);
197198 return;
198199 }
199 if (lastTick) fps += ((1000 / (now - lastTick)) - fps) * 0.15;
200 lastTick = now;
201 lastDrawn = frame; dirty = false;
202 const bad = app.unsupported();
203 $('notes').dataset.unsupported = bad.join(', ');
200 const gpuError = app.gpu_error();
201 if (gpuError) fail(`GPU error: ${gpuError}`);
202 // `undefined`: the surface was not ready; stay dirty and try again next frame.
203 if (ms !== undefined) {
204 evalMs = ms;
205 if (lastTick) fps += ((1000 / (now - lastTick)) - fps) * 0.15;
206 lastTick = now;
207 lastDrawn = frame; dirty = false;
208 const bad = app.unsupported();
209 $('notes').dataset.unsupported = bad.join(', ');
210 }
204211 } else if (!playing) {
205212 lastTick = 0;
206213 }
......@@ -265,9 +272,10 @@ async function ingest(files) {
265272 if (!app) return;
266273 const comps = files.filter(({ path }) => /\.comp$/i.test(path));
267274 if (comps.length) { app.clear_files(); sources.clear(); }
275 let dropped = 0;
268276 for (const { path, file } of files) {
269277 if (!MEDIA_EXT.test(path) || file.size > MAX_FILE_BYTES) continue;
270 app.add_file(path, new Uint8Array(await file.arrayBuffer()));
278 if (!app.add_file(path, new Uint8Array(await file.arrayBuffer()))) dropped++;
271279 }
272280 if (comps.length) {
273281 comps.sort((a, b) => a.path.localeCompare(b.path));
......@@ -280,6 +288,7 @@ async function ingest(files) {
280288 refreshGraph();
281289 dirty = true;
282290 }
291 if (dropped) fail(`${dropped} file(s) skipped: dropped media is past the 512 MB memory limit.`);
283292}
284293
285294boot();
crates/web/src/lib.rs+76-36
......@@ -7,6 +7,7 @@ use engine::{DisplaySettings, Engine};
77use model::{Comp, NodeId};
88use serde_json::json;
99use std::collections::HashSet;
10use std::sync::{Arc, Mutex};
1011use wasm_bindgen::prelude::*;
1112
1213const DEMO_COMP: &str = include_str!("../demo.comp");
......@@ -20,7 +21,9 @@ struct Viewer {
2021pub struct Fission {
2122 engine: Engine,
2223 surface: wgpu::Surface<'static>,
23 surface_format: wgpu::TextureFormat,
24 config: wgpu::SurfaceConfiguration,
25 /// The latest GPU error the device raised outside any error scope, until [`Self::gpu_error`] reads it.
26 gpu_error: Arc<Mutex<Option<String>>>,
2427 present: wgpu::RenderPipeline,
2528 sampler: wgpu::Sampler,
2629 viewer: Option<Viewer>,
......@@ -60,12 +63,31 @@ impl Fission {
6063 .await
6164 .map_err(js_err)?;
6265
63 let surface_format = surface
64 .get_capabilities(&adapter)
65 .formats
66 .into_iter()
67 .find(|f| !f.is_srgb())
68 .unwrap_or(wgpu::TextureFormat::Bgra8Unorm);
66 let gpu_error = Arc::new(Mutex::new(None));
67 let slot = Arc::clone(&gpu_error);
68 device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| {
69 console_error(&format!("GPU error: {e}"));
70 *slot.lock().unwrap() = Some(e.to_string());
71 }));
72 let slot = Arc::clone(&gpu_error);
73 device.set_device_lost_callback(move |reason, message| {
74 console_error(&format!("GPU device lost ({reason:?}): {message}"));
75 *slot.lock().unwrap() = Some(format!("The GPU device was lost ({reason:?}): {message}"));
76 });
77
78 let caps = surface.get_capabilities(&adapter);
79 let surface_format = caps.formats.iter().copied().find(|f| !f.is_srgb()).unwrap_or(wgpu::TextureFormat::Bgra8Unorm);
80 let config = wgpu::SurfaceConfiguration {
81 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
82 format: surface_format,
83 color_space: wgpu::SurfaceColorSpace::Auto,
84 width: 1,
85 height: 1,
86 present_mode: wgpu::PresentMode::AutoVsync,
87 desired_maximum_frame_latency: 2,
88 alpha_mode: caps.alpha_modes.first().copied().unwrap_or(wgpu::CompositeAlphaMode::Auto),
89 view_formats: vec![],
90 };
6991 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
7092 label: Some("present"),
7193 source: wgpu::ShaderSource::Wgsl(include_str!("present.wgsl").into()),
......@@ -83,7 +105,7 @@ impl Fission {
83105 module: &shader,
84106 entry_point: Some("fragment"),
85107 compilation_options: Default::default(),
86 targets: &[Some(surface_format.into())],
108 targets: &[Some(config.format.into())],
87109 }),
88110 primitive: Default::default(),
89111 depth_stencil: None,
......@@ -100,7 +122,8 @@ impl Fission {
100122 Ok(Fission {
101123 engine: Engine::new(device, queue),
102124 surface,
103 surface_format,
125 config,
126 gpu_error,
104127 present,
105128 sampler,
106129 viewer: None,
......@@ -115,9 +138,11 @@ impl Fission {
115138 }
116139
117140 /// Registers a project file (a dropped folder's relative path) that `Loader` clips resolve against.
118 pub fn add_file(&mut self, path: &str, bytes: &[u8]) {
119 MediaCache::insert_virtual_bytes(path, bytes);
141 /// `false` when the files held would pass the memory cap.
142 pub fn add_file(&mut self, path: &str, bytes: &[u8]) -> bool {
143 let added = MediaCache::insert_virtual_bytes(path, bytes);
120144 self.engine.bust_all_caches();
145 added
121146 }
122147
123148 pub fn clear_files(&mut self) {
......@@ -174,21 +199,32 @@ impl Fission {
174199 Ok(())
175200 }
176201
177 /// Evaluates the selected node at `frame` into the canvas and returns the CPU-side milliseconds.
178 pub fn render(&mut self, frame: f64) -> Result<f64, JsError> {
202 /// Evaluates the selected node at `frame` into the canvas and returns the CPU-side milliseconds,
203 /// or `undefined` when the surface could not take the frame and the caller should retry.
204 pub fn render(&mut self, frame: f64) -> Result<Option<f64>, JsError> {
179205 let (comp, target) = self.comp.as_ref().zip(self.target).ok_or_else(|| JsError::new("no comp loaded"))?;
180206 // Cached by the engine, so `render_into_viewer` below reuses it; the size can change with media or time.
181207 let (tex, _) = self.engine.evaluate(comp, target, frame);
182 if self.viewer.as_ref().is_none_or(|v| [v.texture.width(), v.texture.height()] != tex.canvas_size) {
183 self.viewer = Some(make_viewer(self.engine.device(), &self.surface, self.surface_format, &self.present, &self.sampler, tex.canvas_size));
208 let size = fit_texture(tex.canvas_size, self.engine.device().limits().max_texture_dimension_2d);
209 if self.viewer.as_ref().is_none_or(|v| [v.texture.width(), v.texture.height()] != size) {
210 [self.config.width, self.config.height] = size;
211 self.surface.configure(self.engine.device(), &self.config);
212 self.viewer = Some(make_viewer(self.engine.device(), &self.present, &self.sampler, size));
184213 }
185214 let viewer = self.viewer.as_ref().expect("viewer sized above");
186215 let stats = self.engine.render_into_viewer(comp, target, frame, &viewer.texture, DisplaySettings::default());
187216 self.unsupported = stats.unsupported_nodes;
188217
189 let frame_tex = match self.surface.get_current_texture() {
190 wgpu::CurrentSurfaceTexture::Success(t) | wgpu::CurrentSurfaceTexture::Suboptimal(t) => t,
191 _ => return Ok(stats.eval_ms),
218 let (frame_tex, suboptimal) = match self.surface.get_current_texture() {
219 wgpu::CurrentSurfaceTexture::Success(t) => (t, false),
220 wgpu::CurrentSurfaceTexture::Suboptimal(t) => (t, true),
221 wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
222 self.surface.configure(self.engine.device(), &self.config);
223 return Ok(None);
224 }
225 wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded | wgpu::CurrentSurfaceTexture::Validation => {
226 return Ok(None);
227 }
192228 };
193229 let device = self.engine.device();
194230 let mut encoder = device.create_command_encoder(&Default::default());
......@@ -209,7 +245,15 @@ impl Fission {
209245 }
210246 self.engine.queue().submit(Some(encoder.finish()));
211247 self.engine.queue().present(frame_tex);
212 Ok(stats.eval_ms)
248 if suboptimal {
249 self.surface.configure(self.engine.device(), &self.config);
250 }
251 Ok(Some(stats.eval_ms))
252 }
253
254 /// Takes the latest GPU error or device loss, which would otherwise only show as a black canvas.
255 pub fn gpu_error(&self) -> Option<String> {
256 self.gpu_error.lock().unwrap().take()
213257 }
214258
215259 /// Kinds the last rendered frame could not evaluate.
......@@ -218,29 +262,25 @@ impl Fission {
218262 }
219263}
220264
221/// Sizes the canvas and the intermediate viewer texture to the node's logical output.
265#[wasm_bindgen]
266extern "C" {
267 #[wasm_bindgen(js_namespace = console, js_name = error)]
268 fn console_error(message: &str);
269}
270
271/// `size` shrunk, keeping its aspect, until both sides fit `max`; never below one pixel.
272fn fit_texture([width, height]: [u32; 2], max: u32) -> [u32; 2] {
273 let scale = (f64::from(max) / f64::from(width.max(height).max(1))).min(1.0);
274 [width, height].map(|side| ((f64::from(side) * scale).round() as u32).clamp(1, max.max(1)))
275}
276
277/// The intermediate viewer texture, sized to the (already fitted) output.
222278fn make_viewer(
223279 device: &wgpu::Device,
224 surface: &wgpu::Surface<'static>,
225 format: wgpu::TextureFormat,
226280 present: &wgpu::RenderPipeline,
227281 sampler: &wgpu::Sampler,
228282 [width, height]: [u32; 2],
229283) -> Viewer {
230 surface.configure(
231 device,
232 &wgpu::SurfaceConfiguration {
233 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
234 format,
235 color_space: wgpu::SurfaceColorSpace::Auto,
236 width,
237 height,
238 present_mode: wgpu::PresentMode::AutoVsync,
239 desired_maximum_frame_latency: 2,
240 alpha_mode: wgpu::CompositeAlphaMode::Opaque,
241 view_formats: vec![],
242 },
243 );
244284 let texture = device.create_texture(&wgpu::TextureDescriptor {
245285 label: Some("viewer"),
246286 size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },