diff --git a/crates/app/src/inspector/controls.rs b/crates/app/src/inspector/controls.rs index abc01a06d319a899c906bd1d733fc8c83785eb4b..0f721e741acaf6677b4100e2bf0359e14df1a75c 100644 --- a/crates/app/src/inspector/controls.rs +++ b/crates/app/src/inspector/controls.rs @@ -14,32 +14,31 @@ const BOX_H: f32 = 20.0; pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) { let channels = def.channels.as_slice(); - let animatable = match def.kind { + let keys = match def.kind { Kind::Slider | Kind::Screw | Kind::Range | Kind::Color | Kind::Checkbox | Kind::Toggles => true, Kind::Segmented | Kind::Combo => !def.fuid, Kind::Point | Kind::Text => false, }; - let marks = if animatable { channels } else { &[] }; match def.kind { Kind::Slider => { let ch = &channels[0]; let sub = sub_labels(&ch.id); let height = px(if sub.is_some() { ROW_H + 14.0 } else { ROW_H }); - row(ui, cx, &def.label, &ch.id, marks, height, |ui, cx| { + row(ui, cx, &def.label, &ch.id, channels, keys, height, |ui, cx| { let value = cx.number(ch); 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); spec.step = ch.integer.then_some(1.0); spec.sub_labels = sub; spec.label = &def.label; if let Some(next) = ui::slider(ui, ("sld", cx.node.0, ch.id.as_str()), spec) { - cx.write_numbers(&def.label, &[(ch, f64::from(next))], true); + cx.write_numbers(&def.label, &[(ch, f64::from(next))], Some(&ch.id)); } number_box(ui, cx, ch, None, value, px(52.0)); }); } Kind::Screw => { let ch = &channels[0]; - row(ui, cx, &def.label, &ch.id, marks, px(ROW_H), |ui, cx| { + row(ui, cx, &def.label, &ch.id, channels, keys, px(ROW_H), |ui, cx| { let value = cx.number(ch); let mut spec = ui::ScrewControl::new(value as f32, cx.default_of(ch) as f32); 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) { spec.width = fill(); spec.label = &def.label; if let Some(next) = ui::screw_control(ui, ("scw", cx.node.0, ch.id.as_str()), spec) { - cx.write_numbers(&def.label, &[(ch, f64::from(next))], true); + cx.write_numbers(&def.label, &[(ch, f64::from(next))], Some(&ch.id)); } number_box(ui, cx, ch, None, value, px(52.0)); }); } Kind::Range => { let [start, end] = [&channels[0], &channels[1]]; - row(ui, cx, &def.label, &start.id, marks, px(ROW_H), |ui, cx| { + row(ui, cx, &def.label, &start.id, channels, keys, px(ROW_H), |ui, cx| { let [s, e] = [cx.number(start), cx.number(end)]; let mut spec = ui::RangeSlider::new( s as f32, @@ -72,7 +71,7 @@ pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) { .filter(|&(_, old, new)| moved(old, new)) .map(|(ch, _, new)| (ch, f64::from(new))) .collect(); - cx.write_numbers(&def.label, &edits, true); + cx.write_numbers(&def.label, &edits, Some(&start.id)); } number_box(ui, cx, start, None, s, px(44.0)); 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) { Kind::Color => color(ui, cx, def), Kind::Checkbox => { let ch = &channels[0]; - row(ui, cx, &def.label, &ch.id, marks, px(ROW_H), |ui, cx| { + row(ui, cx, &def.label, &ch.id, channels, keys, px(ROW_H), |ui, cx| { let on = cx.number(ch) >= 0.5; if checkbox(ui, ("chk", cx.node.0, ch.id.as_str()), on, &def.label) { - cx.write_numbers(&def.label, &[(ch, f64::from(u8::from(!on)))], false); + cx.write_numbers(&def.label, &[(ch, f64::from(u8::from(!on)))], None); } spacer(ui); }); } - Kind::Toggles => row(ui, cx, &def.label, &channels[0].id, marks, px(ROW_H), |ui, cx| { + Kind::Toggles => row(ui, cx, &def.label, &channels[0].id, channels, keys, px(ROW_H), |ui, cx| { for (ch, name) in channels.iter().zip(&def.entries) { let on = cx.number(ch) >= 0.5; if toggle_button(ui, cx, ("tgl", cx.node.0, ch.id.as_str()), name, on) { - cx.write_numbers(name, &[(ch, f64::from(u8::from(!on)))], false); + cx.write_numbers(name, &[(ch, f64::from(u8::from(!on)))], None); } } spacer(ui); }), Kind::Segmented => { let ch = &channels[0]; - row(ui, cx, &def.label, &ch.id, marks, px(ROW_H + 2.0), |ui, cx| { + row(ui, cx, &def.label, &ch.id, channels, keys, px(ROW_H + 2.0), |ui, cx| { let segments: Vec<_> = def.entries.iter().map(|e| ui::MultiSegment::text(e)).collect(); let mut spec = ui::SegmentedControl::new(&segments, choice_index(cx, def)); spec.width = fill(); @@ -112,7 +111,7 @@ pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) { } Kind::Combo => { let ch = &channels[0]; - row(ui, cx, &def.label, &ch.id, marks, px(ROW_H + 6.0), |ui, cx| { + row(ui, cx, &def.label, &ch.id, channels, keys, px(ROW_H + 6.0), |ui, cx| { let current = choice_index(cx, def); let items: Vec<_> = def .entries @@ -129,7 +128,7 @@ pub(super) fn render(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) { } Kind::Point => { let ch = &channels[0]; - row(ui, cx, &def.label, &ch.id, marks, px(ROW_H), |ui, cx| { + row(ui, cx, &def.label, &ch.id, channels, keys, px(ROW_H), |ui, cx| { let point = cx.point(ch); for (axis, name) in ["X", "Y"].into_iter().enumerate() { 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) { ui.leaf("pad", Spec { size: [px(0.0), fill()], ..Spec::default() }); } -/// Label column, `body`, then the expression badge and keyframe diamond of `marks`. -fn 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)) { +/// Label column, `body`, then the expression badge of `marks` and, when `keys`, their keyframe diamond. +fn 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)) { ui.open( ("row", cx.node.0, key), 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: if cx.has_expression(marks) { expression_badge(ui); } - if marks.is_empty() { + if !keys { ui.leaf("mark-gap", Spec { size: [px(MARK_W), fill()], ..Spec::default() }); } else { let state = cx.key_state(marks); @@ -185,7 +184,7 @@ fn number_box(ui: &mut Ui, cx: &mut Cx, ch: &Channel, axis: Option, value let id = ui.id(("num", cx.node.0, ch.id.as_str(), axis)); let focused = ui.focused() == Some(id); if focused && cx.edit.number.as_ref().is_none_or(|e| e.id != id) { - cx.edit.number = Some(NumberEdit { id, buf: format_value(ch, value), channel: ch.clone(), axis }); + cx.edit.number = Some(NumberEdit { id, node: cx.node, buf: format_value(ch, value), channel: ch.clone(), axis }); ui.focus_all(id); } let mut shown; @@ -289,7 +288,7 @@ fn write_choice(cx: &mut Cx, def: &ControlDef, index: usize) { if def.fuid { cx.write_value(&def.label, &ch.id, ParamValue::FuId(def.entries[index].clone())); } else { - cx.write_numbers(&def.label, &[(ch, index as f64)], false); + cx.write_numbers(&def.label, &[(ch, index as f64)], None); } } @@ -297,7 +296,7 @@ fn write_choice(cx: &mut Cx, def: &ControlDef, index: usize) { fn color(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) { let channels = def.channels.as_slice(); let current: Vec = channels.iter().map(|ch| cx.number(ch)).collect(); - row(ui, cx, &def.label, ("group", &channels[0].id), channels, ui::children(), |ui, cx| { + row(ui, cx, &def.label, ("group", &channels[0].id), channels, true, ui::children(), |ui, cx| { let rgba = [0, 1, 2, 3].map(|i| current.get(i).map_or(1.0, |v| v.clamp(0.0, 1.0) as f32)); let mut spec = ui::ColorPicker::new(rgba); spec.width = fill(); @@ -308,19 +307,19 @@ fn color(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) { .iter() .zip(next) .zip(rgba) - .filter(|((_, new), old)| (new - old).abs() > 1e-6) + .filter(|((_, new), old)| (new - old).abs() > 1e-4) .map(|((ch, new), _)| (ch, f64::from(new))) .collect(); - cx.write_numbers(&def.label, &edits, true); + cx.write_numbers(&def.label, &edits, Some(&channels[0].id)); } }); for (ch, name) in channels.iter().zip(["Red", "Green", "Blue", "Alpha"]) { - row(ui, cx, name, &ch.id, &[], px(ROW_H), |ui, cx| { + row(ui, cx, name, &ch.id, &[], false, px(ROW_H), |ui, cx| { let value = cx.number(ch); let mut spec = ui::Slider::new(value as f32, 0.0, 1.0, cx.default_of(ch) as f32); spec.label = name; if let Some(next) = ui::slider(ui, ("clr-sld", cx.node.0, ch.id.as_str()), spec) { - cx.write_numbers(&def.label, &[(ch, f64::from(next))], true); + cx.write_numbers(&def.label, &[(ch, f64::from(next))], Some(&ch.id)); } number_box(ui, cx, ch, None, value, px(52.0)); }); @@ -330,7 +329,7 @@ fn color(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) { /// A text well; edits apply live and fold into one undo step until it loses the keys. fn text(ui: &mut Ui, cx: &mut Cx, def: &ControlDef) { let ch = &def.channels[0]; - row(ui, cx, &def.label, &ch.id, &[], px(ROW_H), |ui, cx| { + row(ui, cx, &def.label, &ch.id, &def.channels, false, px(ROW_H), |ui, cx| { let id = ui.id(("txt", cx.node.0, ch.id.as_str())); let focused = ui.focused() == Some(id); let model = cx.comp.node(cx.node).static_str(&ch.id).unwrap_or(&def.default_text).to_owned(); diff --git a/crates/app/src/inspector/edit.rs b/crates/app/src/inspector/edit.rs index b2faef93bebdb5802f1ac939a4bf49c2b1cf908d..518e47a13547131f7734200a436727a76d5d8717 100644 --- a/crates/app/src/inspector/edit.rs +++ b/crates/app/src/inspector/edit.rs @@ -13,6 +13,8 @@ pub(super) const SCRUB_GRACE: Duration = Duration::from_millis(350); /// A numeric box being typed into; it commits when it loses the keys. pub(super) struct NumberEdit { pub id: ui::Id, + /// The node the box was focused on; selection may move on before the commit. + pub node: NodeId, pub buf: String, pub channel: Channel, /// `Some(0|1)` edits one axis of a Point input. @@ -76,11 +78,14 @@ impl Cx<'_> { } } - /// Writes numbers, as a keyframe where the input is animated. A `drag` folds into one undo - /// step per input until it rests; anything else is its own step. - pub fn write_numbers(&mut self, label: &str, edits: &[(&Channel, f64)], drag: bool) { - if drag { - let key = format!("scrub:{}:{}", self.node.0, edits[0].0.id); + /// Writes numbers, as a keyframe where the input is animated. A drag, named by its control's + /// primary channel, folds into one undo step until it rests; anything else is its own step. + pub fn write_numbers(&mut self, label: &str, edits: &[(&Channel, f64)], drag: Option<&str>) { + if edits.is_empty() { + return; + } + if let Some(primary) = drag { + let key = format!("scrub:{}:{primary}", self.node.0); self.history.push_coalesced(self.comp, format!("Adjust {label}"), key); self.edit.last_scrub = Some(self.now); } else { @@ -105,12 +110,13 @@ impl Cx<'_> { self.actions.push(InspectorAction::ParamEdited(self.node)); } - /// Commits a numeric box once it has lost the keys. + /// Commits a numeric box once it has lost the keys, onto the node it was typed into. pub fn commit_number(&mut self, edit: NumberEdit) { let Ok(value) = edit.buf.trim().parse::() else { return }; - if !value.is_finite() { + if !value.is_finite() || edit.node.0 >= self.comp.nodes.len() { return; } + let selected = std::mem::replace(&mut self.node, edit.node); let ch = &edit.channel; match edit.axis { Some(axis) => { @@ -118,8 +124,9 @@ impl Cx<'_> { point[axis] = value; self.write_value(&ch.id, &ch.id, ParamValue::Point(point)); } - None => self.write_numbers(&ch.id, &[(ch, value)], false), + None => self.write_numbers(&ch.id, &[(ch, value)], None), } + self.node = selected; } /// Keys every channel at the current frame, or removes those keys when all already have one. diff --git a/crates/app/src/inspector/mod.rs b/crates/app/src/inspector/mod.rs index 1b9083f8ddad666e0dc172e4a87c6bfbcada3acd..f59faf276c26a091ddd2a5375e7f1164b516db6f 100644 --- a/crates/app/src/inspector/mod.rs +++ b/crates/app/src/inspector/mod.rs @@ -65,11 +65,11 @@ impl InspectorPalette { } } -/// Pages for the selected node's own `UserControls` and stray inputs, rebuilt when the comp -/// revision moves. +/// Pages for the selected node's own `UserControls` and stray inputs, rebuilt when the node's +/// shape (see [`pages_key`]) changes rather than on every value edit. struct NodePages { node: NodeId, - revision: u64, + key: u64, pages: Vec, } @@ -90,9 +90,11 @@ pub struct InspectorState { impl InspectorState { pub fn new(theme: &ui::Theme) -> Self { // Parse the catalog off the UI thread; frames wait on it with a placeholder. - std::thread::spawn(|| { - catalog::catalog(); - }); + if catalog::ready().is_none() { + std::thread::spawn(|| { + catalog::catalog(); + }); + } Self { palette: InspectorPalette::from_theme(theme), expr: ExprEngine::new(), @@ -133,6 +135,7 @@ impl InspectorState { ui::Spec { size: [ui::fill(), ui::fill()], axis: ui::Axis::Y, fill: Some(p.bg), ..ui::Spec::default() }, ); let Some(node_id) = selected.filter(|id| id.0 < comp.nodes.len()) else { + self.commit_orphans(comp, history, &mut actions); chrome::empty_state(ui, p); chrome::footer(ui, p, stats); ui.close(); @@ -152,8 +155,9 @@ impl InspectorState { .or_insert_with(|| dynamic::curated_layout(&kind).unwrap_or_default()), }; - if self.node_pages.as_ref().is_none_or(|n| n.node != node_id || n.revision != comp.revision) { - self.node_pages = Some(NodePages { node: node_id, revision: comp.revision, pages: node_pages(comp, node_id, layout) }); + let key = pages_key(comp, node_id); + if self.node_pages.as_ref().is_none_or(|n| n.node != node_id || n.key != key) { + self.node_pages = Some(NodePages { node: node_id, key, pages: node_pages(comp, node_id, layout) }); } let dynamic_pages = self.node_pages.as_ref().map_or(&[][..], |n| n.pages.as_slice()); @@ -215,6 +219,24 @@ impl InspectorState { actions } + /// With nothing selected no box can keep the keys, so a typed value lands where it was typed. + fn commit_orphans(&mut self, comp: &mut Comp, history: &mut CompHistory, actions: &mut Vec) { + self.edit.text = None; + let Some(number) = self.edit.number.take() else { return }; + let mut cx = edit::Cx { + comp, + history, + actions, + node: number.node, + frame: 0.0, + now: std::time::Instant::now(), + p: self.palette, + expr: &self.expr, + edit: &mut self.edit, + }; + cx.commit_number(number); + } + fn loading(&self, ui: &mut ui::Ui, p: InspectorPalette, stats: &EvalStats, actions: Vec) -> Vec { ui.leaf( "insp-loading", @@ -244,6 +266,33 @@ fn settle_edits(ui: &mut ui::Ui, cx: &mut edit::Cx) { } } +/// What `node_pages` reads, minus values: kind, `UserControls` ids, and each input's name, +/// value type and whether it is driven or wired. Order-independent over the input map. +fn pages_key(comp: &Comp, node: NodeId) -> u64 { + use std::hash::{Hash, Hasher}; + let hash = |item: &dyn Fn(&mut std::hash::DefaultHasher)| { + let mut h = std::hash::DefaultHasher::new(); + item(&mut h); + h.finish() + }; + let n = comp.node(node); + let controls = n.raw.get_table("UserControls").map_or(0, |t| { + t.entries.iter().fold(t.entries.len() as u64, |acc, (key, _)| match key { + model::LuaKey::Str(id) => acc.wrapping_add(hash(&|h| id.hash(h))), + _ => acc, + }) + }); + let inputs = n.inputs.iter().fold(0u64, |acc, (key, b)| { + let wired = b.source_op.as_deref().is_some_and(|op| comp.node_by_name.contains_key(op)); + acc.wrapping_add(hash(&|h| { + key.hash(h); + b.value.as_ref().map(std::mem::discriminant).hash(h); + (b.expression.is_some(), b.source_op.is_some(), wired).hash(h); + })) + }); + hash(&|h| (&n.kind, controls, inputs).hash(h)) +} + /// The node's `UserControls` (one page per `ICS_ControlPage`) and inputs no catalog row covers. fn node_pages(comp: &Comp, node: NodeId, layout: &ToolLayout) -> Vec { let mut by_page: Vec<(String, Vec)> = Vec::new(); diff --git a/crates/app/src/inspector/tests.rs b/crates/app/src/inspector/tests.rs index 409fc42f87c656989512bfb7fcc4659cd2a6685a..ba13ccc2381a083a5d826227383310637f32e47f 100644 --- a/crates/app/src/inspector/tests.rs +++ b/crates/app/src/inspector/tests.rs @@ -441,4 +441,84 @@ mod catalog_layout { assert!(h.history.undo(&mut h.comp)); assert_eq!(h.number("Blend"), Some(0.2)); } + + fn type_into(h: &mut Harness, well: [f32; 4], text: &str) { + h.click(center(well)); + for ch in text.chars() { + let key = winit::keyboard::Key::Character(ch.to_string().into()); + h.ui.event(ui::Event::Key { key, text: Some(ch.to_string()), modifiers: Default::default() }); + h.frame(16); + } + } + + /// A color drag that moves no RGB channel (alpha on an RGB-only group, hue on gray) reaches + /// `write_numbers` with nothing to write. + #[test] + fn empty_edits_write_nothing_and_never_panic() { + let mut h = Harness::new("Background", 0); + let (node, mut actions) = (h.node, Vec::new()); + let channel = &find("Background", "TopLeftRed").channels[0]; + let mut edit = super::super::edit::EditState::default(); + let mut cx = super::super::edit::Cx { + comp: &mut h.comp, + history: &mut h.history, + actions: &mut actions, + node, + frame: 0.0, + now: h.at, + p: h.state.palette, + expr: &h.state.expr, + edit: &mut edit, + }; + cx.write_numbers("Color", &[], Some(&channel.id)); + cx.write_numbers("Color", &[], None); + assert!(actions.is_empty() && edit.last_scrub.is_none()); + assert!(!h.history.undo(&mut h.comp)); + } + + #[test] + fn typed_value_commits_to_the_node_it_was_typed_into() { + let mut h = Harness::new("Blur", 0); + h.comp = Comp::from_fusion_str("Composition { Tools = ordered() { Blur1 = Blur {}, Merge1 = Merge {}, }, }").expect("comp"); + h.node = h.comp.find_node("Blur1").expect("blur"); + h.frame(0); + let well = h.rect(0, "XBlurSize", ("num", h.node.0, "XBlurSize", None::)); + type_into(&mut h, well, "7"); + let blur = h.node; + + h.node = h.comp.find_node("Merge1").expect("merge"); + h.frame(16); + h.frame(16); + assert_eq!(h.comp.node(blur).static_number("XBlurSize"), Some(7.0)); + assert!(h.comp.node(h.node).inputs.values().all(|b| b.value.is_none()), "Merge1 was touched"); + } + + #[test] + fn typed_value_commits_to_its_node_on_deselect() { + let mut h = Harness::new("Blur", 0); + let well = h.rect(0, "XBlurSize", ("num", h.node.0, "XBlurSize", None::)); + type_into(&mut h, well, "9"); + h.at += std::time::Duration::from_millis(16); + h.ui.begin([360.0, 900.0], 1.0, h.at); + let pane = ui::Id::ROOT.child(PANE); + h.state.build_ui(&mut h.ui, pane, &mut h.comp, &mut h.history, None, 0.0, &engine::EvalStats::default()); + h.ui.end(); + assert_eq!(h.number("XBlurSize"), Some(9.0)); + assert!(h.state.edit.number.is_none()); + } + + #[test] + fn pages_are_not_rebuilt_by_value_edits() { + let mut h = Harness::new("Merge", 2); + let key = |h: &Harness| h.state.node_pages.as_ref().map(|n| n.key); + h.comp.set_input_value(h.node, "Blend", model::ParamValue::Number(0.2)); + h.frame(16); + let before = key(&h); + h.comp.set_input_value(h.node, "Blend", model::ParamValue::Number(0.7)); + h.frame(16); + assert_eq!(key(&h), before); + h.comp.set_input_value(h.node, "Stray", model::ParamValue::Number(1.0)); + h.frame(16); + assert_ne!(key(&h), before); + } } diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index c4478ccca831c345901ecdd4eb1faa1ca3d65266..4fd76e90ac8e50c0d43258d0da8d16b27ef72ba9 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -58,29 +58,60 @@ struct VirtualFile { /// In-memory files that shadow the filesystem for still and sequence loading, since `wasm32` has no `std::fs`. static VIRTUAL_FILES: RwLock> = RwLock::new(Vec::new()); +/// Total bytes registered virtual files may hold, so dropping a huge folder cannot exhaust the tab. +const MAX_VIRTUAL_BYTES: usize = 512 * 1024 * 1024; + +/// `path`'s components with `.`, empty and resolved `..` segments removed. fn path_parts(path: &Path) -> Vec { - path.to_string_lossy() - .split(['/', '\\']) - .filter(|p| !p.is_empty() && *p != ".") - .map(str::to_owned) - .collect() + let mut parts: Vec = Vec::new(); + for part in path.to_string_lossy().split(['/', '\\']) { + match part { + "" | "." => {} + ".." => { + parts.pop(); + } + _ => parts.push(part.to_owned()), + } + } + parts +} + +/// The registered file whose path shares the most trailing components with `want`, so a comp's +/// absolute `Loader` path still finds a file dropped under a relative one. Exact case wins over +/// case-insensitive; a tie (`/A/bg.png` vs `/B/bg.png` for `bg.png`) matches nothing. +fn find_virtual<'a>(files: &'a [VirtualFile], want: &[String]) -> Option<&'a VirtualFile> { + let exact = |a: &String, b: &String| a == b; + let folded = |a: &String, b: &String| a.to_lowercase() == b.to_lowercase(); + [&exact as &dyn Fn(&String, &String) -> bool, &folded].into_iter().find_map(|same| { + let shared = |f: &VirtualFile| f.parts.iter().rev().zip(want.iter().rev()).take_while(|(a, b)| same(a, b)).count(); + let best = files.iter().map(shared).max().filter(|&n| n > 0)?; + let mut tied = files.iter().filter(|f| shared(f) == best); + match (tied.next(), tied.next()) { + (Some(file), None) => Some(Some(file)), + _ => Some(None), + } + })? } -/// Bytes of the virtual file sharing the longest run of trailing path components with `path`, so a -/// comp's absolute `Loader` path still finds a file registered under a dropped folder's relative path. fn virtual_bytes(path: &Path) -> Option> { let files = VIRTUAL_FILES.read().ok()?; if files.is_empty() { return None; } - let want = path_parts(path); - let shared = |f: &VirtualFile| f.parts.iter().rev().zip(want.iter().rev()).take_while(|(a, b)| a == b).count(); - files - .iter() - .map(|f| (shared(f), f)) - .filter(|(n, _)| *n > 0) - .max_by_key(|(n, _)| *n) - .map(|(_, f)| Arc::clone(&f.bytes)) + find_virtual(&files, &path_parts(path)).map(|f| Arc::clone(&f.bytes)) +} + +/// Adds or replaces `parts`, refusing when `files` would then hold more than `cap` bytes. +fn insert_capped(files: &mut Vec, cap: usize, parts: Vec, bytes: Arc<[u8]>) -> bool { + let held: usize = files.iter().filter(|f| f.parts != parts).map(|f| f.bytes.len()).sum(); + if held.saturating_add(bytes.len()) > cap { + return false; + } + match files.iter_mut().find(|f| f.parts == parts) { + Some(existing) => existing.bytes = bytes, + None => files.push(VirtualFile { parts, bytes }), + } + true } fn path_exists(path: &Path) -> bool { @@ -128,15 +159,11 @@ impl MediaCache { } } - /// Registers `bytes` as the file at `path` for every `MediaCache` in the process. - pub fn insert_virtual_bytes(path: impl AsRef, bytes: impl Into>) { - let parts = path_parts(path.as_ref()); - let bytes = bytes.into(); - let Ok(mut files) = VIRTUAL_FILES.write() else { return }; - match files.iter_mut().find(|f| f.parts == parts) { - Some(existing) => existing.bytes = bytes, - None => files.push(VirtualFile { parts, bytes }), - } + /// Registers `bytes` as the file at `path` for every `MediaCache` in the process. `false` + /// when the files held would pass [`MAX_VIRTUAL_BYTES`], leaving the registry unchanged. + pub fn insert_virtual_bytes(path: impl AsRef, bytes: impl Into>) -> bool { + let Ok(mut files) = VIRTUAL_FILES.write() else { return false }; + insert_capped(&mut files, MAX_VIRTUAL_BYTES, path_parts(path.as_ref()), bytes.into()) } pub fn clear_virtual_bytes() { @@ -955,4 +982,44 @@ mod tests { assert!(path_exists(Path::new("elsewhere/vf_seq.0002.png"))); assert!(!path_exists(Path::new("vf_proj/vf_seq.0003.png"))); } + + fn file(path: &str, len: usize) -> VirtualFile { + VirtualFile { parts: path_parts(Path::new(path)), bytes: vec![0; len].into() } + } + + fn found<'a>(files: &'a [VirtualFile], path: &str) -> Option<&'a [String]> { + find_virtual(files, &path_parts(Path::new(path))).map(|f| f.parts.as_slice()) + } + + #[test] + fn virtual_paths_normalize_dots_and_separators() { + assert_eq!(path_parts(Path::new("/a/./b/../c\\d.png")), ["a", "c", "d.png"]); + assert_eq!(path_parts(Path::new("../../x.png")), ["x.png"]); + } + + #[test] + fn virtual_matching_prefers_exact_and_rejects_ambiguous_basenames() { + let files = [file("A/bg.png", 1), file("B/bg.png", 1), file("only.png", 1), file("Proj/Seq.exr", 1)]; + assert_eq!(found(&files, "/x/A/bg.png"), Some(&["A".to_owned(), "bg.png".to_owned()][..])); + assert_eq!(found(&files, "/x/../B/./bg.png").map(<[String]>::len), Some(2)); + assert_eq!(found(&files, "/C/bg.png"), None, "two files share the basename"); + assert_eq!(found(&files, "bg.png"), None); + assert!(found(&files, "/deep/elsewhere/only.png").is_some()); + assert!(found(&files, "/proj/seq.EXR").is_some(), "case-insensitive fallback"); + assert_eq!(found(&files, "/a/missing.png"), None); + } + + #[test] + fn virtual_files_stop_at_the_memory_cap() { + let mut files = Vec::new(); + let put = |files: &mut Vec, name: &str, len: usize| { + insert_capped(files, 10, path_parts(Path::new(name)), vec![0; len].into()) + }; + assert!(put(&mut files, "a", 6)); + assert!(!put(&mut files, "b", 5)); + assert!(put(&mut files, "b", 4)); + assert!(put(&mut files, "a", 6), "replacing a file frees its old bytes"); + assert!(!put(&mut files, "a", 7)); + assert_eq!(files.iter().map(|f| f.bytes.len()).sum::(), 10); + } } diff --git a/crates/engine/src/media/exr.rs b/crates/engine/src/media/exr.rs index 25b82642237d7fd5cb60630d18f5452672ce4b15..705d14a50f704526ffed56259ec10c9f9bb9d9f6 100644 --- a/crates/engine/src/media/exr.rs +++ b/crates/engine/src/media/exr.rs @@ -150,13 +150,24 @@ pub(super) fn decode_exr_rgba( blue_name: Option<&str>, alpha_name: Option<&str>, post_multiply: bool, +) -> Option { + let names = [red_name, green_name, blue_name, alpha_name]; + match super::virtual_bytes(path) { + Some(bytes) => decode_exr_from(std::io::Cursor::new(bytes), names, post_multiply), + None => decode_exr_from(std::io::BufReader::new(std::fs::File::open(path).ok()?), names, post_multiply), + } +} + +fn decode_exr_from( + reader: R, + [red_name, green_name, blue_name, alpha_name]: [Option<&str>; 4], + post_multiply: bool, ) -> Option { use ::exr::block::reader::ChunksReader; use ::exr::meta::attribute::SampleType; use ::exr::prelude::*; - let file = std::fs::File::open(path).ok()?; - let chunks_reader = ::exr::block::read(std::io::BufReader::new(file), false).ok()?; + let chunks_reader = ::exr::block::read(reader, false).ok()?; let first_header = chunks_reader.headers().first()?; let w = first_header.layer_size.width(); let h = first_header.layer_size.height(); @@ -278,3 +289,21 @@ pub(super) fn decode_exr_rgba( rgba_f32: Some(Arc::new(raw_f32)), }) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::media::MediaCache; + + #[test] + fn dropped_exr_bytes_decode_without_a_file_on_disk() { + let pixels = image::Rgba32FImage::from_pixel(2, 1, image::Rgba([2.5, 0.5, 0.0, 1.0])); + let mut out = std::io::Cursor::new(Vec::new()); + image::DynamicImage::ImageRgba32F(pixels).write_to(&mut out, image::ImageFormat::OpenExr).unwrap(); + assert!(MediaCache::insert_virtual_bytes("vexr_drop/frame.exr", out.into_inner())); + + let decoded = decode_exr_rgba(Path::new("/not/on/disk/vexr_drop/frame.exr"), None, None, None, None, false).unwrap(); + assert_eq!(decoded.size, [2, 1]); + assert_eq!(&decoded.rgba_f32.unwrap()[..4], &[2.5, 0.5, 0.0, 1.0]); + } +} diff --git a/crates/engine/src/profile.rs b/crates/engine/src/profile.rs index 6a85390016d42dc689646c5ea1066fe8b4362fce..801ffd5d7b3bc615130c5bb5e0b555f65445570e 100644 --- a/crates/engine/src/profile.rs +++ b/crates/engine/src/profile.rs @@ -3,7 +3,10 @@ use model::{Comp, NodeId}; use std::collections::HashMap; use std::fmt::Write as _; +#[cfg(not(target_arch = "wasm32"))] use std::time::Instant; +#[cfg(target_arch = "wasm32")] +use web_time::Instant; /// Profiling telemetry for a single node lookup or evaluation within a frame. #[derive(Clone, Debug, PartialEq)] diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs index 2927d7e6ebb70e63b00f329f9b584d390d4ebbe8..631e155e3fc2efff42cc0826718b478f14003c4c 100644 --- a/crates/flow/src/lib.rs +++ b/crates/flow/src/lib.rs @@ -77,10 +77,36 @@ struct ModalTransform { #[derive(Clone, Debug)] struct WireDrag { src: NodeId, + /// The output the wire leaves: the detached binding's own, else the source tool's default. + src_output: String, cursor_local: [f32; 2], target: Option, /// Set when dragging an existing connected input off to disconnect/rewire. detached_from: Option<(NodeId, String)>, + /// Press point of a rewire drag that has not yet moved [`DETACH_DRAG`]; the wire stays + /// connected until it does, so a plain click changes nothing. + pending: Option<[f32; 2]>, +} + +impl WireDrag { + /// Whether this drag has detached its wire inside an open history group. + fn owns_group(&self) -> bool { + self.detached_from.is_some() && self.pending.is_none() + } +} + +/// Screen pixels a pressed input triangle must travel before its wire detaches. +const DETACH_DRAG: f32 = 4.0; + +/// Output a wire from a `kind` tool leaves by: masks and materials have their own. +fn default_output(kind: &str) -> &'static str { + if kind.ends_with("Mask") { + "Mask" + } else if kind.starts_with("Mtl") { + "MaterialOutput" + } else { + "Output" + } } #[derive(Clone, Debug)] @@ -182,6 +208,8 @@ pub struct FlowView { hovered_wire: Option, modal: Option, wire_drag: Option, + /// A gesture that owned a history group was dropped without its history; the next input closes it. + orphaned_group: bool, box_select: Option, panning: Option<([f32; 2], [f32; 2])>, lmb_drag_node: Option<(NodeId, [f32; 2], bool)>, @@ -208,6 +236,7 @@ impl FlowView { hovered_wire: None, modal: None, wire_drag: None, + orphaned_group: false, box_select: None, panning: None, lmb_drag_node: None, @@ -282,8 +311,7 @@ impl FlowView { self.hovered_node = None; self.hovered_handle = None; self.hovered_wire = None; - self.modal = None; - self.wire_drag = None; + self.abandon_gestures(); self.box_select = None; self.lmb_drag_node = None; self.last_click = None; @@ -310,12 +338,17 @@ impl FlowView { } self.hovered_handle = None; self.hovered_wire = None; - self.modal = None; - self.wire_drag = None; + self.abandon_gestures(); self.lmb_drag_node = None; self.last_click = None; } + /// Drops in-flight gestures that have no history to cancel through. + fn abandon_gestures(&mut self) { + let wire = self.wire_drag.take().is_some_and(|wd| wd.owns_group()); + self.orphaned_group |= self.modal.take().is_some() || wire; + } + /// Computes a clean world-space spawn position for a newly added node. pub fn spawn_position(&self, comp: &Comp, is_generator: bool) -> [f32; 2] { if let Some(sel_id) = self.primary.filter(|id| id.0 < comp.nodes.len()) { @@ -499,11 +532,20 @@ impl FlowView { /// Drops an in-flight wire drag; a detached input is wired back. fn cancel_wire_drag(&mut self, comp: &mut Comp, history: &mut CompHistory, actions: &mut Vec) { - if self.wire_drag.take().is_some_and(|wd| wd.detached_from.is_some()) && history.cancel_group(comp) { + if self.wire_drag.take().is_some_and(|wd| wd.owns_group()) && history.cancel_group(comp) { actions.push(FlowAction::GraphMutated(None)); } } + /// Ends every held gesture, as the window losing focus must. + fn cancel_gestures(&mut self, comp: &mut Comp, history: &mut CompHistory, actions: &mut Vec) { + self.cancel_modal(comp, history); + self.cancel_wire_drag(comp, history, actions); + self.panning = None; + self.box_select = None; + self.lmb_drag_node = None; + } + fn handle_key( &mut self, comp: &mut Comp, @@ -699,8 +741,12 @@ impl FlowView { ) -> Vec { let mut actions = Vec::new(); self.pointer_local = [pointer_window[0] - rect[0], pointer_window[1] - rect[1]]; + if std::mem::take(&mut self.orphaned_group) { + history.commit_group(comp); + } match event { + ui::Event::PointerCancelled => self.cancel_gestures(comp, history, &mut actions), ui::Event::PointerMoved(p) => { self.pointer_local = [p[0] - rect[0], p[1] - rect[1]]; if let Some((start_p, start_pan)) = self.panning { @@ -711,6 +757,17 @@ impl FlowView { } else if self.modal.is_some() { self.apply_modal(comp, modifiers.shift_key()); } else if self.wire_drag.is_some() { + if let Some(wd) = &mut self.wire_drag { + if let Some((press, (dst, port))) = wd.pending.zip(wd.detached_from.as_ref()) { + if (press[0] - self.pointer_local[0]).hypot(press[1] - self.pointer_local[1]) <= DETACH_DRAG { + return actions; + } + history.begin_group(comp, "Rewire"); + comp.disconnect(*dst, port); + actions.push(FlowAction::GraphMutated(Some(*dst))); + wd.pending = None; + } + } let hit = self.hit_drop_target(comp, self.pointer_local); if let Some(wd) = &mut self.wire_drag { wd.cursor_local = self.pointer_local; @@ -788,25 +845,27 @@ impl FlowView { } else if let Some((src, None)) = handle { self.wire_drag = Some(WireDrag { src, + src_output: default_output(&comp.node(src).kind).to_owned(), cursor_local: self.pointer_local, target: None, detached_from: None, + pending: None, }); - } else if let Some((dst, Some(port), src)) = handle.and_then(|(dst, port)| { + } else if let Some((dst, port, src)) = handle.and_then(|(dst, port)| { let port = port?; let src = self.upstream_of(comp, comp.node(dst), port)?; - Some((dst, Some(port.to_owned()), src)) + Some((dst, port.to_owned(), src)) }) { // Dragging a connected triangle detaches it: drop on another triangle to move // the wire, or on empty canvas to disconnect. - history.begin_group(comp, "Rewire"); - comp.disconnect(dst, &port); - actions.push(FlowAction::GraphMutated(Some(dst))); + let src_output = comp.node(dst).inputs[&port].source_output.clone(); self.wire_drag = Some(WireDrag { src, + src_output: src_output.unwrap_or_else(|| default_output(&comp.node(src).kind).to_owned()), cursor_local: self.pointer_local, target: None, detached_from: Some((dst, port)), + pending: Some(self.pointer_local), }); } else if let Some(nid) = self.hit_node(comp, self.pointer_local) { let double = self.last_click.is_some_and(|(t, prev)| prev == nid && at.duration_since(t) <= DOUBLE_CLICK); @@ -851,7 +910,7 @@ impl FlowView { self.confirm_modal(comp, history, &mut actions); } } - if let Some(wd) = self.wire_drag.take() { + if let Some(wd) = self.wire_drag.take().filter(|wd| wd.pending.is_none()) { let detached = wd.detached_from.is_some(); let target = self.hit_drop_target(comp, self.pointer_local).map(|(node, port)| (node, port.to_owned())); if let Some((dst, port)) = target { @@ -864,7 +923,7 @@ impl FlowView { if !detached { history.begin_group(comp, "Connect"); } - match comp.connect_output(wd.src, "Output", dst, &port) { + match comp.connect_output(wd.src, &wd.src_output, dst, &port) { Ok(()) => { history.commit_group(comp); actions.push(FlowAction::GraphMutated(Some(dst))); @@ -1286,7 +1345,10 @@ mod tests { ModifiersState::empty(), ); assert!(flow.wire_drag.is_some()); + assert_eq!(source(&comp, merge, "Background").as_deref(), Some("BG1"), "a bare press detaches nothing"); + 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()); assert!(comp.node(merge).inputs["Background"].source_op.is_none()); + assert!(history.in_group()); let acts = key(&mut flow, &mut comp, &mut history, Key::Named(NamedKey::Escape), ModifiersState::empty()); assert!(flow.wire_drag.is_none()); @@ -1460,4 +1522,127 @@ mod tests { assert!(flow.modal.is_some()); assert!(history.in_group()); } + + fn button(pressed: bool) -> ui::Event { + ui::Event::Button { button: MouseButton::Left, pressed, at: Instant::now() } + } + + #[test] + fn clicking_a_connected_triangle_without_dragging_changes_nothing() { + let (mut comp, mut flow, mut history) = wire_flow(); + let merge = id(&comp, "Merge1"); + let tri = input_center(&flow, &comp, merge, "Background"); + let revision = comp.revision; + send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(tri), tri); + send(&mut flow, &mut comp, &mut history, button(true), tri); + send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved([tri[0] + 2.0, tri[1]]), tri); + assert!(!history.in_group()); + send(&mut flow, &mut comp, &mut history, button(false), [tri[0] + 2.0, tri[1]]); + assert!(flow.wire_drag.is_none()); + assert_eq!(source(&comp, merge, "Background").as_deref(), Some("BG1")); + assert_eq!(comp.revision, revision); + assert!(!history.can_undo() && !history.in_group()); + } + + #[test] + fn rewiring_keeps_the_wires_own_output() { + let mut comp = Comp::from_fusion_str( + r#"Composition { + Tools = ordered() { + Ellipse1 = EllipseMask { ViewInfo = OperatorInfo { Pos = { 0, 0 } }, }, + Checker = Fuse.CheckerPieceGenerator { ViewInfo = OperatorInfo { Pos = { 0, 80 } }, }, + Mtl1 = MtlBlinn { ViewInfo = OperatorInfo { Pos = { 0, 160 } }, }, + Merge1 = Merge { + Inputs = { + Foreground = Input { SourceOp = "Checker", Source = "ExtraScale" }, + EffectMask = Input { SourceOp = "Ellipse1", Source = "Mask" }, + }, + ViewInfo = OperatorInfo { Pos = { 160, 0 } }, + }, + Blur1 = Blur { ViewInfo = OperatorInfo { Pos = { 160, 120 } }, }, + Blur2 = Blur { ViewInfo = OperatorInfo { Pos = { 160, 240 } }, }, + }, + }"#, + ) + .expect("parse comp"); + let mut flow = FlowView::new(&ui::Theme::new(&theme::KNIFE, true)); + (flow.size, flow.pan, flow.zoom) = ([800.0, 600.0], [80.0, 60.0], 1.0); + let mut history = CompHistory::new(); + let (merge, blur, blur2) = (id(&comp, "Merge1"), id(&comp, "Blur1"), id(&comp, "Blur2")); + let output = |comp: &Comp, node: NodeId, port: &str| comp.node(node).inputs[port].source_output.clone(); + + let body = flow.world_to_local(comp.node(blur).pos); + let from = input_center(&flow, &comp, merge, "Foreground"); + drag(&mut flow, &mut comp, &mut history, from, body); + assert_eq!(output(&comp, blur, "Input").as_deref(), Some("ExtraScale")); + + let from = input_center(&flow, &comp, merge, "EffectMask"); + let to = input_center(&flow, &comp, blur, "EffectMask"); + drag(&mut flow, &mut comp, &mut history, from, to); + assert_eq!(output(&comp, blur, "EffectMask").as_deref(), Some("Mask")); + + // A fresh wire picks the output its source tool has. + let body = flow.world_to_local(comp.node(blur2).pos); + for (name, expected) in [("Ellipse1", "Mask"), ("Mtl1", "MaterialOutput"), ("Checker", "Output")] { + let from = output_center(&flow, &comp, id(&comp, name)); + drag(&mut flow, &mut comp, &mut history, from, body); + assert_eq!(output(&comp, blur2, "Input").as_deref(), Some(expected), "{name}"); + } + } + + #[test] + fn losing_pointer_focus_cancels_an_open_rewire_or_modal() { + let (mut comp, mut flow, mut history) = wire_flow(); + let merge = id(&comp, "Merge1"); + let tri = input_center(&flow, &comp, merge, "Background"); + let far = [tri[0] + 40.0, tri[1] + 40.0]; + send(&mut flow, &mut comp, &mut history, button(true), tri); + send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(far), far); + assert!(history.in_group() && source(&comp, merge, "Background").is_none()); + + send(&mut flow, &mut comp, &mut history, ui::Event::PointerCancelled, far); + assert!(flow.wire_drag.is_none() && !history.in_group() && !history.can_undo()); + assert_eq!(source(&comp, merge, "Background").as_deref(), Some("BG1")); + + flow.selected.insert(merge); + flow.primary = Some(merge); + key(&mut flow, &mut comp, &mut history, Key::Character("g".into()), ModifiersState::empty()); + assert!(flow.modal.is_some() && history.in_group()); + send(&mut flow, &mut comp, &mut history, ui::Event::PointerCancelled, far); + assert!(flow.modal.is_none() && !history.in_group()); + } + + #[test] + fn sanitizing_mid_gesture_does_not_leave_the_history_group_open() { + let (mut comp, mut flow, mut history) = wire_flow(); + let merge = id(&comp, "Merge1"); + flow.selected.insert(merge); + flow.primary = Some(merge); + key(&mut flow, &mut comp, &mut history, Key::Character("g".into()), ModifiersState::empty()); + assert!(history.in_group()); + flow.sanitize_ids(&comp); + send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved([5.0, 5.0]), [5.0, 5.0]); + assert!(!history.in_group()); + } + + #[test] + fn port_tables_follow_fusion() { + let comp = Comp::from_fusion_str( + "Composition { Tools = ordered() { Else = Fuse.SwitchElse {}, Key = DeltaKeyer {}, Checker = Fuse.CheckerPieceGenerator {}, }, }", + ) + .expect("parse comp"); + let mut flow = FlowView::new(&ui::Theme::new(&theme::KNIFE, true)); + flow.zoom = 1.0; + let ports = |name: &str| { + let mut found = Vec::new(); + flow.for_each_input(&comp, comp.node(id(&comp, name)), |s| found.push((s.port, s.color))); + found + }; + let names = |name: &str| ports(name).into_iter().map(|(p, _)| p).collect::>(); + assert_eq!(names("Else"), ["Input1", "Input2", "EffectMask"]); + assert_eq!(names("Key"), ["Input", "EffectMask", "Garbage.Matte", "Solid.Matte"]); + assert_eq!(names("Checker"), ["EffectMask"]); + assert!(ports("Key").iter().filter(|(p, _)| p.ends_with(".Matte")).all(|(_, c)| *c == ports::GRAY)); + } + } diff --git a/crates/flow/src/ports.rs b/crates/flow/src/ports.rs index a6990617945cb0c82034d966221fe8f89c43d87b..bf8808bcc3f74ca314f60b499fe85bb184c76b22 100644 --- a/crates/flow/src/ports.rs +++ b/crates/flow/src/ports.rs @@ -17,7 +17,7 @@ const STUB: f32 = 6.0; const YELLOW: [f32; 4] = [0.91, 0.77, 0.23, 1.0]; const GREEN: [f32; 4] = [0.42, 0.75, 0.23, 1.0]; const BLUE: [f32; 4] = [0.23, 0.63, 0.91, 1.0]; -const GRAY: [f32; 4] = [0.80, 0.81, 0.86, 1.0]; +pub(crate) const GRAY: [f32; 4] = [0.80, 0.81, 0.86, 1.0]; const PURPLE: [f32; 4] = [0.72, 0.50, 0.92, 1.0]; static SCENE_INPUTS: [&str; 32] = [ @@ -116,9 +116,10 @@ fn table(n: &Node) -> (Table, Class) { match n.kind.as_str() { "Merge" | "Dissolve" | "ChannelBoolean" => (Table::Fixed(&["Background", "Foreground", "EffectMask"]), TwoInput), "Displace" => (Table::Fixed(&["Input", "Foreground", "EffectMask"]), TwoInput), - "Background" | "FastNoise" | "TextPlus" | "Loader" | "EllipseMask" | "RectangleMask" | "PolylineMask" => { - (Table::Fixed(&["EffectMask"]), Generator) - } + "Background" | "FastNoise" | "TextPlus" | "Loader" | "EllipseMask" | "RectangleMask" | "PolylineMask" + | "Fuse.CheckerPieceGenerator" => (Table::Fixed(&["EffectMask"]), Generator), + "Fuse.SwitchElse" => (Table::Fixed(&["Input1", "Input2", "EffectMask"]), Single), + "DeltaKeyer" => (Table::Fixed(&["Input", "EffectMask", "Garbage.Matte", "Solid.Matte"]), Single), "Renderer3D" | "Transform3D" | "ReplaceMaterial3D" | "Override3D" | "ReplaceNormals3D" | "Displace3D" | "Duplicate3D" => { (Table::Fixed(&["SceneInput"]), Single) } @@ -187,7 +188,7 @@ fn port_color(n: &Node, port: &str) -> [f32; 4] { "Input1" if n.kind == "Switch" && zero_indexed(n) => GREEN, "Input1" => YELLOW, "Input2" | "SceneInput2" => GREEN, - "GarbageMatte" | "SolidMatte" => GRAY, + "GarbageMatte" | "SolidMatte" | "Garbage.Matte" | "Solid.Matte" => GRAY, _ => match PortRole::from_input_name(port) { PortRole::Background => YELLOW, PortRole::Foreground => GREEN, @@ -362,8 +363,12 @@ impl FlowView { /// Extra pixels around a node's rect that its handles can reach. fn handle_reach(&self, n: &Node) -> f32 { let m = Metrics::at(self.zoom); - let grow = if matches!(table(n).0, Table::Grow(_)) { n.inputs.len() as f32 * 4.5 } else { 0.0 }; - HIT_IN + m.tri_len + 4.0 + grow + let r = self.node_rect_local(n.pos); + let mut ports = 0_usize; + each_port(n, table(n).0, |_| ports += 1); + // One edge carrying every port spreads them past the node's shorter side. + 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; + HIT_IN + m.tri_len + 4.0 + spread.max(0.0) } /// Output square (`None` port) or input triangle under `local`. A node body always wins. diff --git a/crates/model/src/comp/save.rs b/crates/model/src/comp/save.rs index 4a91ffb32ef8e8e0a881427793c469af79e118e6..0cd5381d108335b184ce10e1e580abda6fdc1d91 100644 --- a/crates/model/src/comp/save.rs +++ b/crates/model/src/comp/save.rs @@ -214,9 +214,10 @@ impl Comp { ("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())); + // The first clip proper, as `node.clips.first()` (what the engine plays) is. + let clip = tool_tbl.get_table_mut("Clips").and_then(|c| { + c.entries.iter_mut().find_map(|(_, v)| v.as_table_mut().filter(|t| t.get_str("Filename").is_some())) + }); if let Some(clip) = clip { for (key, value) in updates { if let Some(value) = value { @@ -779,6 +780,39 @@ mod tests { assert_eq!(clip.global_end, 25); } + #[test] + fn loader_timing_edits_land_in_the_first_clip_of_a_multi_clip_loader() { + let src = r#"Composition { + Tools = ordered() { + L = Loader { + Clips = { + Note = { Comment = "not a clip", }, + Clip { + Filename = "a.0000.exr", + GlobalStart = 0, + GlobalEnd = 10, + }, + Clip { + Filename = "b.0000.exr", + GlobalStart = 11, + GlobalEnd = 30, + }, + }, + }, + }, + }"#; + let mut comp = Comp::from_fusion_str(src).unwrap(); + let l = comp.find_node("L").unwrap(); + comp.set_input_value(l, "GlobalOut", ParamValue::Number(25.0)); + comp.set_input_value(l, "Reverse", ParamValue::Number(1.0)); + let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap(); + let clips = &saved.node(saved.find_node("L").unwrap()).clips; + assert_eq!(clips.len(), 2); + assert_eq!((clips[0].global_end, clips[0].reverse), (25, true)); + assert_eq!((clips[1].global_start, clips[1].global_end, clips[1].reverse), (11, 30, false)); + assert!(comp.to_fusion_string().contains("Comment = \"not a clip\"")); + } + #[test] fn cleared_cross_macro_wire_keeps_its_source_op_on_save() { let src = r#"Composition { diff --git a/crates/model/src/expr.rs b/crates/model/src/expr.rs index e0e1599e7ab561b396ce436ba244d5f77b00b1a3..cf9fce8c2e9e37f5f4a5f261f5ff3e10aa5c1197 100644 --- a/crates/model/src/expr.rs +++ b/crates/model/src/expr.rs @@ -11,6 +11,32 @@ pub enum ExprValue { Text(String), } +/// Lua's `tostring` for a float: C `%.14g`, so `0.1 + 0.2` reads `0.3` and `3.0` reads `3`. +fn format_number(n: f64) -> String { + if !n.is_finite() { + return if n.is_nan() { "nan" } else if n > 0.0 { "inf" } else { "-inf" }.to_owned(); + } + let sci = format!("{:.13e}", n.abs()); + let (mantissa, exp) = sci.split_once('e').expect("`{:e}` always has an exponent"); + let exp: i32 = exp.parse().expect("exponent is an integer"); + let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect(); + let digits = digits.trim_end_matches('0'); + let digits = if digits.is_empty() { "0" } else { digits }; + let sign = if n.is_sign_negative() { "-" } else { "" }; + let (head, tail) = digits.split_at(1); + if !(-4..14).contains(&exp) { + let point = if tail.is_empty() { "" } else { "." }; + return format!("{sign}{head}{point}{tail}e{}{:02}", if exp < 0 { '-' } else { '+' }, exp.abs()); + } + if exp < 0 { + return format!("{sign}0.{}{digits}", "0".repeat(exp.unsigned_abs() as usize - 1)); + } + let int_len = exp as usize + 1; + let padded = format!("{digits:0 hi then return hi else return x end end mix = function(a, b, t) return a + (b - a) * t end @@ -197,7 +225,7 @@ mod lua { 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::Number(n) => Some(super::format_number(n)), Value::Integer(i) => Some(format!("{i}")), Value::Table(t) => t.get::("Value").ok(), _ => None, @@ -354,6 +382,7 @@ mod pure { use std::collections::HashMap; const MAX_DEPTH: usize = 64; + const MAX_TOKENS: usize = 2048; const MATH_FNS: &[&str] = &[ "abs", "acos", "asin", "atan", "ceil", "cos", "deg", "exp", "floor", "fmod", "log", "max", "min", "rad", "sin", "sqrt", "tan", @@ -365,7 +394,8 @@ mod pure { #[derive(Clone, Debug, PartialEq)] enum Tok { - Num(f64), + /// `true` for a Lua integer literal, which divides by zero as an error rather than `inf`. + Num(f64, bool), Str(String), Name(String), Op(&'static str), @@ -390,19 +420,22 @@ mod pure { i += 1; } let digits: String = chars[start + 2..i].iter().collect(); - toks.push(Tok::Num(u64::from_str_radix(&digits, 16).ok()? as f64)); + toks.push(Tok::Num(u64::from_str_radix(&digits, 16).ok()? as f64, true)); continue; } while chars.get(i).is_some_and(char::is_ascii_digit) { i += 1; } + let mut integer = true; if chars.get(i) == Some(&'.') && chars.get(i + 1) != Some(&'.') { + integer = false; i += 1; while chars.get(i).is_some_and(char::is_ascii_digit) { i += 1; } } if matches!(chars.get(i), Some('e' | 'E')) { + integer = false; i += 1; if matches!(chars.get(i), Some('+' | '-')) { i += 1; @@ -411,7 +444,8 @@ mod pure { i += 1; } } - toks.push(Tok::Num(chars[start..i].iter().collect::().parse().ok()?)); + let value: f64 = chars[start..i].iter().collect::().parse().ok()?; + toks.push(Tok::Num(value, integer && value < 2f64.powi(63))); } else if c.is_alphabetic() || c == '_' { let start = i; while chars.get(i).is_some_and(|c| c.is_alphanumeric() || *c == '_') { @@ -453,6 +487,8 @@ mod pure { Nil, Bool(bool), Num(f64), + /// An integer literal. + Int(f64), Str(String), Name(String), Index(Box, Box), @@ -500,23 +536,34 @@ mod pure { Some((op, left, right)) } - fn expr(&mut self, min_bp: u8) -> Option { + /// One more level of tree height, which nesting and every left-associative link add alike, + /// so recursive eval and drop stay bounded. + fn descend(&mut self) -> Option<()> { self.depth += 1; - let ast = if self.depth > MAX_DEPTH { None } else { self.binary(min_bp) }; - self.depth -= 1; - ast + (self.depth <= MAX_DEPTH).then_some(()) + } + + fn expr(&mut self, min_bp: u8) -> Option { + let outer = self.depth; + self.descend()?; + let ast = self.binary(min_bp)?; + self.depth = outer; + Some(ast) } fn binary(&mut self, min_bp: u8) -> Option { + let outer = self.depth; let mut lhs = self.unary()?; while let Some((op, left, right)) = self.binary_op() { if left < min_bp { break; } self.pos += 1; + self.descend()?; let rhs = self.expr(right)?; lhs = Ast::Bin(op, Box::new(lhs), Box::new(rhs)); } + self.depth = outer; Some(lhs) } @@ -533,7 +580,8 @@ mod pure { fn postfix(&mut self) -> Option { let mut node = match self.toks.get(self.pos)?.clone() { - Tok::Num(n) => Ast::Num(n), + Tok::Num(n, true) => Ast::Int(n), + Tok::Num(n, false) => Ast::Num(n), Tok::Str(s) => Ast::Str(s), Tok::Name(n) => match n.as_str() { "nil" => Ast::Nil, @@ -553,18 +601,22 @@ mod pure { Tok::Op(_) => return None, }; self.pos += 1; + let outer = self.depth; loop { if self.eat_op(".") { + self.descend()?; let Some(Tok::Name(key)) = self.peek().cloned() else { return None }; self.pos += 1; node = Ast::Index(Box::new(node), Box::new(Ast::Str(key))); } else if self.eat_op("[") { + self.descend()?; let key = self.expr(0)?; if !self.eat_op("]") { return None; } node = Ast::Index(Box::new(node), Box::new(key)); } else if self.eat_op("(") { + self.descend()?; let mut args = Vec::new(); if !self.eat_op(")") { loop { @@ -579,6 +631,7 @@ mod pure { } node = Ast::Call(Box::new(node), args); } else { + self.depth = outer; return Some(node); } } @@ -613,13 +666,23 @@ mod pure { } } + /// What `..` accepts: numbers and strings. fn text(&self) -> Option { match self { - Val::Num(n) => Some(format!("{n}")), + Val::Num(n) => Some(super::format_number(*n)), Val::Str(s) | Val::Text(s) => Some(s.clone()), _ => None, } } + + /// Lua's `tostring`, which also names `nil` and booleans. + fn tostring(&self) -> Option { + match self { + Val::Nil => Some("nil".to_owned()), + Val::Bool(b) => Some(b.to_string()), + other => other.text(), + } + } } struct Scope<'a> { @@ -655,7 +718,7 @@ mod pure { Some(match ast { Ast::Nil => Val::Nil, Ast::Bool(b) => Val::Bool(*b), - Ast::Num(n) => Val::Num(*n), + Ast::Num(n) | Ast::Int(n) => Val::Num(*n), Ast::Str(s) => Val::Str(s.clone()), Ast::Name(n) => self.name(n), Ast::Neg(a) => Val::Num(-self.eval(a)?.num()?), @@ -674,11 +737,28 @@ mod pure { let a = self.eval(a)?; if a.truthy() { a } else { self.eval(b)? } } - Ast::Bin(op, a, b) => binary(op, self.eval(a)?, self.eval(b)?)?, + Ast::Bin(op, a, b) => { + let (a_val, b_val) = (self.eval(a)?, self.eval(b)?); + // Lua 5.4 errors on integer `//` and `%` by zero; floats give `inf`/`nan`. + if matches!(*op, "//" | "%") && b_val.num() == Some(0.0) && is_integer(a) && is_integer(b) { + return None; + } + binary(op, a_val, b_val)? + } }) } } + /// Whether Lua 5.4 types `ast` as an integer: integer literals and `+ - * // %` of them. + fn is_integer(ast: &Ast) -> bool { + match ast { + Ast::Int(_) => true, + Ast::Neg(a) => is_integer(a), + Ast::Bin("+" | "-" | "*" | "//" | "%", a, b) => is_integer(a) && is_integer(b), + _ => false, + } + } + fn index<'a>(base: Val<'a>, key: Val<'a>) -> Option> { Some(match (base, key) { (Val::Node(fields), key) => match key { @@ -708,7 +788,7 @@ mod pure { fn binary<'a>(op: &str, a: Val<'a>, b: Val<'a>) -> Option> { use std::cmp::Ordering; let ordering = |a: &Val, b: &Val| match (a, b) { - (Val::Num(a), Val::Num(b)) => a.partial_cmp(b).map(Some), + (Val::Num(a), Val::Num(b)) => Some(a.partial_cmp(b)), (Val::Str(a), Val::Str(b)) => Some(Some(a.cmp(b))), _ => None, }; @@ -790,7 +870,8 @@ mod pure { } "mix" => Val::Num(arg(0)? + (arg(1)? - arg(0)?) * arg(2)?), "Point" => Val::Point([arg(0).unwrap_or(0.0), arg(1).unwrap_or(0.0)]), - "Text" | "tostring" => Val::Str(args.first().map_or(Some(String::new()), Val::text)?), + "tostring" => Val::Str(args.first()?.tostring()?), + "Text" => Val::Str(args.first().filter(|a| a.truthy()).map_or(Some(String::new()), Val::tostring)?), "tonumber" => args.first()?.num().map_or(Val::Nil, Val::Num), _ => return None, }) @@ -814,10 +895,15 @@ mod pure { read: impl FnOnce(Val) -> Option, ) -> Option { let body = match expr.trim_start().strip_prefix(':') { - Some(stmt) => stmt.trim_start().strip_prefix("return ")?, + Some(stmt) => { + let value = stmt.trim_start().strip_prefix("return ")?.trim_end(); + value.strip_suffix(';').unwrap_or(value) + } None => expr, }; - let mut parser = Parser { toks: lex(body)?, pos: 0, depth: 0 }; + // Every AST node consumes a token, so this also caps the tree's size. + let toks = lex(body).filter(|t| t.len() <= MAX_TOKENS)?; + let mut parser = Parser { toks, pos: 0, depth: 0 }; let ast = parser.expr(0)?; if parser.pos != parser.toks.len() { return None; @@ -943,8 +1029,86 @@ mod pure { assert_eq!(num(src, 0.0), None, "{src:?}"); } assert_eq!(num(":return time * 2", 2.0), Some(4.0)); + assert_eq!(num(":return time * 2;", 2.0), Some(4.0)); assert_eq!(num(&"(".repeat(200), 0.0), None); } + + #[test] + fn long_chains_are_bounded_instead_of_overflowing_the_stack() { + let sum = |terms: usize| vec!["1"; terms].join("+"); + assert_eq!(num(&sum(40), 0.0), Some(40.0)); + for terms in [100, 10_000, 200_000] { + assert_eq!(num(&sum(terms), 0.0), None, "{terms} terms"); + } + let path = |links: usize| format!("Ctl{}", ".Size".repeat(links)); + assert_eq!(num(&path(1), 0.0), Some(0.25)); + assert_eq!(num(&path(100), 0.0), None); + assert_eq!(num(&format!("max({})", vec!["1"; 5000].join(",")), 0.0), None); + assert_eq!(num(&format!("{}1{}", "-".repeat(500), ""), 0.0), None); + } + + #[test] + fn nan_compares_false_instead_of_failing() { + 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)] { + assert_eq!(num(src, 0.0), Some(want), "{src}"); + } + } + + #[test] + fn integer_division_by_zero_errors_but_float_gives_inf() { + assert_eq!(num("1 // 0", 0.0), None); + assert_eq!(num("1 % 0", 0.0), None); + assert_eq!(num("(2 + 3) % (1 - 1)", 0.0), None); + assert_eq!(num("1.0 // 0", 0.0), Some(f64::INFINITY)); + assert_eq!(num("1 // 0.0", 0.0), Some(f64::INFINITY)); + assert_eq!(num("time // 0", 2.0), Some(f64::INFINITY)); + assert!(num("time % 0", 2.0).is_some_and(f64::is_nan)); + } + + #[test] + fn tostring_names_nil_and_booleans() { + let e = ExprEngine::new(); + let (p, q, n) = (HashMap::new(), HashMap::new(), nodes()); + let s = |src: &str| e.eval_string(src, 0.0, &p, &q, &n); + assert_eq!(s("tostring(true)").as_deref(), Some("true")); + assert_eq!(s("tostring(false)").as_deref(), Some("false")); + assert_eq!(s("tostring(nil)").as_deref(), Some("nil")); + assert_eq!(s("Text(nil)").as_deref(), Some("")); + assert_eq!(s("Text(false)").as_deref(), Some("")); + assert_eq!(s("'a' .. nil"), None); + assert_eq!(s("0.1 + 0.2").as_deref(), Some("0.3")); + } + } +} + +#[cfg(test)] +mod tests { + use super::format_number; + + #[test] + fn numbers_format_like_c_percent_14g() { + for (n, want) in [ + (3.0, "3"), + (-0.0, "-0"), + (0.0, "0"), + (0.1 + 0.2, "0.3"), + (1.0 / 3.0, "0.33333333333333"), + (2.5, "2.5"), + (100.0, "100"), + (123456789012345.0, "1.2345678901234e+14"), + (99999999999999.0, "99999999999999"), + (1e15, "1e+15"), + (2f64.powi(53), "9.007199254741e+15"), + (1e100, "1e+100"), + (0.0001, "0.0001"), + (0.00001, "1e-05"), + (-1234.5, "-1234.5"), + (f64::INFINITY, "inf"), + (f64::NEG_INFINITY, "-inf"), + (f64::NAN, "nan"), + ] { + assert_eq!(format_number(n), want, "{n:e}"); + } } } @@ -980,6 +1144,13 @@ mod parity { "max(1, time, 3) + min(time, 9) + abs(-time) + ceil(time) + sqrt(time)", "cosh(time) + sinh(time) + tanh(time) + deg(1) + rad(90)", "time ~= 2.5", + "0/0 < 1", + "0/0 >= 1", + "1 // 0", + "1 % 0", + "time // 0", + "1.0 % 0 < 1", + ":return time * 2;", "'10' + 1", "Nope.Size", "1 +", @@ -988,10 +1159,24 @@ mod parity { let l = lua.eval_number(args.0, args.1, args.2, args.3, args.4); let p = pure.eval_number(args.0, args.1, args.2, args.3, args.4); match (l, p) { - (Some(l), Some(p)) => assert!((l - p).abs() < 1e-9 || (l.is_nan() && p.is_nan()), "{src} @ {time}: {l} vs {p}"), + (Some(l), Some(p)) => assert!(l == p || (l - p).abs() < 1e-9 || (l.is_nan() && p.is_nan()), "{src} @ {time}: {l} vs {p}"), _ => assert_eq!(l, p, "{src} @ {time}"), } } } } + + #[test] + fn pure_formats_numbers_like_lua() { + let nodes = HashMap::new(); + let (lua, pure) = (ExprEngine::new(), pure::ExprEngine::new()); + for src in [ + "0.1 + 0.2", "3.0", "time", "1e15", "2^53", "1e100", "0.00001", "1/3", "-0.0", "7 // 2", "100 * 1.0", + "tostring(true)", "tostring(nil)", "Text(nil)", "Text(time)", "123456789.123456789", + ] { + let l = lua.eval_string(src, 2.0, &HashMap::new(), &HashMap::new(), &nodes); + let p = pure.eval_string(src, 2.0, &HashMap::new(), &HashMap::new(), &nodes); + assert_eq!(l, p, "{src}"); + } + } } diff --git a/crates/web/index.html b/crates/web/index.html index 3a441f361e90e676c9cc16714ef09efa3e604fd3..b50ea8df9f3bdddb197c3aa23376acf464db41b7 100644 --- a/crates/web/index.html +++ b/crates/web/index.html @@ -189,18 +189,25 @@ function tick(now) { $('scrub').value = frame; } if (dirty || frame !== lastDrawn) { + let ms; try { - evalMs = app.render(frame); + ms = app.render(frame); } catch (e) { broken = true; fail(`Render failed: ${e.message ?? e}. Reload the page; details are in the console.`); return; } - if (lastTick) fps += ((1000 / (now - lastTick)) - fps) * 0.15; - lastTick = now; - lastDrawn = frame; dirty = false; - const bad = app.unsupported(); - $('notes').dataset.unsupported = bad.join(', '); + const gpuError = app.gpu_error(); + if (gpuError) fail(`GPU error: ${gpuError}`); + // `undefined`: the surface was not ready; stay dirty and try again next frame. + if (ms !== undefined) { + evalMs = ms; + if (lastTick) fps += ((1000 / (now - lastTick)) - fps) * 0.15; + lastTick = now; + lastDrawn = frame; dirty = false; + const bad = app.unsupported(); + $('notes').dataset.unsupported = bad.join(', '); + } } else if (!playing) { lastTick = 0; } @@ -265,9 +272,10 @@ async function ingest(files) { if (!app) return; const comps = files.filter(({ path }) => /\.comp$/i.test(path)); if (comps.length) { app.clear_files(); sources.clear(); } + let dropped = 0; for (const { path, file } of files) { if (!MEDIA_EXT.test(path) || file.size > MAX_FILE_BYTES) continue; - app.add_file(path, new Uint8Array(await file.arrayBuffer())); + if (!app.add_file(path, new Uint8Array(await file.arrayBuffer()))) dropped++; } if (comps.length) { comps.sort((a, b) => a.path.localeCompare(b.path)); @@ -280,6 +288,7 @@ async function ingest(files) { refreshGraph(); dirty = true; } + if (dropped) fail(`${dropped} file(s) skipped: dropped media is past the 512 MB memory limit.`); } boot(); diff --git a/crates/web/src/lib.rs b/crates/web/src/lib.rs index 36058d7836c06400a31e0000354ebf03888d63fa..dfce58fe23fca09731efdf6789a5ef76226e7b59 100644 --- a/crates/web/src/lib.rs +++ b/crates/web/src/lib.rs @@ -7,6 +7,7 @@ use engine::{DisplaySettings, Engine}; use model::{Comp, NodeId}; use serde_json::json; use std::collections::HashSet; +use std::sync::{Arc, Mutex}; use wasm_bindgen::prelude::*; const DEMO_COMP: &str = include_str!("../demo.comp"); @@ -20,7 +21,9 @@ struct Viewer { pub struct Fission { engine: Engine, surface: wgpu::Surface<'static>, - surface_format: wgpu::TextureFormat, + config: wgpu::SurfaceConfiguration, + /// The latest GPU error the device raised outside any error scope, until [`Self::gpu_error`] reads it. + gpu_error: Arc>>, present: wgpu::RenderPipeline, sampler: wgpu::Sampler, viewer: Option, @@ -60,12 +63,31 @@ impl Fission { .await .map_err(js_err)?; - let surface_format = surface - .get_capabilities(&adapter) - .formats - .into_iter() - .find(|f| !f.is_srgb()) - .unwrap_or(wgpu::TextureFormat::Bgra8Unorm); + let gpu_error = Arc::new(Mutex::new(None)); + let slot = Arc::clone(&gpu_error); + device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| { + console_error(&format!("GPU error: {e}")); + *slot.lock().unwrap() = Some(e.to_string()); + })); + let slot = Arc::clone(&gpu_error); + device.set_device_lost_callback(move |reason, message| { + console_error(&format!("GPU device lost ({reason:?}): {message}")); + *slot.lock().unwrap() = Some(format!("The GPU device was lost ({reason:?}): {message}")); + }); + + let caps = surface.get_capabilities(&adapter); + let surface_format = caps.formats.iter().copied().find(|f| !f.is_srgb()).unwrap_or(wgpu::TextureFormat::Bgra8Unorm); + let config = wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + format: surface_format, + color_space: wgpu::SurfaceColorSpace::Auto, + width: 1, + height: 1, + present_mode: wgpu::PresentMode::AutoVsync, + desired_maximum_frame_latency: 2, + alpha_mode: caps.alpha_modes.first().copied().unwrap_or(wgpu::CompositeAlphaMode::Auto), + view_formats: vec![], + }; let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("present"), source: wgpu::ShaderSource::Wgsl(include_str!("present.wgsl").into()), @@ -83,7 +105,7 @@ impl Fission { module: &shader, entry_point: Some("fragment"), compilation_options: Default::default(), - targets: &[Some(surface_format.into())], + targets: &[Some(config.format.into())], }), primitive: Default::default(), depth_stencil: None, @@ -100,7 +122,8 @@ impl Fission { Ok(Fission { engine: Engine::new(device, queue), surface, - surface_format, + config, + gpu_error, present, sampler, viewer: None, @@ -115,9 +138,11 @@ impl Fission { } /// Registers a project file (a dropped folder's relative path) that `Loader` clips resolve against. - pub fn add_file(&mut self, path: &str, bytes: &[u8]) { - MediaCache::insert_virtual_bytes(path, bytes); + /// `false` when the files held would pass the memory cap. + pub fn add_file(&mut self, path: &str, bytes: &[u8]) -> bool { + let added = MediaCache::insert_virtual_bytes(path, bytes); self.engine.bust_all_caches(); + added } pub fn clear_files(&mut self) { @@ -174,21 +199,32 @@ impl Fission { Ok(()) } - /// Evaluates the selected node at `frame` into the canvas and returns the CPU-side milliseconds. - pub fn render(&mut self, frame: f64) -> Result { + /// Evaluates the selected node at `frame` into the canvas and returns the CPU-side milliseconds, + /// or `undefined` when the surface could not take the frame and the caller should retry. + pub fn render(&mut self, frame: f64) -> Result, JsError> { let (comp, target) = self.comp.as_ref().zip(self.target).ok_or_else(|| JsError::new("no comp loaded"))?; // Cached by the engine, so `render_into_viewer` below reuses it; the size can change with media or time. let (tex, _) = self.engine.evaluate(comp, target, frame); - if self.viewer.as_ref().is_none_or(|v| [v.texture.width(), v.texture.height()] != tex.canvas_size) { - self.viewer = Some(make_viewer(self.engine.device(), &self.surface, self.surface_format, &self.present, &self.sampler, tex.canvas_size)); + let size = fit_texture(tex.canvas_size, self.engine.device().limits().max_texture_dimension_2d); + if self.viewer.as_ref().is_none_or(|v| [v.texture.width(), v.texture.height()] != size) { + [self.config.width, self.config.height] = size; + self.surface.configure(self.engine.device(), &self.config); + self.viewer = Some(make_viewer(self.engine.device(), &self.present, &self.sampler, size)); } let viewer = self.viewer.as_ref().expect("viewer sized above"); let stats = self.engine.render_into_viewer(comp, target, frame, &viewer.texture, DisplaySettings::default()); self.unsupported = stats.unsupported_nodes; - let frame_tex = match self.surface.get_current_texture() { - wgpu::CurrentSurfaceTexture::Success(t) | wgpu::CurrentSurfaceTexture::Suboptimal(t) => t, - _ => return Ok(stats.eval_ms), + let (frame_tex, suboptimal) = match self.surface.get_current_texture() { + wgpu::CurrentSurfaceTexture::Success(t) => (t, false), + wgpu::CurrentSurfaceTexture::Suboptimal(t) => (t, true), + wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => { + self.surface.configure(self.engine.device(), &self.config); + return Ok(None); + } + wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded | wgpu::CurrentSurfaceTexture::Validation => { + return Ok(None); + } }; let device = self.engine.device(); let mut encoder = device.create_command_encoder(&Default::default()); @@ -209,7 +245,15 @@ impl Fission { } self.engine.queue().submit(Some(encoder.finish())); self.engine.queue().present(frame_tex); - Ok(stats.eval_ms) + if suboptimal { + self.surface.configure(self.engine.device(), &self.config); + } + Ok(Some(stats.eval_ms)) + } + + /// Takes the latest GPU error or device loss, which would otherwise only show as a black canvas. + pub fn gpu_error(&self) -> Option { + self.gpu_error.lock().unwrap().take() } /// Kinds the last rendered frame could not evaluate. @@ -218,29 +262,25 @@ impl Fission { } } -/// Sizes the canvas and the intermediate viewer texture to the node's logical output. +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(js_namespace = console, js_name = error)] + fn console_error(message: &str); +} + +/// `size` shrunk, keeping its aspect, until both sides fit `max`; never below one pixel. +fn fit_texture([width, height]: [u32; 2], max: u32) -> [u32; 2] { + let scale = (f64::from(max) / f64::from(width.max(height).max(1))).min(1.0); + [width, height].map(|side| ((f64::from(side) * scale).round() as u32).clamp(1, max.max(1))) +} + +/// The intermediate viewer texture, sized to the (already fitted) output. fn make_viewer( device: &wgpu::Device, - surface: &wgpu::Surface<'static>, - format: wgpu::TextureFormat, present: &wgpu::RenderPipeline, sampler: &wgpu::Sampler, [width, height]: [u32; 2], ) -> Viewer { - surface.configure( - device, - &wgpu::SurfaceConfiguration { - usage: wgpu::TextureUsages::RENDER_ATTACHMENT, - format, - color_space: wgpu::SurfaceColorSpace::Auto, - width, - height, - present_mode: wgpu::PresentMode::AutoVsync, - desired_maximum_frame_latency: 2, - alpha_mode: wgpu::CompositeAlphaMode::Opaque, - view_formats: vec![], - }, - ); let texture = device.create_texture(&wgpu::TextureDescriptor { label: Some("viewer"), size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },