From fa632a6ebe2e37cf35a691f7d9f8f4518a56ad94 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Wed, 21 Oct 2026 10:15:50 +0200 Subject: [PATCH 01/38] Offset all selected keyframes when a value is edited on one of them (#1963) --- crates/engine/src/commands/prop.rs | 17 ++++++- crates/engine/src/lib.rs | 2 + crates/engine/src/tests_set_selected_keys.rs | 53 ++++++++++++++++++++ 3 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/tests_set_selected_keys.rs diff --git a/crates/engine/src/commands/prop.rs b/crates/engine/src/commands/prop.rs index 3af877d34..35718197b 100644 --- a/crates/engine/src/commands/prop.rs +++ b/crates/engine/src/commands/prop.rs @@ -443,6 +443,7 @@ fn set(s: &mut Session, p: &Value) -> Result { } let v = p.get("value").ok_or_else(|| bad("prop.set", "missing `value`"))?.clone(); let at = snapped_key_time(s, cid, lid, p, "prop.set")?; + let selected: Vec = s.state.selected_keys.iter().filter(|k| k.layer == lid && k.prop == uid).map(|k| k.time).collect(); let out = with_prop(s, "Change Property", merge_p(p), cid, lid, uid, |pr, lt| { let cur = pr.value_at(lt); let mut nv = cur.coerce_json(&v).ok_or_else(|| bad("prop.set", format!("can't use {v} for a {} property", cur.kind_name())))?; @@ -452,7 +453,21 @@ fn set(s: &mut Session, p: &Value) -> Result { { nv = effectcraft_keyframe::Value::Scalar(x.clamp(min, max)); } - pr.set_value_at(at.unwrap_or(lt), nv.clone()); + let target = at.unwrap_or(lt); + // After Effects: editing the value with the CTI on one of several selected keys moves all + // the selected keys by the same change; between keys it only adds a key. + if selected.len() > 1 && selected.contains(&target) && key_at(&pr.keys, target).is_some() && nv.interpolates() { + let delta: Vec = nv.components().iter().zip(pr.value_at(target).components()).map(|(n, o)| n - o).collect(); + let range = if let effectcraft_project::ParamUi::Slider { min, max, .. } = pr.ui { Some((min, max)) } else { None }; + for k in pr.keys.iter_mut().filter(|k| k.time != target && selected.contains(&k.time)) { + let moved: Vec = k.value.components().iter().zip(&delta).map(|(c, d)| c + d).collect(); + k.value = k.value.with_components(&moved); + if let (Some((min, max)), effectcraft_keyframe::Value::Scalar(x)) = (range, &k.value) { + k.value = effectcraft_keyframe::Value::Scalar(x.clamp(min, max)); + } + } + } + pr.set_value_at(target, nv.clone()); Ok(nv.to_json()) })?; if p.get("timeBase").is_none() { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index cdfc7468e..f3dc76fc4 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1294,6 +1294,8 @@ mod tests_rig3d; #[cfg(test)] mod tests_sequence; #[cfg(test)] +mod tests_set_selected_keys; +#[cfg(test)] mod tests_settings; #[cfg(test)] mod tests_shortcut_cmds; diff --git a/crates/engine/src/tests_set_selected_keys.rs b/crates/engine/src/tests_set_selected_keys.rs new file mode 100644 index 000000000..5747e7fa2 --- /dev/null +++ b/crates/engine/src/tests_set_selected_keys.rs @@ -0,0 +1,53 @@ +//! `prop.set` with the CTI on one of several selected keys moves all the selected keys by the same change. + +use effectcraft_project::LayerId; +use serde_json::json; + +use crate::{KeyRef, Session}; + +fn setup() -> (Session, u64, u64) { + let mut s = Session::default(); + s.execute_checked("comp.new", json!({"width": 64, "height": 64, "frameRate": 30, "duration": 4})).unwrap(); + let layer = s.execute_checked("layer.newSolid", json!({"name": "Box", "color": "#fff"})).unwrap()["layer"].as_u64().unwrap(); + for t in 0..3 { + s.execute_checked("prop.addKey", json!({"layer": layer, "path": "transform/opacity", "time": t, "value": t * 25})).unwrap(); + } + let prop = s.active_comp().unwrap().layer(LayerId(layer)).unwrap().props.prop("transform/opacity").unwrap().uid; + (s, layer, prop) +} + +fn values(s: &Session, layer: u64, prop: u64) -> Vec { + s.active_comp().unwrap().layer(LayerId(layer)).unwrap().props.find(prop).unwrap().keys.iter().map(|k| k.value.as_f64()).collect() +} + +fn select_all(s: &mut Session, layer: u64, prop: u64) { + let keys = s.active_comp().unwrap().layer(LayerId(layer)).unwrap().props.find(prop).unwrap().keys.iter().map(|k| k.time).collect::>(); + s.state.selected_keys = keys.into_iter().map(|time| KeyRef { layer: LayerId(layer), prop, time }).collect(); +} + +#[test] +fn value_edit_on_a_selected_key_offsets_all_selected_keys() { + let (mut s, layer, prop) = setup(); + select_all(&mut s, layer, prop); + s.execute_checked("time.set", json!({"time": 1.0})).unwrap(); + s.execute_checked("prop.set", json!({"layer": layer, "path": "transform/opacity", "value": 40})).unwrap(); + assert_eq!(values(&s, layer, prop), vec![15.0, 40.0, 65.0]); +} + +#[test] +fn offset_selected_keys_stay_in_the_slider_range() { + let (mut s, layer, prop) = setup(); + select_all(&mut s, layer, prop); + s.execute_checked("time.set", json!({"time": 1.0})).unwrap(); + s.execute_checked("prop.set", json!({"layer": layer, "path": "transform/opacity", "value": 90})).unwrap(); + assert_eq!(values(&s, layer, prop), vec![65.0, 90.0, 100.0]); +} + +#[test] +fn value_edit_between_keys_only_adds_a_key() { + let (mut s, layer, prop) = setup(); + select_all(&mut s, layer, prop); + s.execute_checked("time.set", json!({"time": 0.5})).unwrap(); + s.execute_checked("prop.set", json!({"layer": layer, "path": "transform/opacity", "value": 40})).unwrap(); + assert_eq!(values(&s, layer, prop), vec![0.0, 40.0, 25.0, 50.0]); +} From 150e6a4e747402a472cdc5d5bfa4ef91638b6609 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:38:57 +0100 Subject: [PATCH 02/38] Offset selected keys only when the playhead is on the edited key (#1963) --- crates/engine/src/cmd/prop.rs | 4 ++-- crates/engine/src/tests/set_selected_keys.rs | 9 +++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/prop.rs b/crates/engine/src/cmd/prop.rs index c5e7b500b..501860840 100644 --- a/crates/engine/src/cmd/prop.rs +++ b/crates/engine/src/cmd/prop.rs @@ -513,8 +513,8 @@ fn set(s: &mut Session, p: &Value) -> Result { } let target = at.unwrap_or(lt); // After Effects: editing the value with the CTI on one of several selected keys moves all - // the selected keys by the same change; between keys it only adds a key. - if selected.len() > 1 && selected.contains(&target) && key_at(&pr.keys, target).is_some() && nv.interpolates() { + // the selected keys by the same change; between keys, or at an explicit other time, it only edits that key. + if selected.len() > 1 && target == lt && selected.contains(&target) && key_at(&pr.keys, target).is_some() && nv.interpolates() { let delta: Vec = nv.components().iter().zip(pr.value_at(target).components()).map(|(n, o)| n - o).collect(); let range = if let effectcraft_project::ParamUi::Slider { min, max, .. } = pr.ui { Some((min, max)) } else { None }; for k in pr.keys.iter_mut().filter(|k| k.time != target && selected.contains(&k.time)) { diff --git a/crates/engine/src/tests/set_selected_keys.rs b/crates/engine/src/tests/set_selected_keys.rs index 5747e7fa2..226ed6ba0 100644 --- a/crates/engine/src/tests/set_selected_keys.rs +++ b/crates/engine/src/tests/set_selected_keys.rs @@ -51,3 +51,12 @@ fn value_edit_between_keys_only_adds_a_key() { s.execute_checked("prop.set", json!({"layer": layer, "path": "transform/opacity", "value": 40})).unwrap(); assert_eq!(values(&s, layer, prop), vec![0.0, 40.0, 25.0, 50.0]); } + +#[test] +fn explicit_time_off_the_playhead_only_edits_that_key() { + let (mut s, layer, prop) = setup(); + select_all(&mut s, layer, prop); + s.execute_checked("time.set", json!({"time": 0.5})).unwrap(); + s.execute_checked("prop.set", json!({"layer": layer, "path": "transform/opacity", "time": 1.0, "value": 40})).unwrap(); + assert_eq!(values(&s, layer, prop), vec![0.0, 40.0, 50.0]); +} From a2e24096087f62c54ebca27af2c0470f04161033 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 22:44:46 -0800 Subject: [PATCH 03/38] Import: read PhotoCraft composites and saved layer pixels --- Cargo.lock | 67 ++++- Cargo.toml | 3 +- README.md | 3 +- apps/effectcraft-web/src/files.rs | 7 +- crates/engine/Cargo.toml | 4 + crates/engine/src/cmd/file.rs | 54 +++- crates/engine/src/footage/media_browser.rs | 2 +- crates/engine/src/footage/sequence.rs | 2 +- crates/engine/src/interchange.rs | 1 + .../engine/src/interchange/pcraft_import.rs | 160 ++++++++++++ crates/engine/src/services.rs | 23 +- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/import_photocraft.rs | 237 ++++++++++++++++++ crates/media/Cargo.toml | 1 + crates/media/src/convert.rs | 15 ++ crates/media/src/layered.rs | 8 +- crates/media/src/lib.rs | 26 +- crates/media/src/pcraft.rs | 170 +++++++++++++ crates/ui-egui/src/menus/frontend.rs | 2 +- crates/ui-egui/src/menus/tests.rs | 5 +- crates/ui-egui/src/panels/forms.rs | 29 +++ crates/ui-egui/src/prefs_live.rs | 2 +- docs/photocraft-import.md | 25 ++ 23 files changed, 829 insertions(+), 18 deletions(-) create mode 100644 crates/engine/src/interchange/pcraft_import.rs create mode 100644 crates/engine/src/tests/import_photocraft.rs create mode 100644 crates/media/src/pcraft.rs create mode 100644 docs/photocraft-import.md diff --git a/Cargo.lock b/Cargo.lock index c43ba9d9c..7742a2c0d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -489,6 +489,19 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "blake3" +version = "1.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "cpufeatures 0.3.1", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -959,6 +972,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + [[package]] name = "core-foundation" version = "0.9.4" @@ -1089,6 +1108,22 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-doc" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6ae033e6c18bde9cd6f18e505c0556667ba2226a#6ae033e6c18bde9cd6f18e505c0556667ba2226a" +dependencies = [ + "blake3", + "craft-ecproj-format", + "craft-pcraft-format", + "craft-vectorcraft-format", + "flate2", + "ruzstd", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-docpath" version = "0.1.0" @@ -1097,7 +1132,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13af [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ca1b5e2edb8568335c6c14f390307bd5beae8238#ca1b5e2edb8568335c6c14f390307bd5beae8238" +source = "git+https://github.com/storytold/craft-libs?rev=6ae033e6c18bde9cd6f18e505c0556667ba2226a#6ae033e6c18bde9cd6f18e505c0556667ba2226a" dependencies = [ "serde", "serde_json", @@ -1132,6 +1167,16 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-pcraft-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6ae033e6c18bde9cd6f18e505c0556667ba2226a#6ae033e6c18bde9cd6f18e505c0556667ba2226a" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -1199,6 +1244,17 @@ dependencies = [ "zip 9.1.3", ] +[[package]] +name = "craft-vectorcraft-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6ae033e6c18bde9cd6f18e505c0556667ba2226a#6ae033e6c18bde9cd6f18e505c0556667ba2226a" +dependencies = [ + "flate2", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -1506,6 +1562,7 @@ name = "effectcraft-engine" version = "0.21.0" dependencies = [ "chrono", + "craft-doc", "craft-docpath", "effectcraft-color", "effectcraft-effects", @@ -1513,6 +1570,7 @@ dependencies = [ "effectcraft-interchange", "effectcraft-keyframe", "effectcraft-lottie", + "effectcraft-media", "effectcraft-model", "effectcraft-path", "effectcraft-pdf", @@ -1701,6 +1759,7 @@ dependencies = [ name = "effectcraft-media" version = "0.21.0" dependencies = [ + "craft-doc", "craft-docpath", "effectcraft-color", "effectcraft-model", @@ -5333,6 +5392,12 @@ dependencies = [ "wait-timeout", ] +[[package]] +name = "ruzstd" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69e4ce4a039f42bf25920b95667e4d789e98749ab11bbb8d2c2936f788421bb5" + [[package]] name = "ryu-js" version = "1.0.3" diff --git a/Cargo.toml b/Cargo.toml index f5f84775f..6c4a562c1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,10 +11,11 @@ rust-version = "1.95" repository = "https://github.com/storytold/effectcraft" [workspace.dependencies] +craft-doc = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6ae033e6c18bde9cd6f18e505c0556667ba2226a" } craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", version = "=0.1.0", default-features = false, features = ["read"] } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } -craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ca1b5e2edb8568335c6c14f390307bd5beae8238" } +craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6ae033e6c18bde9cd6f18e505c0556667ba2226a" } # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } # internal diff --git a/README.md b/README.md index 81b5a0ba5..585f29268 100644 --- a/README.md +++ b/README.md @@ -221,7 +221,8 @@ cargo run --release -p effectcraft-cli -- render --out intro.mp4 # render the cargo xtask web --serve 8765 # the browser build on http://127.0.0.1:8765/ (docs/web.md) ``` -New to it? [docs/footage.md](docs/footage.md) covers importing footage and image sequences and +New to it? [docs/photocraft-import.md](docs/photocraft-import.md) describes PhotoCraft composites and saved layer pixels. +[docs/footage.md](docs/footage.md) covers importing footage and image sequences and Interpret Footage. To work on it: `cargo test --workspace`, and `cargo xtask ci` before every commit (format, lints, diff --git a/apps/effectcraft-web/src/files.rs b/apps/effectcraft-web/src/files.rs index f6aac5aa4..b1647c15d 100644 --- a/apps/effectcraft-web/src/files.rs +++ b/apps/effectcraft-web/src/files.rs @@ -114,8 +114,13 @@ pub struct WebServices; impl Services for WebServices { fn read_file(&self, path: &str) -> std::io::Result> { get(path) - .map(|d| d.to_vec()) .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, format!("{path}: open it with File ▸ Open (or drop it on the page)"))) + .and_then(|data| { + if (data.starts_with(b"PK\x03\x04") || path.to_ascii_lowercase().ends_with(".pcraft")) && data.len() as u64 > 512 << 20 { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "ZIP/PhotoCraft bundle exceeds the 512 MiB input limit")); + } + Ok(data.to_vec()) + }) } fn write_file(&self, path: &str, data: &[u8]) -> std::io::Result<()> { put(path, data.into()); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 826346987..10e4140c4 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -10,6 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] +craft-doc = { workspace = true } craft-docpath = { workspace = true } effectcraft-time = { workspace = true } effectcraft-geom = { workspace = true } @@ -40,6 +41,9 @@ image = { workspace = true } web-time = { workspace = true } exr = { workspace = true } +[dev-dependencies] +effectcraft-media = { workspace = true } + # Native file identity and SAM 2 inference; browsers keep the built-in engines. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] same-file = { workspace = true } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index e1f58a1cc..61ee1d8ae 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -321,6 +321,18 @@ impl Prober { let importer = self.importer.as_ref().ok_or_else(|| fail("media import is not available in this build".into()))?; let mut f = crate::sequence::probe(importer.as_ref(), src, self.sequence_rate).map_err(fail)?; let mut warning = None; + if f.codec == "PhotoCraft" { + let bytes = self.services.read_file(path).map_err(|e| fail(e.to_string()))?; + let outline = craft_doc::outline(&bytes, &craft_doc::Limits::default()).map_err(|e| fail(e.to_string()))?; + if let Some(canvas) = outline.canvas + && (canvas.width, canvas.height) != (f.width, f.height) + { + warning = Some(format!( + "{name}: imported the saved {} × {} composite of a {} × {} PhotoCraft canvas", + f.width, f.height, canvas.width, canvas.height + )); + } + } // Settings ▸ Import ▸ Report Missing Frames (numbered sequences). if f.kind == FootageKind::Sequence && !f.alphabetical @@ -416,7 +428,22 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result { if let Some(retain) = retain { let mut rest = vec![]; for path in paths { + if path.to_ascii_lowercase().ends_with(".pcraft") && s.services.stamp(&path).is_some_and(|(bytes, _)| bytes > 512 << 20) { + errors.push(format!("{path}: PhotoCraft bundle exceeds the 512 MiB input limit")); + continue; + } let bytes = match s.services.read_file(&path) { + Ok(b) if path.to_ascii_lowercase().ends_with(".pcraft") || craft_doc::sniff(&b) == Some(craft_doc::Kind::PhotoCraft) => { + match import_pcraft_comp(s, &path, &b, retain) { + Ok((comp, made, warnings)) => { + comps.push(comp); + items.extend(made); + errors.extend(warnings); + } + Err(e) => errors.push(format!("{path}: {e}")), + } + continue; + } Ok(b) if effectcraft_psd::is_psd(&b) => b, Ok(b) if effectcraft_pdf::sniff(&b).is_some() && !path.to_ascii_lowercase().ends_with(".svg") => { // PDF / Illustrator / EPS: one layer per file layer. @@ -429,6 +456,10 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result { } continue; } + Err(e) if e.kind() == std::io::ErrorKind::InvalidData || path.to_ascii_lowercase().ends_with(".pcraft") => { + errors.push(format!("{path}: {e}")); + continue; + } _ => { rest.push(path); continue; @@ -545,7 +576,26 @@ fn add_footage(s: &mut Session, pending: PendingImport, probed: Vec bool { let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); - matches!(ext.as_str(), "png" | "gif" | "webp" | "psd" | "psb" | "exr" | "svg" | "jpg" | "jpeg" | "ai" | "pdf" | "eps") || codec.eq_ignore_ascii_case("PSD") + matches!(ext.as_str(), "png" | "gif" | "webp" | "psd" | "psb" | "pcraft" | "exr" | "svg" | "jpg" | "jpeg" | "ai" | "pdf" | "eps") + || codec.eq_ignore_ascii_case("PSD") + || codec == "PhotoCraft" +} + +fn import_pcraft_comp(s: &mut Session, path: &str, bytes: &[u8], retain: bool) -> Result<(u64, Vec, Vec)> { + use crate::interchange::pcraft_import; + let doc = pcraft_import::read(bytes).map_err(EngineError::Other)?; + let name = std::path::Path::new(path).file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "PhotoCraft".into()); + let rate = effectcraft_time::FrameRate::FPS_29_97; + let secs = if s.prefs.import.still_footage == "seconds" { s.prefs.import.still_seconds } else { 10.0 }; + let duration = rate.snap_nearest(effectcraft_time::Tick::from_seconds_f64(secs)); + let r = s.edit("Import", None, |project, state| { + let r = pcraft_import::import(project, &doc, path, &name, retain, rate, duration); + state.project_selection = vec![r.comp]; + Ok(r) + })?; + let mut items = vec![r.folder.0]; + items.extend(r.items.iter().map(|id| id.0)); + Ok((r.comp.0, items, r.warnings)) } /// A Photoshop layer by index or name (pixel layers only). @@ -785,7 +835,7 @@ pub fn specs() -> Vec { "File...", ["File", "Import"], Some("Cmd+I"), - "{paths: [string] (files or folders), sequence?: bool (the Sequence checkbox: true imports numbered stills of one run as one image sequence, one picked file bringing its whole run and several picked files that range; default false: picked or dropped files import as stills, as in After Effects; folders' runs import as sequences; false imports stills and a folder's files individually), alphabetical?: bool (Force Alphabetical Order: every image of that type in the folder, by name), frameRate?: fps (image sequences; default Settings ▸ Import ▸ Sequence Footage), importAs?: footage|composition|compositionLayerSizes (Photoshop, PDF, Illustrator and EPS files), layer?: name|index (footage of one Photoshop layer), page?: number from 1 (PDF / Illustrator page), drag?: bool (dropped files: Settings ▸ Import ▸ Default Drag Import As; files import as stills unless sequence), addToComp?: bool (also add them to the active comp, at time?, index?, position? as in layer.addItem), newComp?: bool (make one new composition of the footage and solids imported, as file.newCompFromSelection with single; a layered file imported as a composition is that composition and gets no other; takes precedence over addToComp), background?: bool (probe the files in a background job, jobs.list / jobs.wait; returns {job})}", + "{paths: [string] (files or folders), sequence?: bool (the Sequence checkbox: true imports numbered stills of one run as one image sequence, one picked file bringing its whole run and several picked files that range; default false: picked or dropped files import as stills, as in After Effects; folders' runs import as sequences; false imports stills and a folder's files individually), alphabetical?: bool (Force Alphabetical Order: every image of that type in the folder, by name), frameRate?: fps (image sequences; default Settings ▸ Import ▸ Sequence Footage), importAs?: footage|composition|compositionLayerSizes (Photoshop, PhotoCraft, PDF, Illustrator and EPS files), layer?: name|index (footage of one Photoshop layer), page?: number from 1 (PDF / Illustrator page), drag?: bool (dropped files: Settings ▸ Import ▸ Default Drag Import As; files import as stills unless sequence), addToComp?: bool (also add them to the active comp, at time?, index?, position? as in layer.addItem), newComp?: bool (make one new composition of the footage and solids imported, as file.newCompFromSelection with single; a layered file imported as a composition is that composition and gets no other; takes precedence over addToComp), background?: bool (probe the files in a background job, jobs.list / jobs.wait; returns {job})}", always, import_cmd ), diff --git a/crates/engine/src/footage/media_browser.rs b/crates/engine/src/footage/media_browser.rs index 2c40fcf20..d21efd439 100644 --- a/crates/engine/src/footage/media_browser.rs +++ b/crates/engine/src/footage/media_browser.rs @@ -197,7 +197,7 @@ fn sort_entries(entries: &mut [Entry]) { entries.sort_by_cached_key(|e| (!e.is_dir, e.name.to_lowercase())); } -const IMAGE: &[&str] = &["png", "jpg", "jpeg", "tif", "tiff", "exr", "bmp", "webp", "psd", "psb", "svg", "tga", "dpx", "cin", "hdr"]; +const IMAGE: &[&str] = &["png", "jpg", "jpeg", "tif", "tiff", "exr", "bmp", "webp", "psd", "psb", "pcraft", "svg", "tga", "dpx", "cin", "hdr"]; const AUDIO: &[&str] = &["wav", "aif", "aiff", "mp3", "m4a", "aac", "flac", "ogg", "opus"]; const DATA: &[&str] = &["json", "csv", "tsv", "mgjson"]; const MODEL: &[&str] = &["gltf", "glb", "obj", "stl", "fbx"]; diff --git a/crates/engine/src/footage/sequence.rs b/crates/engine/src/footage/sequence.rs index fc2dab2b0..ec2547b2a 100644 --- a/crates/engine/src/footage/sequence.rs +++ b/crates/engine/src/footage/sequence.rs @@ -97,7 +97,7 @@ fn extension(path: &str) -> String { /// Stills that can form a sequence (not layered or vector documents, which import as comps). fn sequenceable(path: &str) -> bool { - crate::media_browser::kind_of(path) == Some("image") && !matches!(extension(path).as_str(), "svg" | "psd" | "psb") + crate::media_browser::kind_of(path) == Some("image") && !matches!(extension(path).as_str(), "svg" | "psd" | "psb" | "pcraft") } /// The run a still belongs to: (folder, name prefix, extension); alphabetical runs ignore the diff --git a/crates/engine/src/interchange.rs b/crates/engine/src/interchange.rs index 3b166b83e..a83090159 100644 --- a/crates/engine/src/interchange.rs +++ b/crates/engine/src/interchange.rs @@ -1,5 +1,6 @@ pub(crate) mod keyframe_text; pub(crate) mod keyframe_text_effects; +pub(crate) mod pcraft_import; pub mod psd_import; pub mod vector; pub mod xml_project; diff --git a/crates/engine/src/interchange/pcraft_import.rs b/crates/engine/src/interchange/pcraft_import.rs new file mode 100644 index 000000000..a7b24ff62 --- /dev/null +++ b/crates/engine/src/interchange/pcraft_import.rs @@ -0,0 +1,160 @@ +//! PhotoCraft's layer outline as a composition of lazily decoded, canvas-sized pixel layers. + +use std::sync::Arc; + +use craft_doc::{Layer as InputLayer, Outline}; +use effectcraft_color::{BlendMode, Label}; +use effectcraft_keyframe::Value; +use effectcraft_project::{AlphaMode, Comp, Footage, FootageKind, ItemId, ItemKind, LayerSource, Project, SourceLayer, build}; +use effectcraft_time::{FrameRate, Tick}; + +pub(crate) struct Document { + outline: Outline, + width: u32, + height: u32, +} + +/// Metadata only: source pixels remain media and are decoded when a frame needs them, as PSD +/// footage is. Bound the number of project items before creating their property groups. +pub(crate) fn read(bytes: &[u8]) -> Result { + if bytes.len() as u64 > 512 << 20 { + return Err("PhotoCraft bundle exceeds the 512 MiB input limit".into()); + } + fn count(layers: &[InputLayer], depth: usize, nodes: &mut usize, pixels: &mut usize) -> Result<(), String> { + if depth > 100 { + return Err("PhotoCraft groups exceed 100 levels".into()); + } + for layer in layers { + *nodes += 1; + if *nodes > 4096 { + return Err("PhotoCraft composition import exceeds 4096 layers; import as Footage for the saved composite".into()); + } + if matches!(layer.kind.as_str(), "raster" | "text" | "shape" | "smart") { + *pixels += 1; + } + if !layer.children.is_empty() { + if layer.kind != "group" { + return Err(format!("PhotoCraft {} layer has unsupported nested content", layer.kind)); + } + count(&layer.children, depth + 1, nodes, pixels)?; + } + } + Ok(()) + } + let outline = craft_doc::outline(bytes, &craft_doc::Limits::default()).map_err(|e| e.to_string())?; + let canvas = outline.canvas.as_ref().ok_or("not a PhotoCraft canvas")?; + let (width, height) = (canvas.width, canvas.height); + if width == 0 || height == 0 || width > effectcraft_project::limits::MAX_SIZE || height > effectcraft_project::limits::MAX_SIZE { + return Err(format!("PhotoCraft canvas {width} × {height} is outside the composition size limits")); + } + if u64::from(width) * u64::from(height) > 16 << 20 { + return Err("PhotoCraft layer decoding exceeds 16777216 canvas pixels; import as Footage for the saved composite".into()); + } + if matches!(canvas.mode.as_str(), "Cmyk" | "Lab") { + return Err(format!("PhotoCraft {} layer pixels are not supported; import as Footage for the saved composite", canvas.mode)); + } + let (mut nodes, mut pixels) = (0, 0); + count(&outline.layers, 0, &mut nodes, &mut pixels)?; + if nodes != 0 && pixels == 0 { + return Err("PhotoCraft document has no supported saved pixel layers; import as Footage for the saved composite".into()); + } + Ok(Document { outline, width, height }) +} + +pub(crate) struct Imported { + pub comp: ItemId, + pub folder: ItemId, + pub items: Vec, + pub warnings: Vec, +} + +struct Context<'a> { + doc: &'a Document, + path: &'a str, + folder: ItemId, + rate: FrameRate, + duration: Tick, + next: u32, + items: Vec, + warnings: Vec, +} + +pub(crate) fn import(project: &mut Project, doc: &Document, path: &str, name: &str, retain: bool, rate: FrameRate, duration: Tick) -> Imported { + let folder = project.add_item(&format!("{name} Layers"), Label::Yellow, None, ItemKind::Folder); + let mut ctx = Context { + doc, + path, + folder, + rate, + duration, + next: 0, + items: Vec::new(), + warnings: vec![ + "Layered PhotoCraft import uses saved pixels. Some masks, effects and profiles are unsupported; use Footage for the saved appearance.".into(), + ], + }; + if retain { + ctx.warnings.push("PhotoCraft layer footage uses the document canvas; Retain Layer Sizes keeps those canvas bounds.".into()); + } + let comp = build_comp(project, &mut ctx, name, &doc.outline.layers, None, 0); + Imported { comp, folder, items: ctx.items, warnings: ctx.warnings } +} + +fn build_comp(project: &mut Project, ctx: &mut Context, name: &str, layers: &[InputLayer], parent: Option, depth: usize) -> ItemId { + let mut comp = Comp::new(ctx.doc.width, ctx.doc.height, ctx.rate, ctx.duration); + let id = project.add_item(name, Label::Sandstone, parent, ItemKind::Comp(Arc::new(comp.clone()))); + ctx.items.push(id); + if depth <= 100 { + for input in layers { + let index = ctx.next; + ctx.next = ctx.next.saturating_add(1); + let name = if input.name.is_empty() { format!("Layer {}", index + 1) } else { input.name.clone() }; + let source = if input.kind == "group" { + let folder = ctx.folder; + let sub = build_comp(project, ctx, &name, &input.children, Some(folder), depth + 1); + LayerSource::Comp { item: sub } + } else if matches!(input.kind.as_str(), "raster" | "text" | "shape" | "smart") { + let file = std::path::Path::new(ctx.path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let footage = Footage { + path: ctx.path.into(), + kind: FootageKind::Still, + width: ctx.doc.width, + height: ctx.doc.height, + has_video: true, + alpha: AlphaMode::Straight, + codec: "PhotoCraft".into(), + layer: Some(SourceLayer { index, name: name.clone(), layer_size: false, embedded: None, placed: false }), + ..Default::default() + }; + let item = project.add_item(&format!("{name}/{file}"), Label::Lavender, Some(ctx.folder), ItemKind::Footage(footage)); + ctx.items.push(item); + LayerSource::Footage { item } + } else { + ctx.warnings.push(format!("{name}: PhotoCraft {} content has no supported saved pixels and was skipped", input.kind)); + continue; + }; + let mut layer = build::layer(project, &comp, &name, source, (ctx.doc.width, ctx.doc.height), None); + layer.switches.video = input.visible; + if let Some(opacity) = layer.props.prop_mut("transform/opacity") { + opacity.value = Value::Scalar(f64::from(input.opacity.filter(|v| v.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0)) * 100.0); + } + if let Some(blend) = input.blend.as_deref() { + if input.kind == "group" && (blend.eq_ignore_ascii_case("PassThrough") || blend.eq_ignore_ascii_case("Pass Through")) { + layer.switches.collapse = true; + } else if let Some(mode) = BlendMode::from_name(blend) { + layer.blend_mode = mode; + } else { + ctx.warnings.push(format!("{name}: PhotoCraft blend mode {blend} is not supported; using Normal")); + } + } + comp.layers.push(layer); + } + } + // PhotoCraft stores bottom first; EffectCraft stores the top layer first. Reverse + // after visiting the source so preorder pixel indexes still address the original tree. + comp.layers.reverse(); + if let Some(item) = project.item_mut(id) { + item.kind = ItemKind::Comp(Arc::new(comp)); + } + id +} diff --git a/crates/engine/src/services.rs b/crates/engine/src/services.rs index 2d425a4e6..5f1a86c99 100644 --- a/crates/engine/src/services.rs +++ b/crates/engine/src/services.rs @@ -53,16 +53,35 @@ impl Services for FsServices { /// Refuses what isn't a regular file: a project can name `/dev/zero` or a FIFO, and reading /// those never ends (#2134). fn read_file(&self, path: &str) -> std::io::Result> { - use std::io::Read; + use std::io::{Read, Seek}; let mut file = std::fs::File::open(path)?; let meta = file.metadata()?; if !meta.is_file() { return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{path} is not a file"))); } + // A renamed PhotoCraft bundle must be bounded before allocating its whole input. + // Bound ZIP containers by their signature even when manifest.json is a later entry. + let mut head = [0u8; 4]; + if meta.len() >= 4 { + file.read_exact(&mut head)?; + file.rewind()?; + } + let limited = head == *b"PK\x03\x04" || path.to_ascii_lowercase().ends_with(".pcraft"); + const MAX_BUNDLE: u64 = 512 << 20; + if limited && meta.len() > MAX_BUNDLE { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "ZIP/PhotoCraft bundle exceeds the 512 MiB input limit")); + } let mut bytes = Vec::new(); // A sparse file can claim far more than memory: an error, not an abort. bytes.try_reserve_exact(usize::try_from(meta.len()).unwrap_or(usize::MAX)).map_err(|e| std::io::Error::new(std::io::ErrorKind::OutOfMemory, e))?; - file.read_to_end(&mut bytes)?; + if limited { + file.take(MAX_BUNDLE + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_BUNDLE { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "ZIP/PhotoCraft bundle grew beyond the 512 MiB input limit")); + } + } else { + file.read_to_end(&mut bytes)?; + } Ok(bytes) } fn write_file(&self, path: &str, data: &[u8]) -> std::io::Result<()> { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 013d2f24c..bb06ba978 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -17,6 +17,7 @@ mod fidelity; mod frame_export; mod fuzz_open; mod history; +mod import_photocraft; mod import_project; mod instance3d; mod key_metadata_order; diff --git a/crates/engine/src/tests/import_photocraft.rs b/crates/engine/src/tests/import_photocraft.rs new file mode 100644 index 000000000..1298c346f --- /dev/null +++ b/crates/engine/src/tests/import_photocraft.rs @@ -0,0 +1,237 @@ +//! PhotoCraft bundles written from synthetic manifest data. + +use effectcraft_color::BlendMode; +use effectcraft_project::{ItemId, ItemKind, LayerSource}; +use serde_json::{Value, json}; + +use crate::Session; + +struct Import; + +impl crate::Importer for Import { + fn probe(&self, path: &str) -> Result { + effectcraft_media::probe(path).map_err(|e| e.to_string()) + } +} + +fn surface(color: &str) -> Value { + json!({"format":{"mode":"Rgb","sample":"U8","alpha":true},"default":color,"tiles":[]}) +} + +fn layer(name: &str, visible: bool, opacity: f32, blend: &str, content: Value) -> Value { + json!({"name":name,"visible":visible,"opacity":opacity,"blend":blend,"content":content}) +} + +fn bundle(layers: Value) -> Vec { + bundle_sized(layers, (8, 6)) +} + +fn bundle_sized(layers: Value, size: (u32, u32)) -> Vec { + let manifest = json!({"format_version":1,"generator":"synthetic PhotoCraft fixture", + "document":{"size":{"width":size.0,"height":size.1},"resolution_dpi":72.0,"mode":"Rgb","depth":"U8","layers":layers}, + "thumbnail":null,"composite":"composite/preview.png"}); + let mut png = std::io::Cursor::new(Vec::new()); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(4, 3, image::Rgba([20, 30, 40, 255]))).write_to(&mut png, image::ImageFormat::Png).unwrap(); + effectcraft_lottie::zip::store(&[("manifest.json".into(), serde_json::to_vec(&manifest).unwrap()), ("composite/preview.png".into(), png.into_inner())]) +} + +fn fixture(name: &str, layers: Value) -> String { + fixture_bytes(name, bundle(layers)) +} + +fn fixture_bytes(name: &str, bytes: Vec) -> String { + let dir = std::env::temp_dir().join(format!("effectcraft-pcraft-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(name); + std::fs::write(&path, bytes).unwrap(); + path.to_string_lossy().into_owned() +} + +#[test] +fn photocraft_composite_imports_as_footage() { + let path = fixture("composite.pcraft", json!([])); + let mut s = Session { importer: Some(std::sync::Arc::new(Import)), ..Default::default() }; + let r = s.execute("file.import", json!({"paths":[path]})).unwrap(); + assert!(r["errors"].as_array().unwrap().is_empty(), "{r}"); + let id = ItemId(r["items"][0].as_u64().unwrap()); + let ItemKind::Footage(f) = &s.project.item(id).unwrap().kind else { panic!("not footage") }; + assert_eq!((f.path.as_str(), f.width, f.height, f.codec.as_str()), (path.as_str(), 4, 3, "PhotoCraft")); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains("4 × 3") && w.contains("8 × 6"))), "{r}"); + let image = effectcraft_media::MediaPool::new().frame_at(f, effectcraft_time::Tick::ZERO).unwrap(); + assert_eq!((image.width, image.height), (4, 3)); + assert!((image.data[0][0] - 20.0 / 255.0).abs() < 1e-6); + assert_eq!(crate::media_browser::kind_of("shot_001.pcraft"), Some("image")); + assert!(crate::sequence::sequences(s.services.as_ref(), &["/shot_001.pcraft".into(), "/shot_002.pcraft".into()], false).is_empty()); + assert!(effectcraft_media::is_importable(std::path::Path::new("shot.PCRAFT"))); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn photocraft_composition_keeps_layer_names_visibility_opacity_and_blend() { + let layers = json!([ + layer("Bottom", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("ff0000ff")})), + layer("Hidden", false, 0.25, "Multiply", json!({"kind":"text","cache":surface("00ff0080")})), + layer( + "Group", + true, + 1.0, + "Normal", + json!({"kind":"group","children":[ + layer("Nested", true, 0.5, "Screen", json!({"kind":"shape","cache":surface("0000ffff")})) + ]}) + ) + ]); + let path = fixture("layered.pcraft", layers); + let mut s = Session::default(); + let before = s.project.items.len(); + let r = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); + assert_eq!(r["comps"].as_array().unwrap().len(), 1, "{r}"); + assert!(r["errors"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains("Some masks, effects and profiles are unsupported"))), "{r}"); + let cid = ItemId(r["comps"][0].as_u64().unwrap()); + let c = s.project.comp(cid).unwrap(); + assert_eq!((c.width, c.height), (8, 6)); + let bottom = c.layers.iter().find(|l| l.name == "Bottom").unwrap(); + assert!(matches!(bottom.source, LayerSource::Footage { .. })); + let hidden = c.layers.iter().find(|l| l.name == "Hidden").unwrap(); + assert!(!hidden.switches.video); + assert_eq!(hidden.blend_mode, BlendMode::Multiply); + assert_eq!(hidden.props.prop("transform/opacity").unwrap().value.as_f64(), 25.0); + let group = c.layers.iter().find(|l| l.name == "Group").unwrap(); + let LayerSource::Comp { item } = group.source else { panic!("group is not a precomposition") }; + let nested = &s.project.comp(item).unwrap().layers[0]; + assert_eq!(nested.name, "Nested"); + assert_eq!(nested.blend_mode, BlendMode::Screen); + assert_eq!(nested.props.prop("transform/opacity").unwrap().value.as_f64(), 50.0); + let LayerSource::Footage { item } = nested.source else { panic!("nested layer is not footage") }; + let ItemKind::Footage(f) = &s.project.item(item).unwrap().kind else { panic!("not footage") }; + assert_eq!(f.layer.as_ref().unwrap().index, 3); + let image = effectcraft_media::MediaPool::new().frame_at(f, effectcraft_time::Tick::ZERO).unwrap(); + assert_eq!((image.width, image.height), (8, 6)); + assert_eq!(image.data[0], [0.0, 0.0, 1.0, 1.0]); + let saved = s.project.to_json(); + let limits = craft_doc::Limits::default(); + assert_eq!(craft_doc::info(saved.as_bytes(), &limits).unwrap().kind, craft_doc::Kind::EffectCraft); + let written = craft_doc::outline(saved.as_bytes(), &limits).unwrap(); + assert!(written.pages.iter().any(|p| p.layers.iter().any(|l| l.name == "Hidden"))); + assert!(craft_doc::renditions(saved.as_bytes(), &limits).unwrap().is_empty()); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.project.items.len(), before); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn photocraft_masks_and_sample_depths_decode_through_the_media_pool() { + use effectcraft_project::{AlphaMode, Footage, SourceLayer}; + for (sample, color, expected) in [ + ("U8", "ff0000ff", 1.0), + ("U16", "ffff00000000ffff", 1.0), + ("F32", "0000803e00000000000000000000803f", 0.5370987), + ("F32", "0000c07f00000000000000000000803f", 0.0), + ] { + let content = json!({"kind":"raster","surface":{"format":{"mode":"Rgb","sample":sample,"alpha":true},"default":color,"tiles":[]}}); + let mut raster = layer("Masked", true, 1.0, "Normal", content); + raster["mask"] = json!({"enabled":true,"density":0.5,"feather":if sample == "U16" { 0.75 } else { 0.0 }, + "surface":{"format":{"mode":"Grayscale","sample":"U8","alpha":false},"default":"80","tiles":[]}}); + let path = fixture(&format!("masked-{sample}.pcraft"), json!([raster])); + let mut f = Footage { + path: path.clone(), + width: 8, + height: 6, + has_video: true, + alpha: AlphaMode::Straight, + layer: Some(SourceLayer { index: 0, name: "Masked".into(), layer_size: false, embedded: None, placed: false }), + ..Default::default() + }; + let pool = effectcraft_media::MediaPool::new(); + let image = pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap(); + let coverage = 1.0 - 0.5 * (1.0 - 128.0 / 255.0); + assert!((image.data[0][0] - expected * coverage).abs() < 1e-5, "{sample}: {:?}", image.data[0]); + assert!((image.data[0][3] - coverage).abs() < 1e-6); + f.alpha = AlphaMode::Premultiplied; + let image = pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap(); + assert!((image.data[0][0] - expected * coverage).abs() < 1e-5, "masked premultiplied {sample}: {:?}", image.data[0]); + assert!((image.data[0][3] - coverage).abs() < 1e-6); + f.alpha = AlphaMode::Ignore; + let image = pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap(); + assert!((image.data[0][0] - expected).abs() < 1e-5); + assert_eq!(image.data[0][3], 1.0, "Ignore Alpha includes the source mask"); + std::fs::remove_file(path).unwrap(); + } +} + +#[test] +fn photocraft_overlapping_layers_render_in_source_stack_order() { + let path = fixture( + "stack-order.pcraft", + json!([ + layer("Bottom", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("ff0000ff")})), + layer( + "Group", + true, + 1.0, + "Normal", + json!({"kind":"group","children":[ + layer("Group bottom", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("00ff00ff")})), + layer("Group top", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("0000ffff")})) + ]}) + ) + ]), + ); + let mut s = Session { footage: std::sync::Arc::new(effectcraft_media::MediaPool::new()), ..Default::default() }; + let result = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); + let comp = ItemId(result["comps"][0].as_u64().unwrap()); + let image = s.render(comp, effectcraft_time::Tick::ZERO, Default::default()); + assert_eq!(image.data[0], [0.0, 0.0, 1.0, 1.0], "the source's top layer must cover both lower layers"); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn photocraft_bad_metadata_and_missing_layer_pixels_report_errors() { + use effectcraft_project::{AlphaMode, Footage, SourceLayer}; + for (name, bytes) in [ + ("empty-side.pcraft", bundle_sized(json!([]), (0, 6))), + ("large-canvas.pcraft", bundle_sized(json!([]), (30_000, 30_000))), + ("unsupported-fill.pcraft", bundle(json!([layer("Fill", true, 1.0, "Normal", json!({"kind":"fill"}))]))), + ("truncated.pcraft", b"PK\x03\x04broken".to_vec()), + ] { + let path = fixture_bytes(name, bytes); + let mut s = Session::default(); + let before = s.project.items.len(); + let result = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); + assert!(result["comps"].as_array().unwrap().is_empty(), "{name}: {result}"); + assert!(!result["errors"].as_array().unwrap().is_empty(), "{name}: {result}"); + assert_eq!(s.project.items.len(), before); + std::fs::remove_file(path).unwrap(); + } + let path = fixture("missing-cache.pcraft", json!([layer("Text", true, 1.0, "Normal", json!({"kind":"text"}))])); + let mut f = Footage { + path: path.clone(), + width: 8, + height: 6, + has_video: true, + alpha: AlphaMode::Straight, + layer: Some(SourceLayer { index: 0, name: "Text".into(), layer_size: false, embedded: None, placed: false }), + ..Default::default() + }; + let pool = effectcraft_media::MediaPool::new(); + assert!(pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap_err().to_string().contains("no saved pixels")); + f.layer.as_mut().unwrap().index = 99; + assert!(pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap_err().to_string().contains("no PhotoCraft layer")); + std::fs::remove_file(path).unwrap(); +} + +#[test] +#[cfg(unix)] // Sparse length checks exercise the guard without writing half a GiB. +fn photocraft_large_files_are_rejected_before_reading() { + for name in ["large-sparse.pcraft", "renamed-sparse.zip"] { + let path = fixture_bytes(name, b"PK\x03\x04".to_vec()); + std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_len((512 << 20) + 1).unwrap(); + assert!(effectcraft_media::probe(&path).unwrap_err().to_string().contains("512 MiB input limit")); + let mut s = Session::default(); + let before = s.project.items.len(); + let r = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); + assert_eq!(s.project.items.len(), before); + assert!(r["errors"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains("512 MiB input limit"))), "{r}"); + std::fs::remove_file(path).unwrap(); + } +} diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index a4070297b..5cca921c8 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -10,6 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] +craft-doc = { workspace = true, features = ["pcraft-pixels"] } craft-docpath = { workspace = true } effectcraft-time = { workspace = true } effectcraft-color = { workspace = true } diff --git a/crates/media/src/convert.rs b/crates/media/src/convert.rs index 9e88ab4dd..cbecb2729 100644 --- a/crates/media/src/convert.rs +++ b/crates/media/src/convert.rs @@ -37,6 +37,21 @@ impl AlphaOp { pub(crate) fn float_curve(self) -> FloatCurve { self.float } + /// A source sample, with float RGB encoded the same way as a floating-point image. + pub(crate) fn rgba(self, rgb: [f32; 3], alpha: f32, floating: bool, coverage: f32) -> Px { + let rgb = if floating && self.mode == AlphaMode::Premultiplied { + let inv = if alpha > 0.0 { 1.0 / alpha } else { 0.0 }; + rgb.map(|v| self.float(v * inv) * alpha) + } else if floating { + rgb.map(|v| self.float(v)) + } else { + rgb + }; + let pixel = self.apply(rgb, alpha); + // Interpret the source against its original alpha and matte before applying the + // mask. Ignore Alpha deliberately ignores both source and mask coverage. + if self.mode == AlphaMode::Ignore { pixel } else { pixel.map(|v| v * coverage) } + } /// A linear float value as the compositor takes it. #[inline(always)] fn float(self, v: f32) -> f32 { diff --git a/crates/media/src/layered.rs b/crates/media/src/layered.rs index b259c8b7f..76e6ff0e8 100644 --- a/crates/media/src/layered.rs +++ b/crates/media/src/layered.rs @@ -43,11 +43,14 @@ fn is_pdf_like(path: &str, bytes: &[u8]) -> bool { /// Whether `bytes` (the first 64 KiB suffice) are a Photoshop or vector file [`probe`] handles. #[cfg_attr(not(any(unix, windows)), allow(dead_code))] pub(crate) fn sniff(path: &str, bytes: &[u8]) -> bool { - effectcraft_psd::is_psd(bytes) || is_svg(path, bytes) || is_pdf_like(path, bytes) + effectcraft_psd::is_psd(bytes) || crate::pcraft::sniff(path, bytes) || is_svg(path, bytes) || is_pdf_like(path, bytes) } /// Footage for a Photoshop or vector file (`None` for other formats). pub(crate) fn probe(path: &str, bytes: &[u8]) -> Result> { + if crate::pcraft::sniff(path, bytes) { + return crate::pcraft::probe(path, bytes).map(Some); + } if effectcraft_psd::is_psd(bytes) { let psd = effectcraft_psd::Psd::parse(bytes.to_vec()).map_err(|e| MediaError::Decode(format!("{path}: {e}")))?; let mut f = crate::probe::still_footage(path, psd.width, psd.height, image::ImageFormat::Png, true); @@ -76,6 +79,9 @@ pub(crate) fn probe(path: &str, bytes: &[u8]) -> Result> { /// Decode a Photoshop or SVG still (`None` for other formats). pub(crate) fn decode(path: &str, bytes: &[u8], footage: &Footage, op: AlphaOp) -> Result> { + if crate::pcraft::sniff(path, bytes) { + return crate::pcraft::decode(path, bytes, footage, op).map(Some); + } if effectcraft_psd::is_psd(bytes) { let psd = effectcraft_psd::Psd::parse(bytes.to_vec()).map_err(|e| MediaError::Decode(format!("{path}: {e}")))?; // A smart object's embedded file: an embedded document's merged image, or an image. diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index e985985b7..ad6b1442a 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -11,7 +11,8 @@ //! AV1, ProRes, DNxHD, MPEG-2, MJPEG; AAC, Opus, PCM, MP3/FLAC/Vorbis) come from FilmCraft's pure-Rust crates (git dependency, //! pinned; `plan/adr/0001`). FilmCraft types never leave this crate. Stills use the `image` crate //! (PNG, JPEG, GIF, WebP, TIFF, BMP, OpenEXR, Targa, Radiance HDR); Photoshop documents (merged image or one layer) come -//! from `effectcraft-psd` and SVG from `effectcraft-svg` (rasterised at any scale). +//! from `effectcraft-psd`, PhotoCraft composites and saved layer pixels from `craft-doc`, and SVG +//! from `effectcraft-svg` (rasterised at any scale). #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -22,6 +23,7 @@ mod dpx; pub mod exr_channels; mod gif_anim; mod layered; +mod pcraft; pub use layered::vector_doc; mod pool; mod probe; @@ -62,7 +64,7 @@ impl From for MediaError { /// File extensions recognised as stills. pub const STILL_EXTENSIONS: &[&str] = - &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "tga", "hdr", "psd", "psb", "svg", "pdf", "ai", "eps"]; + &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "tga", "hdr", "psd", "psb", "pcraft", "svg", "pdf", "ai", "eps"]; /// File extensions recognised as audio-only files. pub const AUDIO_EXTENSIONS: &[&str] = filmcraft_media::AUDIO_EXTENSIONS; pub use effectcraft_project::VIDEO_EXTENSIONS; @@ -83,16 +85,32 @@ pub fn is_importable(path: &std::path::Path) -> bool { /// A whole file's bytes, refusing anything that isn't a regular file: a project can name /// `/dev/zero` or a FIFO as footage, and reading those never ends (#2134). pub(crate) fn read_regular_file(path: &std::path::Path) -> std::io::Result> { - use std::io::Read; + use std::io::{Read, Seek}; let mut file = std::fs::File::open(path)?; let meta = file.metadata()?; if !meta.is_file() { return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{} is not a file", path.display()))); } + let mut head = [0u8; 4]; + if meta.len() >= 4 { + file.read_exact(&mut head)?; + file.rewind()?; + } + let pcraft = ext_of(path) == "pcraft" || head == *b"PK\x03\x04"; + if pcraft && meta.len() > pcraft::MAX_INPUT_BYTES { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "ZIP/PhotoCraft bundle exceeds the 512 MiB input limit")); + } let mut bytes = Vec::new(); // A sparse file can claim far more than memory: an error, not an abort. bytes.try_reserve_exact(usize::try_from(meta.len()).unwrap_or(usize::MAX)).map_err(|e| std::io::Error::new(std::io::ErrorKind::OutOfMemory, e))?; - file.read_to_end(&mut bytes)?; + if pcraft { + file.take(pcraft::MAX_INPUT_BYTES + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > pcraft::MAX_INPUT_BYTES { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "PhotoCraft bundle grew beyond the 512 MiB input limit")); + } + } else { + file.read_to_end(&mut bytes)?; + } Ok(bytes) } diff --git a/crates/media/src/pcraft.rs b/crates/media/src/pcraft.rs new file mode 100644 index 000000000..fb7587c31 --- /dev/null +++ b/crates/media/src/pcraft.rs @@ -0,0 +1,170 @@ +//! PhotoCraft's saved composite and canvas-sized raster or cached layer pixels. + +use craft_doc::{Layer, RenditionKind, Samples}; +use effectcraft_project::{AlphaMode, Footage}; +use effectcraft_raster::Image; + +use crate::convert::{AlphaOp, dynamic_to_image}; +use crate::{MediaError, Result}; + +/// Keep the decoded float frame and its conversion buffers within the still-image budget. +const MAX_PIXELS: u64 = 16 << 20; +pub(crate) const MAX_INPUT_BYTES: u64 = 512 << 20; + +pub(crate) fn sniff(path: &str, bytes: &[u8]) -> bool { + path.to_ascii_lowercase().ends_with(".pcraft") || craft_doc::sniff(bytes) == Some(craft_doc::Kind::PhotoCraft) +} + +fn error(path: &str, e: impl std::fmt::Display) -> MediaError { + MediaError::Decode(format!("{path}: {e}")) +} + +fn check_size(path: &str, width: u32, height: u32) -> Result<()> { + if width == 0 || height == 0 || u64::from(width) * u64::from(height) > MAX_PIXELS { + return Err(error(path, format!("PhotoCraft image {width} × {height} exceeds the {MAX_PIXELS}-pixel decoding limit or has an empty side"))); + } + Ok(()) +} + +fn composite(path: &str, bytes: &[u8]) -> Result> { + check_input(path, bytes)?; + craft_doc::renditions(bytes, &craft_doc::Limits::default()) + .map_err(|e| error(path, e))? + .into_iter() + .find(|r| r.kind == RenditionKind::Composite) + .map(|r| r.bytes) + .ok_or_else(|| error(path, "PhotoCraft document has no saved composite")) +} + +fn check_input(path: &str, bytes: &[u8]) -> Result<()> { + if bytes.len() as u64 > MAX_INPUT_BYTES { + return Err(error(path, "PhotoCraft bundle exceeds the 512 MiB input limit")); + } + Ok(()) +} + +fn png_size(path: &str, bytes: &[u8]) -> Result<(u32, u32)> { + let size = image::ImageReader::with_format(std::io::Cursor::new(bytes), image::ImageFormat::Png).into_dimensions().map_err(|e| error(path, e))?; + check_size(path, size.0, size.1)?; + Ok(size) +} + +pub(crate) fn probe(path: &str, bytes: &[u8]) -> Result { + let png = composite(path, bytes)?; + let (w, h) = png_size(path, &png)?; + let mut f = crate::probe::still_footage(path, w, h, image::ImageFormat::Png, true); + f.codec = "PhotoCraft".into(); + f.alpha = AlphaMode::Straight; + Ok(f) +} + +/// Preorder indexes include groups and unsupported layers, so a reload addresses the same +/// outline entry used by the composition importer. +fn layer_path(layers: &[Layer], wanted: u32) -> Option> { + fn find(layers: &[Layer], wanted: u32, next: &mut u32, path: &mut Vec, depth: usize) -> Option> { + if depth > 100 { + return None; + } + for (index, layer) in layers.iter().enumerate() { + path.push(index); + let current = *next; + *next = next.checked_add(1)?; + if current == wanted { + return Some(path.clone()); + } + if let Some(found) = find(&layer.children, wanted, next, path, depth + 1) { + return Some(found); + } + path.pop(); + } + None + } + find(layers, wanted, &mut 0, &mut Vec::new(), 0) +} + +fn mask_image(path: &str, width: u32, height: u32, samples: Samples) -> Result { + let count = usize::try_from(u64::from(width) * u64::from(height)).map_err(|e| error(path, e))?; + if samples.len() != count { + return Err(error(path, "PhotoCraft mask size does not match the canvas")); + } + let mut data = Vec::new(); + data.try_reserve_exact(count).map_err(|e| error(path, e))?; + let pixel = |v: f32| [if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; 4]; + match samples { + Samples::U8(v) => data.extend(v.into_iter().map(|v| pixel(f32::from(v) / 255.0))), + Samples::U16(v) => data.extend(v.into_iter().map(|v| pixel(f32::from(v) / 65535.0))), + Samples::F32(v) => data.extend(v.into_iter().map(pixel)), + _ => return Err(error(path, "unsupported PhotoCraft mask sample type")), + } + Ok(Image { width, height, data }) +} + +pub(crate) fn decode(path: &str, bytes: &[u8], footage: &Footage, op: AlphaOp) -> Result { + check_input(path, bytes)?; + let Some(layer) = &footage.layer else { + let png = composite(path, bytes)?; + png_size(path, &png)?; + let image = crate::probe::load_oriented(&png, Some(image::ImageFormat::Png)).map_err(|e| error(path, e))?; + return Ok(dynamic_to_image(&image, op)); + }; + if layer.layer_size || layer.embedded.is_some() || layer.placed { + return Err(error(path, "PhotoCraft layer footage supports canvas-sized saved pixels, not cropped or embedded-file sources")); + } + let outline = craft_doc::outline(bytes, &craft_doc::Limits::default()).map_err(|e| error(path, e))?; + let canvas = outline.canvas.ok_or_else(|| error(path, "PhotoCraft document has no canvas"))?; + check_size(path, canvas.width, canvas.height)?; + let indexes = layer_path(&outline.layers, layer.index).ok_or_else(|| error(path, format!("no PhotoCraft layer {}", layer.index)))?; + let pixels = craft_doc::pcraft_layer_rgba(bytes, &indexes, &craft_doc::Limits::default()) + .map_err(|e| error(path, e))? + .ok_or_else(|| error(path, format!("PhotoCraft layer {} has no saved pixels", layer.name)))?; + let (w, h) = (pixels.width, pixels.height); + let count = usize::try_from(u64::from(w) * u64::from(h)).map_err(|e| error(path, e))?; + if count.checked_mul(4) != Some(pixels.rgba.len()) { + return Err(error(path, "PhotoCraft layer sample count does not match the canvas")); + } + let mask = if let Some(mask) = pixels.mask.filter(|m| m.enabled) { + let mut alpha = mask_image(path, w, h, mask.alpha)?; + let sigma = if mask.feather.is_finite() { f64::from(mask.feather.clamp(0.0, 1000.0)) } else { 0.0 }; + if sigma > 0.0 { + alpha = if effectcraft_raster::gaussian_is_exact(sigma, sigma) { + effectcraft_raster::gaussian_blur_exact(&alpha, sigma, sigma, true) + } else { + effectcraft_raster::gaussian_blur(&alpha, sigma, sigma, true) + }; + } + let density = if mask.density.is_finite() { mask.density.clamp(0.0, 1.0) } else { 1.0 }; + Some((alpha, density)) + } else { + None + }; + let mut data = Vec::new(); + data.try_reserve_exact(count).map_err(|e| error(path, e))?; + let mut push = |index: usize, rgba: [f32; 4], floating: bool| -> Result<()> { + let rgba = rgba.map(|v| if v.is_finite() { v } else { 0.0 }); + let coverage = match &mask { + Some((alpha, density)) => 1.0 - density * (1.0 - alpha.data.get(index).ok_or_else(|| error(path, "PhotoCraft mask pixel is missing"))?[3]), + None => 1.0, + }; + data.push(op.rgba([rgba[0], rgba[1], rgba[2]], rgba[3].clamp(0.0, 1.0), floating, coverage)); + Ok(()) + }; + match pixels.rgba { + Samples::U8(v) => { + for (index, [r, g, b, a]) in v.as_chunks::<4>().0.iter().enumerate() { + push(index, [f32::from(*r), f32::from(*g), f32::from(*b), f32::from(*a)].map(|v| v / 255.0), false)?; + } + } + Samples::U16(v) => { + for (index, [r, g, b, a]) in v.as_chunks::<4>().0.iter().enumerate() { + push(index, [f32::from(*r), f32::from(*g), f32::from(*b), f32::from(*a)].map(|v| v / 65535.0), false)?; + } + } + Samples::F32(v) => { + for (index, [r, g, b, a]) in v.as_chunks::<4>().0.iter().enumerate() { + push(index, [*r, *g, *b, *a], true)?; + } + } + _ => return Err(error(path, "unsupported PhotoCraft layer sample type")), + } + Ok(Image { width: w, height: h, data }) +} diff --git a/crates/ui-egui/src/menus/frontend.rs b/crates/ui-egui/src/menus/frontend.rs index 71bf8214b..88c5bb7c7 100644 --- a/crates/ui-egui/src/menus/frontend.rs +++ b/crates/ui-egui/src/menus/frontend.rs @@ -607,7 +607,7 @@ pub(super) fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> // Importable files besides movies. const MEDIA: &[&str] = &[ "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "dpx", "cin", "wav", "aif", "aiff", "mp3", "flac", "ogg", "opus", "svg", "pdf", "ai", - "eps", "psd", "psb", "tga", "hdr", "gltf", "glb", "obj", "stl", "fbx", "json", "csv", "tsv", + "eps", "psd", "psb", "pcraft", "tga", "hdr", "gltf", "glb", "obj", "stl", "fbx", "json", "csv", "tsv", ]; let footage = |more: &[&'static str]| effectcraft_project::VIDEO_EXTENSIONS.iter().chain(more).copied().collect::>(); // A host whose blocking dialogs are unsafe inside this frame shows the dialog without diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 0ed3fe7ad..fe16b7486 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -449,7 +449,7 @@ fn file_dialogs_block_floating_windows_only_while_up() { } #[test] -fn tga_is_available_in_import_replace_and_proxy_dialogs() { +fn tga_is_available_in_import_replace_and_proxy_and_pcraft_in_import_replace() { use std::sync::{Arc, Mutex}; let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); let ctx = egui::Context::default(); @@ -460,6 +460,9 @@ fn tga_is_available_in_import_replace_and_proxy_dialogs() { assert_eq!(invoke(&mut app, &ctx, command, json!({})).unwrap(), json!({"dialog": command})); let crate::FileDialog::Open { exts, .. } = pending.lock().unwrap().pop().unwrap() else { panic!("not an open dialog") }; assert!(exts.iter().any(|ext| ext == "tga"), "{command}: {exts:?}"); + if command != "file.setProxy" { + assert!(exts.iter().any(|ext| ext == "pcraft"), "{command}: {exts:?}"); + } } } diff --git a/crates/ui-egui/src/panels/forms.rs b/crates/ui-egui/src/panels/forms.rs index 65d825b45..269db8a47 100644 --- a/crates/ui-egui/src/panels/forms.rs +++ b/crates/ui-egui/src/panels/forms.rs @@ -513,6 +513,20 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool { let lt = layer.map(|l| l.layer_time(t)).unwrap_or(t); let mut base = p.clone(); let (title, fields): (String, Vec) = match id { + "file.import" if !has(p, &["importAs"]) && imports_ext(p, &["pcraft"]) && !is_layered(p) => { + let drag = p.get("drag").and_then(Value::as_bool).unwrap_or(false); + let sel = usize::from(drag && s.prefs.drag_import_as() != "footage"); + ( + "Import PhotoCraft File".into(), + vec![ + Field::choice("importAs", "Import Kind", &[("Footage", json!("footage")), ("Composition", json!("composition"))], sel), + Field::note( + "pcraftNote", + "Composition uses canvas-sized saved pixels. Masks, effects and profiles may differ; use Footage for the saved appearance.", + ), + ], + ) + } // Photoshop files: Import Kind (Footage / Composition / – Retain Layer Sizes). Dropped // files start at Settings ▸ Import ▸ Default Drag Import As. "file.import" if !has(p, &["importAs"]) && is_layered(p) => { @@ -1050,6 +1064,21 @@ pub fn show_view_options(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Toke mod tests { use super::*; + #[test] + fn photocraft_import_offers_footage_or_canvas_sized_layers() { + for (pref, expected) in [("footage", "footage"), ("comp", "composition"), ("compLayerSizes", "composition")] { + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + app.session.prefs.import.drag_import_as = pref.into(); + let reply = crate::menus::invoke(&mut app, &egui::Context::default(), "file.import", json!({"paths":["/picked.pcraft"],"drag":true})).unwrap(); + assert_eq!(reply["dialog"], "file.import"); + assert_eq!(app.dialog_state.form.title, "Import PhotoCraft File"); + assert_eq!(app.dialog_state.form.params()["importAs"], expected); + assert!(app.dialog_state.form.params().get("pcraftNote").is_none()); + let FieldKind::Choice { options, .. } = &app.dialog_state.form.fields[0].kind else { panic!("no import choices") }; + assert_eq!(options.len(), 2, "Retain Layer Sizes is not offered for canvas-sized PhotoCraft pixels"); + } + } + #[test] fn form_params_build_arrays_and_choices() { let f = Form { diff --git a/crates/ui-egui/src/prefs_live.rs b/crates/ui-egui/src/prefs_live.rs index b456dc7ce..f351864eb 100644 --- a/crates/ui-egui/src/prefs_live.rs +++ b/crates/ui-egui/src/prefs_live.rs @@ -112,7 +112,7 @@ pub fn dropped_files(app: &mut EffectcraftApp, ui: &egui::Ui, bounds: Rect) { let alt = ctx.input(|i| i.modifiers.alt); // A dropped Photoshop file asks how to import it (the Import Photoshop File dialog, its // Import Kind starting at Default Drag Import As), as File ▸ Import ▸ File… does (#678). - let layered = rest.iter().any(|p| p.rsplit('.').next().is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "psd" | "psb"))); + let layered = rest.iter().any(|p| p.rsplit('.').next().is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "psd" | "psb" | "pcraft"))); let mut params = json!({ "paths": rest, "drag": true, diff --git a/docs/photocraft-import.md b/docs/photocraft-import.md new file mode 100644 index 000000000..8c4d709e3 --- /dev/null +++ b/docs/photocraft-import.md @@ -0,0 +1,25 @@ +# Import PhotoCraft documents + +Choose **File ▸ Import ▸ File…** and select a `.pcraft` document. Numbered PhotoCraft documents import individually, rather than as an image sequence. + +**Footage** reads the document's saved composite as one still image. Its dimensions are the saved image's actual dimensions. The currently pinned shared reader exposes PhotoCraft's saved preview, which can be smaller than the canvas. Import reports both sizes when they differ. Full-resolution composite selection requires a later shared-reader update. + +**Composition** creates a composition with canvas-sized layer footage. It preserves layer names, visibility, opacity, recognized blend modes and group nesting. Groups become precompositions; pass-through groups use Collapse Transformations. Raster layers and saved pixel caches for text, shapes and smart objects remain linked to the source file. Text, shapes and smart objects are imported as pixels, without their native editing controls. + +Layer pixels decode when a frame needs them. Missing caches or unsupported pixel data produce media decoding errors when used. Layered import supports RGB and grayscale pixels with 8-bit, 16-bit or floating-point samples. Enabled raster masks apply their density and feather. Native effects, vector and group masks, and embedded color profiles are unsupported, so a layered composition can differ from the saved appearance. Choose Footage when that appearance matters. + +The dialog offers Footage and Composition. The command API also accepts `compositionLayerSizes`, but reports that PhotoCraft layers retain the full canvas bounds. A drag preference for retaining layer sizes selects Composition in this dialog. + +## Command API + +```json +{"command":"file.import","params":{"paths":["/path/artwork.pcraft"],"importAs":"footage"}} +``` + +Use `"importAs":"composition"` for layers. Import uses the existing still-footage duration preference and creates one undoable import operation for each layered document. Compatibility messages accompany the command's import results. + +## Limits + +PhotoCraft input is limited to 512 MiB. Whole-file ZIP reads share that limit, checked from the archive signature before allocating the input, so renaming a bundle does not bypass it. Decoded composites and layer canvases are limited to 16,777,216 pixels. Composition import also respects EffectCraft's composition size limit, allows up to 4,096 layers and 100 levels of group nesting, and rejects unsupported CMYK or Lab layer data. Footage can still import a supported saved composite when the document's layers exceed those limits. + +Unsupported layer kinds are skipped with a message naming the layer. A nonempty document with no supported pixel layers cannot import as a composition; the error recommends Footage. Invalid input reports an error before adding a composition. From 76bd5dc1018966cce0f709dbfc61e294ea942437 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 22:51:02 -0800 Subject: [PATCH 04/38] Import: budget PhotoCraft layer buffers before decoding pixels --- .../engine/src/interchange/pcraft_import.rs | 6 +++-- crates/engine/src/tests/import_photocraft.rs | 22 +++++++++++++++++++ crates/media/src/pcraft.rs | 7 ++++++ docs/photocraft-import.md | 4 +++- 4 files changed, 36 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/interchange/pcraft_import.rs b/crates/engine/src/interchange/pcraft_import.rs index a7b24ff62..681409f1f 100644 --- a/crates/engine/src/interchange/pcraft_import.rs +++ b/crates/engine/src/interchange/pcraft_import.rs @@ -47,8 +47,10 @@ pub(crate) fn read(bytes: &[u8]) -> Result { if width == 0 || height == 0 || width > effectcraft_project::limits::MAX_SIZE || height > effectcraft_project::limits::MAX_SIZE { return Err(format!("PhotoCraft canvas {width} × {height} is outside the composition size limits")); } - if u64::from(width) * u64::from(height) > 16 << 20 { - return Err("PhotoCraft layer decoding exceeds 16777216 canvas pixels; import as Footage for the saved composite".into()); + if u64::from(width) * u64::from(height) > 12 << 20 { + return Err( + "PhotoCraft layer decoding exceeds the 1 GiB working-buffer budget (12582912 canvas pixels); import as Footage for the saved composite".into() + ); } if matches!(canvas.mode.as_str(), "Cmyk" | "Lab") { return Err(format!("PhotoCraft {} layer pixels are not supported; import as Footage for the saved composite", canvas.mode)); diff --git a/crates/engine/src/tests/import_photocraft.rs b/crates/engine/src/tests/import_photocraft.rs index 1298c346f..e9b7af55c 100644 --- a/crates/engine/src/tests/import_photocraft.rs +++ b/crates/engine/src/tests/import_photocraft.rs @@ -235,3 +235,25 @@ fn photocraft_large_files_are_rejected_before_reading() { std::fs::remove_file(path).unwrap(); } } + +#[test] +fn photocraft_layer_buffers_are_bounded_before_decoding_pixels() { + use effectcraft_project::{AlphaMode, Footage, SourceLayer}; + // An invalid source sample proves the budget is checked before the pixel reader. + let mut raster = layer("Large masked layer", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("invalid-pixel-sample")})); + raster["mask"] = json!({"enabled":true,"density":1.0,"feather":4.0, + "surface":{"format":{"mode":"Grayscale","sample":"U8","alpha":false},"default":"ff","tiles":[]}}); + let path = fixture_bytes("mask-budget.pcraft", bundle_sized(json!([raster]), (4097, 3072))); + let f = Footage { + path: path.clone(), + width: 4097, + height: 3072, + has_video: true, + alpha: AlphaMode::Straight, + layer: Some(SourceLayer { index: 0, name: "Large masked layer".into(), layer_size: false, embedded: None, placed: false }), + ..Default::default() + }; + let error = effectcraft_media::MediaPool::new().frame_at(&f, effectcraft_time::Tick::ZERO).unwrap_err().to_string(); + assert!(error.contains("1 GiB working-buffer budget") && error.contains("Footage"), "{error}"); + std::fs::remove_file(path).unwrap(); +} diff --git a/crates/media/src/pcraft.rs b/crates/media/src/pcraft.rs index fb7587c31..220fcd381 100644 --- a/crates/media/src/pcraft.rs +++ b/crates/media/src/pcraft.rs @@ -9,6 +9,10 @@ use crate::{MediaError, Result}; /// Keep the decoded float frame and its conversion buffers within the still-image budget. const MAX_PIXELS: u64 = 16 << 20; +// Conservatively count source RGBA (16 B), raw mask samples (4 B), mask image +// (16 B), two blur images (32 B) and output (16 B), even where lifetimes do not +// overlap. Twelve Mi pixels fit within a 1 GiB working-buffer budget (84 B/pixel). +const MAX_LAYER_PIXELS: u64 = 12 << 20; pub(crate) const MAX_INPUT_BYTES: u64 = 512 << 20; pub(crate) fn sniff(path: &str, bytes: &[u8]) -> bool { @@ -113,6 +117,9 @@ pub(crate) fn decode(path: &str, bytes: &[u8], footage: &Footage, op: AlphaOp) - let outline = craft_doc::outline(bytes, &craft_doc::Limits::default()).map_err(|e| error(path, e))?; let canvas = outline.canvas.ok_or_else(|| error(path, "PhotoCraft document has no canvas"))?; check_size(path, canvas.width, canvas.height)?; + if u64::from(canvas.width) * u64::from(canvas.height) > MAX_LAYER_PIXELS { + return Err(error(path, "PhotoCraft layer exceeds the 1 GiB working-buffer budget; import as Footage for the saved composite")); + } let indexes = layer_path(&outline.layers, layer.index).ok_or_else(|| error(path, format!("no PhotoCraft layer {}", layer.index)))?; let pixels = craft_doc::pcraft_layer_rgba(bytes, &indexes, &craft_doc::Limits::default()) .map_err(|e| error(path, e))? diff --git a/docs/photocraft-import.md b/docs/photocraft-import.md index 8c4d709e3..47cdf5a8c 100644 --- a/docs/photocraft-import.md +++ b/docs/photocraft-import.md @@ -20,6 +20,8 @@ Use `"importAs":"composition"` for layers. Import uses the existing still-footag ## Limits -PhotoCraft input is limited to 512 MiB. Whole-file ZIP reads share that limit, checked from the archive signature before allocating the input, so renaming a bundle does not bypass it. Decoded composites and layer canvases are limited to 16,777,216 pixels. Composition import also respects EffectCraft's composition size limit, allows up to 4,096 layers and 100 levels of group nesting, and rejects unsupported CMYK or Lab layer data. Footage can still import a supported saved composite when the document's layers exceed those limits. +PhotoCraft input is limited to 512 MiB. Whole-file ZIP reads share that limit, checked from the archive signature before allocating the input, so renaming a bundle does not bypass it. Decoded composites are limited to 16,777,216 pixels and layer canvases to 12,582,912 pixels. Composition import also respects EffectCraft's composition size limit, allows up to 4,096 layers and 100 levels of group nesting, and rejects unsupported CMYK or Lab layer data. Footage can still import a supported saved composite when the document's layers exceed those limits. Unsupported layer kinds are skipped with a message naming the layer. A nonempty document with no supported pixel layers cannot import as a composition; the error recommends Footage. Invalid input reports an error before adding a composition. + +Layer decoding has a separate limit of 12,582,912 canvas pixels, checked before reading source samples. A conservative budget counts the source, raw mask, mask image, both feathering intermediates and output together, within 1 GiB of working buffers. Larger canvases report an error recommending Footage before decoding layer pixels. This includes masked and unmasked layers; saved composites retain the 16,777,216-pixel limit. From b7cd1ae80dcfa9a8cdb3db1b5feec12045c51907 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 22:55:01 -0800 Subject: [PATCH 05/38] Import: match PhotoCraft group depth to the renderer limit --- .../engine/src/interchange/pcraft_import.rs | 12 ++++++--- crates/engine/src/tests/import_photocraft.rs | 25 +++++++++++++++++++ docs/photocraft-import.md | 2 +- 3 files changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/interchange/pcraft_import.rs b/crates/engine/src/interchange/pcraft_import.rs index 681409f1f..ae3b4e4e0 100644 --- a/crates/engine/src/interchange/pcraft_import.rs +++ b/crates/engine/src/interchange/pcraft_import.rs @@ -8,6 +8,9 @@ use effectcraft_keyframe::Value; use effectcraft_project::{AlphaMode, Comp, Footage, FootageKind, ItemId, ItemKind, LayerSource, Project, SourceLayer, build}; use effectcraft_time::{FrameRate, Tick}; +// Each source group becomes a precomposition; match the renderer's nesting limit. +const MAX_GROUP_DEPTH: usize = 16; + pub(crate) struct Document { outline: Outline, width: u32, @@ -21,10 +24,13 @@ pub(crate) fn read(bytes: &[u8]) -> Result { return Err("PhotoCraft bundle exceeds the 512 MiB input limit".into()); } fn count(layers: &[InputLayer], depth: usize, nodes: &mut usize, pixels: &mut usize) -> Result<(), String> { - if depth > 100 { - return Err("PhotoCraft groups exceed 100 levels".into()); + if depth > MAX_GROUP_DEPTH { + return Err("PhotoCraft groups exceed 16 levels; import as Footage for the saved composite".into()); } for layer in layers { + if depth == MAX_GROUP_DEPTH && layer.kind == "group" { + return Err("PhotoCraft groups exceed 16 levels; import as Footage for the saved composite".into()); + } *nodes += 1; if *nodes > 4096 { return Err("PhotoCraft composition import exceeds 4096 layers; import as Footage for the saved composite".into()); @@ -106,7 +112,7 @@ fn build_comp(project: &mut Project, ctx: &mut Context, name: &str, layers: &[In let mut comp = Comp::new(ctx.doc.width, ctx.doc.height, ctx.rate, ctx.duration); let id = project.add_item(name, Label::Sandstone, parent, ItemKind::Comp(Arc::new(comp.clone()))); ctx.items.push(id); - if depth <= 100 { + if depth <= MAX_GROUP_DEPTH { for input in layers { let index = ctx.next; ctx.next = ctx.next.saturating_add(1); diff --git a/crates/engine/src/tests/import_photocraft.rs b/crates/engine/src/tests/import_photocraft.rs index e9b7af55c..203fc9ecf 100644 --- a/crates/engine/src/tests/import_photocraft.rs +++ b/crates/engine/src/tests/import_photocraft.rs @@ -257,3 +257,28 @@ fn photocraft_layer_buffers_are_bounded_before_decoding_pixels() { assert!(error.contains("1 GiB working-buffer budget") && error.contains("Footage"), "{error}"); std::fs::remove_file(path).unwrap(); } + +#[test] +fn photocraft_group_nesting_stays_within_the_composition_renderer_limit() { + for (depth, blend) in [(16, "Normal"), (16, "PassThrough"), (17, "Normal"), (17, "PassThrough")] { + let mut layers = json!([layer("Deep pixels", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("0000ffff")}))]); + for index in 0..depth { + layers = json!([layer(&format!("Group {index}"), true, 1.0, blend, json!({"kind":"group","children":layers}))]); + } + let path = fixture(&format!("nesting-{depth}-{blend}.pcraft"), layers); + let mut s = Session { footage: std::sync::Arc::new(effectcraft_media::MediaPool::new()), ..Default::default() }; + let before = s.project.items.len(); + let result = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); + if depth == 16 { + let comp = ItemId(result["comps"][0].as_u64().unwrap()); + assert_eq!(s.render(comp, effectcraft_time::Tick::ZERO, Default::default()).data[0], [0.0, 0.0, 1.0, 1.0]); + } else { + assert_eq!(s.project.items.len(), before, "unsupported nesting must not create a composition with disappearing artwork"); + assert!( + result["errors"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains("16 levels") && e.contains("Footage"))), + "{result}" + ); + } + std::fs::remove_file(path).unwrap(); + } +} diff --git a/docs/photocraft-import.md b/docs/photocraft-import.md index 47cdf5a8c..0599fcfbf 100644 --- a/docs/photocraft-import.md +++ b/docs/photocraft-import.md @@ -20,7 +20,7 @@ Use `"importAs":"composition"` for layers. Import uses the existing still-footag ## Limits -PhotoCraft input is limited to 512 MiB. Whole-file ZIP reads share that limit, checked from the archive signature before allocating the input, so renaming a bundle does not bypass it. Decoded composites are limited to 16,777,216 pixels and layer canvases to 12,582,912 pixels. Composition import also respects EffectCraft's composition size limit, allows up to 4,096 layers and 100 levels of group nesting, and rejects unsupported CMYK or Lab layer data. Footage can still import a supported saved composite when the document's layers exceed those limits. +PhotoCraft input is limited to 512 MiB. Whole-file ZIP reads share that limit, checked from the archive signature before allocating the input, so renaming a bundle does not bypass it. Decoded composites are limited to 16,777,216 pixels and layer canvases to 12,582,912 pixels. Composition import also respects EffectCraft's composition size limit, allows up to 4,096 layers and 16 levels of group nesting, and rejects unsupported CMYK or Lab layer data. Footage can still import a supported saved composite when the document's layers exceed those limits. Unsupported layer kinds are skipped with a message naming the layer. A nonempty document with no supported pixel layers cannot import as a composition; the error recommends Footage. Invalid input reports an error before adding a composition. From 6d5615cb4336c40b77a4ab4196f3d3008d923c68 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 03:54:06 -0800 Subject: [PATCH 06/38] Import: keep optional PhotoCraft canvas warnings non-fatal --- crates/engine/src/cmd/file.rs | 21 ++++++------- crates/engine/src/tests/import_photocraft.rs | 32 ++++++++++++++++++++ 2 files changed, 42 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 61ee1d8ae..e91de3e6f 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -321,17 +321,16 @@ impl Prober { let importer = self.importer.as_ref().ok_or_else(|| fail("media import is not available in this build".into()))?; let mut f = crate::sequence::probe(importer.as_ref(), src, self.sequence_rate).map_err(fail)?; let mut warning = None; - if f.codec == "PhotoCraft" { - let bytes = self.services.read_file(path).map_err(|e| fail(e.to_string()))?; - let outline = craft_doc::outline(&bytes, &craft_doc::Limits::default()).map_err(|e| fail(e.to_string()))?; - if let Some(canvas) = outline.canvas - && (canvas.width, canvas.height) != (f.width, f.height) - { - warning = Some(format!( - "{name}: imported the saved {} × {} composite of a {} × {} PhotoCraft canvas", - f.width, f.height, canvas.width, canvas.height - )); - } + // The composite has already probed successfully. Optional canvas metadata must + // not prevent Footage import when its read or outline exceeds another limit. + if f.codec == "PhotoCraft" + && let Ok(bytes) = self.services.read_file(path) + && let Ok(outline) = craft_doc::outline(&bytes, &craft_doc::Limits::default()) + && let Some(canvas) = outline.canvas + && (canvas.width, canvas.height) != (f.width, f.height) + { + warning = + Some(format!("{name}: imported the saved {} × {} composite of a {} × {} PhotoCraft canvas", f.width, f.height, canvas.width, canvas.height)); } // Settings ▸ Import ▸ Report Missing Frames (numbered sequences). if f.kind == FootageKind::Sequence diff --git a/crates/engine/src/tests/import_photocraft.rs b/crates/engine/src/tests/import_photocraft.rs index 203fc9ecf..58115fd71 100644 --- a/crates/engine/src/tests/import_photocraft.rs +++ b/crates/engine/src/tests/import_photocraft.rs @@ -119,6 +119,38 @@ fn photocraft_composition_keeps_layer_names_visibility_opacity_and_blend() { std::fs::remove_file(path).unwrap(); } +#[test] +fn photocraft_optional_canvas_metadata_does_not_block_probed_footage() { + struct Metadata(bool); + impl crate::Services for Metadata { + fn read_file(&self, _: &str) -> std::io::Result> { + if self.0 { + Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "metadata unavailable")) + } else { + Ok(b"invalid optional metadata".to_vec()) + } + } + fn write_file(&self, _: &str, _: &[u8]) -> std::io::Result<()> { + Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "read only")) + } + } + for unreadable in [true, false] { + let path = fixture(&format!("optional-metadata-{unreadable}.pcraft"), json!([])); + let mut s = Session { services: std::sync::Arc::new(Metadata(unreadable)), importer: Some(std::sync::Arc::new(Import)), ..Default::default() }; + let result = s.execute("file.import", json!({"paths":[path]})).unwrap(); + assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); + assert_eq!(result["items"].as_array().unwrap().len(), 1, "a successful media probe must survive an optional warning failure"); + let id = ItemId(result["items"][0].as_u64().unwrap()); + let ItemKind::Footage(f) = &s.project.item(id).unwrap().kind else { panic!("not footage") }; + assert_eq!((f.width, f.height), (4, 3)); + assert_eq!( + effectcraft_media::MediaPool::new().frame_at(f, effectcraft_time::Tick::ZERO).unwrap().data[0], + [20.0 / 255.0, 30.0 / 255.0, 40.0 / 255.0, 1.0] + ); + std::fs::remove_file(path).unwrap(); + } +} + #[test] fn photocraft_masks_and_sample_depths_decode_through_the_media_pool() { use effectcraft_project::{AlphaMode, Footage, SourceLayer}; From bc527043b04680c01ed01c6d3f1888a055c49b26 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 20:32:10 -0800 Subject: [PATCH 07/38] Import: limit only PhotoCraft reads to 512 MiB Services::read_file and the media reader no longer refuse ZIP-based files over 512 MiB, so large templates and dotLottie files read as before. A new Services::read_pcraft applies the limit before reading, and the PhotoCraft canvas check and composition import use it for .pcraft files; the browser checks the stored size before copying. The media reader limits .pcraft files before reading. A PhotoCraft bundle with another extension is still refused after its read, before it is parsed. --- apps/effectcraft-web/src/files.rs | 16 ++-- crates/engine/src/cmd/file.rs | 16 ++-- crates/engine/src/lib.rs | 2 +- crates/engine/src/services.rs | 94 +++++++++++++------- crates/engine/src/tests/import_photocraft.rs | 20 ++--- crates/media/src/lib.rs | 27 ++++-- docs/photocraft-import.md | 2 +- 7 files changed, 112 insertions(+), 65 deletions(-) diff --git a/apps/effectcraft-web/src/files.rs b/apps/effectcraft-web/src/files.rs index b1647c15d..d33db6542 100644 --- a/apps/effectcraft-web/src/files.rs +++ b/apps/effectcraft-web/src/files.rs @@ -114,13 +114,17 @@ pub struct WebServices; impl Services for WebServices { fn read_file(&self, path: &str) -> std::io::Result> { get(path) + .map(|d| d.to_vec()) .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, format!("{path}: open it with File ▸ Open (or drop it on the page)"))) - .and_then(|data| { - if (data.starts_with(b"PK\x03\x04") || path.to_ascii_lowercase().ends_with(".pcraft")) && data.len() as u64 > 512 << 20 { - return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "ZIP/PhotoCraft bundle exceeds the 512 MiB input limit")); - } - Ok(data.to_vec()) - }) + } + /// Checks the size before copying the stored bytes. + fn read_pcraft(&self, path: &str) -> std::io::Result> { + let data = + get(path).ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, format!("{path}: open it with File ▸ Open (or drop it on the page)")))?; + if data.len() as u64 > effectcraft_engine::PCRAFT_MAX_INPUT { + return Err(effectcraft_engine::pcraft_too_large()); + } + Ok(data.to_vec()) } fn write_file(&self, path: &str, data: &[u8]) -> std::io::Result<()> { put(path, data.into()); diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index e91de3e6f..23e835cbf 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -324,7 +324,7 @@ impl Prober { // The composite has already probed successfully. Optional canvas metadata must // not prevent Footage import when its read or outline exceeds another limit. if f.codec == "PhotoCraft" - && let Ok(bytes) = self.services.read_file(path) + && let Ok(bytes) = self.services.read_pcraft(path) && let Ok(outline) = craft_doc::outline(&bytes, &craft_doc::Limits::default()) && let Some(canvas) = outline.canvas && (canvas.width, canvas.height) != (f.width, f.height) @@ -427,12 +427,12 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result { if let Some(retain) = retain { let mut rest = vec![]; for path in paths { - if path.to_ascii_lowercase().ends_with(".pcraft") && s.services.stamp(&path).is_some_and(|(bytes, _)| bytes > 512 << 20) { - errors.push(format!("{path}: PhotoCraft bundle exceeds the 512 MiB input limit")); - continue; - } - let bytes = match s.services.read_file(&path) { - Ok(b) if path.to_ascii_lowercase().ends_with(".pcraft") || craft_doc::sniff(&b) == Some(craft_doc::Kind::PhotoCraft) => { + // Only PhotoCraft reads have the input limit; a renamed bundle is checked after its + // read, before it is parsed. + let pcraft = path.to_ascii_lowercase().ends_with(".pcraft"); + let read = if pcraft { s.services.read_pcraft(&path) } else { s.services.read_file(&path) }; + let bytes = match read { + Ok(b) if pcraft || craft_doc::sniff(&b) == Some(craft_doc::Kind::PhotoCraft) => { match import_pcraft_comp(s, &path, &b, retain) { Ok((comp, made, warnings)) => { comps.push(comp); @@ -455,7 +455,7 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result { } continue; } - Err(e) if e.kind() == std::io::ErrorKind::InvalidData || path.to_ascii_lowercase().ends_with(".pcraft") => { + Err(e) if pcraft => { errors.push(format!("{path}: {e}")); continue; } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 0cc9a7189..6493a0481 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -95,7 +95,7 @@ pub use doc_state::{CompSelection, EditorState, KeyClip, KeyMove, KeyRef, LinkCl pub use error::{EngineError, Result}; pub use event::Event; pub use fonts::{FontRow, font_features, font_menu, font_preview, font_styles, text_families}; -pub use services::{FsServices, Importer, Services}; +pub use services::{FsServices, Importer, PCRAFT_MAX_INPUT, Services, pcraft_too_large}; pub use session::upgrade_effects; pub struct Session { diff --git a/crates/engine/src/services.rs b/crates/engine/src/services.rs index 5f1a86c99..cce219f33 100644 --- a/crates/engine/src/services.rs +++ b/crates/engine/src/services.rs @@ -1,8 +1,28 @@ use super::config; +/// The largest PhotoCraft bundle [`Services::read_pcraft`] reads. +pub const PCRAFT_MAX_INPUT: u64 = 512 << 20; + +/// The error for a PhotoCraft bundle over [`PCRAFT_MAX_INPUT`]. +pub fn pcraft_too_large() -> std::io::Error { + std::io::Error::new(std::io::ErrorKind::InvalidData, "PhotoCraft bundle exceeds the 512 MiB input limit") +} + /// Host services (file access) injected by the frontend. pub trait Services: Send + Sync { fn read_file(&self, path: &str) -> std::io::Result>; + /// A PhotoCraft bundle's bytes: like [`Services::read_file`], but a file over + /// [`PCRAFT_MAX_INPUT`] is an error. Other files read with `read_file` have no such limit. + fn read_pcraft(&self, path: &str) -> std::io::Result> { + if self.stamp(path).is_some_and(|(len, _)| len > PCRAFT_MAX_INPUT) { + return Err(pcraft_too_large()); + } + let bytes = self.read_file(path)?; + if bytes.len() as u64 > PCRAFT_MAX_INPUT { + return Err(pcraft_too_large()); + } + Ok(bytes) + } fn write_file(&self, path: &str, data: &[u8]) -> std::io::Result<()>; /// Whether a file exists (the background footage check after open). fn exists(&self, path: &str) -> bool { @@ -53,42 +73,39 @@ impl Services for FsServices { /// Refuses what isn't a regular file: a project can name `/dev/zero` or a FIFO, and reading /// those never ends (#2134). fn read_file(&self, path: &str) -> std::io::Result> { - use std::io::{Read, Seek}; - let mut file = std::fs::File::open(path)?; - let meta = file.metadata()?; - if !meta.is_file() { - return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{path} is not a file"))); - } - // A renamed PhotoCraft bundle must be bounded before allocating its whole input. - // Bound ZIP containers by their signature even when manifest.json is a later entry. - let mut head = [0u8; 4]; - if meta.len() >= 4 { - file.read_exact(&mut head)?; - file.rewind()?; - } - let limited = head == *b"PK\x03\x04" || path.to_ascii_lowercase().ends_with(".pcraft"); - const MAX_BUNDLE: u64 = 512 << 20; - if limited && meta.len() > MAX_BUNDLE { - return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "ZIP/PhotoCraft bundle exceeds the 512 MiB input limit")); - } - let mut bytes = Vec::new(); - // A sparse file can claim far more than memory: an error, not an abort. - bytes.try_reserve_exact(usize::try_from(meta.len()).unwrap_or(usize::MAX)).map_err(|e| std::io::Error::new(std::io::ErrorKind::OutOfMemory, e))?; - if limited { - file.take(MAX_BUNDLE + 1).read_to_end(&mut bytes)?; - if bytes.len() as u64 > MAX_BUNDLE { - return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "ZIP/PhotoCraft bundle grew beyond the 512 MiB input limit")); - } - } else { - file.read_to_end(&mut bytes)?; - } - Ok(bytes) + read_regular_file(path, None) + } + /// Checks the size before reserving the buffer, and stops reading a file that grows past + /// the limit while it is read. + fn read_pcraft(&self, path: &str) -> std::io::Result> { + read_regular_file(path, Some(PCRAFT_MAX_INPUT)) } fn write_file(&self, path: &str, data: &[u8]) -> std::io::Result<()> { config::atomic_write(std::path::Path::new(path), data) } } +/// A regular file's bytes; with `limit`, a file larger than `limit` bytes is an error. +fn read_regular_file(path: &str, limit: Option) -> std::io::Result> { + use std::io::Read; + let file = std::fs::File::open(path)?; + let meta = file.metadata()?; + if !meta.is_file() { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{path} is not a file"))); + } + if limit.is_some_and(|max| meta.len() > max) { + return Err(pcraft_too_large()); + } + let mut bytes = Vec::new(); + // A sparse file can claim far more than memory: an error, not an abort. + bytes.try_reserve_exact(usize::try_from(meta.len()).unwrap_or(usize::MAX)).map_err(|e| std::io::Error::new(std::io::ErrorKind::OutOfMemory, e))?; + file.take(limit.map_or(u64::MAX, |max| max + 1)).read_to_end(&mut bytes)?; + if limit.is_some_and(|max| bytes.len() as u64 > max) { + return Err(pcraft_too_large()); + } + Ok(bytes) +} + /// Imports media files into the project (implemented by the media layer). pub trait Importer: Send + Sync { /// Probe one file and return footage metadata. Image sequences are the engine's @@ -118,4 +135,21 @@ mod tests { assert_eq!(FsServices.read_file(&f.to_string_lossy()).unwrap(), b"data"); let _ = std::fs::remove_file(f); } + + /// Templates and dotLottie files are ZIP archives too: only PhotoCraft reads have the + /// 512 MiB input limit. The length is set without writing the data. + #[test] + fn only_photocraft_reads_have_the_input_limit() { + let f = std::env::temp_dir().join(format!("ec-services-large-{}.zip", std::process::id())); + std::fs::write(&f, b"PK\x03\x04").unwrap(); + std::fs::OpenOptions::new().write(true).open(&f).unwrap().set_len(super::PCRAFT_MAX_INPUT + 1).unwrap(); + let path = f.to_string_lossy(); + let error = FsServices.read_pcraft(&path).unwrap_err(); + assert!(error.to_string().contains("512 MiB input limit"), "{error}"); + let bytes = FsServices.read_file(&path).unwrap(); + assert_eq!(bytes.len() as u64, super::PCRAFT_MAX_INPUT + 1); + assert!(bytes.starts_with(b"PK\x03\x04")); + drop(bytes); + let _ = std::fs::remove_file(f); + } } diff --git a/crates/engine/src/tests/import_photocraft.rs b/crates/engine/src/tests/import_photocraft.rs index 58115fd71..1a198d75c 100644 --- a/crates/engine/src/tests/import_photocraft.rs +++ b/crates/engine/src/tests/import_photocraft.rs @@ -255,17 +255,15 @@ fn photocraft_bad_metadata_and_missing_layer_pixels_report_errors() { #[test] #[cfg(unix)] // Sparse length checks exercise the guard without writing half a GiB. fn photocraft_large_files_are_rejected_before_reading() { - for name in ["large-sparse.pcraft", "renamed-sparse.zip"] { - let path = fixture_bytes(name, b"PK\x03\x04".to_vec()); - std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_len((512 << 20) + 1).unwrap(); - assert!(effectcraft_media::probe(&path).unwrap_err().to_string().contains("512 MiB input limit")); - let mut s = Session::default(); - let before = s.project.items.len(); - let r = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); - assert_eq!(s.project.items.len(), before); - assert!(r["errors"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains("512 MiB input limit"))), "{r}"); - std::fs::remove_file(path).unwrap(); - } + let path = fixture_bytes("large-sparse.pcraft", b"PK\x03\x04".to_vec()); + std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_len((512 << 20) + 1).unwrap(); + assert!(effectcraft_media::probe(&path).unwrap_err().to_string().contains("512 MiB input limit")); + let mut s = Session::default(); + let before = s.project.items.len(); + let r = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); + assert_eq!(s.project.items.len(), before); + assert!(r["errors"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains("512 MiB input limit"))), "{r}"); + std::fs::remove_file(path).unwrap(); } #[test] diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index ad6b1442a..50d5f9e61 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -85,20 +85,17 @@ pub fn is_importable(path: &std::path::Path) -> bool { /// A whole file's bytes, refusing anything that isn't a regular file: a project can name /// `/dev/zero` or a FIFO as footage, and reading those never ends (#2134). pub(crate) fn read_regular_file(path: &std::path::Path) -> std::io::Result> { - use std::io::{Read, Seek}; + use std::io::Read; let mut file = std::fs::File::open(path)?; let meta = file.metadata()?; if !meta.is_file() { return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{} is not a file", path.display()))); } - let mut head = [0u8; 4]; - if meta.len() >= 4 { - file.read_exact(&mut head)?; - file.rewind()?; - } - let pcraft = ext_of(path) == "pcraft" || head == *b"PK\x03\x04"; + // Only `.pcraft` files are limited before the read; other ZIP-based files are not. + // A renamed bundle is checked after its read, before it is parsed. + let pcraft = ext_of(path) == "pcraft"; if pcraft && meta.len() > pcraft::MAX_INPUT_BYTES { - return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "ZIP/PhotoCraft bundle exceeds the 512 MiB input limit")); + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "PhotoCraft bundle exceeds the 512 MiB input limit")); } let mut bytes = Vec::new(); // A sparse file can claim far more than memory: an error, not an abort. @@ -150,4 +147,18 @@ mod read_tests { assert_eq!(super::read_regular_file(&f).unwrap(), b"abc"); let _ = std::fs::remove_file(f); } + + /// Templates and dotLottie files are ZIP archives too: only `.pcraft` files have the + /// 512 MiB input limit. The length is set without writing the data. + #[test] + fn large_zip_files_other_than_photocraft_are_read_whole() { + let f = std::env::temp_dir().join(format!("ec-read-large-{}.zip", std::process::id())); + std::fs::write(&f, b"PK\x03\x04").unwrap(); + std::fs::OpenOptions::new().write(true).open(&f).unwrap().set_len(crate::pcraft::MAX_INPUT_BYTES + 1).unwrap(); + let bytes = super::read_regular_file(&f).unwrap(); + assert_eq!(bytes.len() as u64, crate::pcraft::MAX_INPUT_BYTES + 1); + assert!(bytes.starts_with(b"PK\x03\x04")); + drop(bytes); + let _ = std::fs::remove_file(f); + } } diff --git a/docs/photocraft-import.md b/docs/photocraft-import.md index 0599fcfbf..20ebf49b2 100644 --- a/docs/photocraft-import.md +++ b/docs/photocraft-import.md @@ -20,7 +20,7 @@ Use `"importAs":"composition"` for layers. Import uses the existing still-footag ## Limits -PhotoCraft input is limited to 512 MiB. Whole-file ZIP reads share that limit, checked from the archive signature before allocating the input, so renaming a bundle does not bypass it. Decoded composites are limited to 16,777,216 pixels and layer canvases to 12,582,912 pixels. Composition import also respects EffectCraft's composition size limit, allows up to 4,096 layers and 16 levels of group nesting, and rejects unsupported CMYK or Lab layer data. Footage can still import a supported saved composite when the document's layers exceed those limits. +PhotoCraft input is limited to 512 MiB. A `.pcraft` file is checked before it is read. A PhotoCraft bundle with another extension is checked after it is read and before it is parsed. Other ZIP-based files, such as templates and dotLottie files, do not have this limit. Decoded composites are limited to 16,777,216 pixels and layer canvases to 12,582,912 pixels. Composition import also respects EffectCraft's composition size limit, allows up to 4,096 layers and 16 levels of group nesting, and rejects unsupported CMYK or Lab layer data. Footage can still import a supported saved composite when the document's layers exceed those limits. Unsupported layer kinds are skipped with a message naming the layer. A nonempty document with no supported pixel layers cannot import as a composition; the error recommends Footage. Invalid input reports an error before adding a composition. From 0b8c5846e6b77875664b462a158d16e1736aa13b Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Wed, 4 Nov 2026 07:54:00 +0100 Subject: [PATCH 08/38] Measure the selected-key offset from the stored key and cover unselected, muted and vector keys (#1963) --- crates/engine/src/cmd/prop.rs | 6 ++- crates/engine/src/tests/set_selected_keys.rs | 43 ++++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/prop.rs b/crates/engine/src/cmd/prop.rs index 501860840..9c2515dd8 100644 --- a/crates/engine/src/cmd/prop.rs +++ b/crates/engine/src/cmd/prop.rs @@ -513,9 +513,11 @@ fn set(s: &mut Session, p: &Value) -> Result { } let target = at.unwrap_or(lt); // After Effects: editing the value with the CTI on one of several selected keys moves all - // the selected keys by the same change; between keys, or at an explicit other time, it only edits that key. + // the selected keys by the same change, measured from the stored key (even a muted one); between keys, or at an explicit + // other time, it only edits that key. if selected.len() > 1 && target == lt && selected.contains(&target) && key_at(&pr.keys, target).is_some() && nv.interpolates() { - let delta: Vec = nv.components().iter().zip(pr.value_at(target).components()).map(|(n, o)| n - o).collect(); + let stored = key_at(&pr.keys, target).and_then(|i| pr.keys.get(i)).map(|k| k.value.components()).unwrap_or_default(); + let delta: Vec = nv.components().iter().zip(&stored).map(|(n, o)| n - o).collect(); let range = if let effectcraft_project::ParamUi::Slider { min, max, .. } = pr.ui { Some((min, max)) } else { None }; for k in pr.keys.iter_mut().filter(|k| k.time != target && selected.contains(&k.time)) { let moved: Vec = k.value.components().iter().zip(&delta).map(|(c, d)| c + d).collect(); diff --git a/crates/engine/src/tests/set_selected_keys.rs b/crates/engine/src/tests/set_selected_keys.rs index 226ed6ba0..8c85f4dbe 100644 --- a/crates/engine/src/tests/set_selected_keys.rs +++ b/crates/engine/src/tests/set_selected_keys.rs @@ -60,3 +60,46 @@ fn explicit_time_off_the_playhead_only_edits_that_key() { s.execute_checked("prop.set", json!({"layer": layer, "path": "transform/opacity", "time": 1.0, "value": 40})).unwrap(); assert_eq!(values(&s, layer, prop), vec![0.0, 40.0, 50.0]); } + +#[test] +fn value_edit_leaves_unselected_keys_unchanged() { + let (mut s, layer, prop) = setup(); + let times = s.active_comp().unwrap().layer(LayerId(layer)).unwrap().props.find(prop).unwrap().keys.iter().take(2).map(|k| k.time).collect::>(); + s.state.selected_keys = times.into_iter().map(|time| KeyRef { layer: LayerId(layer), prop, time }).collect(); + s.execute_checked("time.set", json!({"time": 1.0})).unwrap(); + s.execute_checked("prop.set", json!({"layer": layer, "path": "transform/opacity", "value": 40})).unwrap(); + assert_eq!(values(&s, layer, prop), vec![15.0, 40.0, 50.0]); +} + +#[test] +fn offset_is_measured_from_a_muted_target_key() { + let mut s = Session::default(); + s.execute_checked("comp.new", json!({"width": 64, "height": 64, "frameRate": 30, "duration": 4})).unwrap(); + let layer = s.execute_checked("layer.newSolid", json!({"name": "Box", "color": "#fff"})).unwrap()["layer"].as_u64().unwrap(); + for (t, v) in [(0, 0), (1, 10), (2, 50)] { + s.execute_checked("prop.addKey", json!({"layer": layer, "path": "transform/opacity", "time": t, "value": v})).unwrap(); + } + let prop = s.active_comp().unwrap().layer(LayerId(layer)).unwrap().props.prop("transform/opacity").unwrap().uid; + s.execute_checked("keys.select", json!({"keys": [{"layer": layer, "path": "transform/opacity", "time": 1.0}]})).unwrap(); + s.execute_checked("keys.setMuted", json!({"muted": true})).unwrap(); + select_all(&mut s, layer, prop); + s.execute_checked("time.set", json!({"time": 1.0})).unwrap(); + s.execute_checked("prop.set", json!({"layer": layer, "path": "transform/opacity", "value": 40})).unwrap(); + assert_eq!(values(&s, layer, prop), vec![30.0, 40.0, 80.0]); +} + +#[test] +fn value_edit_offsets_every_component_of_a_vector() { + let mut s = Session::default(); + s.execute_checked("comp.new", json!({"width": 64, "height": 64, "frameRate": 30, "duration": 4})).unwrap(); + let layer = s.execute_checked("layer.newSolid", json!({"name": "Box", "color": "#fff"})).unwrap()["layer"].as_u64().unwrap(); + for (t, v) in [(0, [10, 20]), (1, [20, 40]), (2, [30, 60])] { + s.execute_checked("prop.addKey", json!({"layer": layer, "path": "transform/position", "time": t, "value": v})).unwrap(); + } + let prop = s.active_comp().unwrap().layer(LayerId(layer)).unwrap().props.prop("transform/position").unwrap().uid; + select_all(&mut s, layer, prop); + s.execute_checked("time.set", json!({"time": 1.0})).unwrap(); + s.execute_checked("prop.set", json!({"layer": layer, "path": "transform/position", "value": [25, 45]})).unwrap(); + let keys = s.active_comp().unwrap().layer(LayerId(layer)).unwrap().props.find(prop).unwrap().keys.iter().map(|k| k.value.as_vec2()).collect::>(); + assert_eq!(keys, vec![[15.0, 25.0], [25.0, 45.0], [35.0, 65.0]]); +} From 87d9126e7049f4ce5587dbff99784bc0f8000b6e Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Wed, 4 Nov 2026 07:58:03 +0100 Subject: [PATCH 09/38] Test that one undo restores every offset selected key (#1963) --- crates/engine/src/tests/set_selected_keys.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/engine/src/tests/set_selected_keys.rs b/crates/engine/src/tests/set_selected_keys.rs index 8c85f4dbe..03ce6b2dd 100644 --- a/crates/engine/src/tests/set_selected_keys.rs +++ b/crates/engine/src/tests/set_selected_keys.rs @@ -34,6 +34,16 @@ fn value_edit_on_a_selected_key_offsets_all_selected_keys() { assert_eq!(values(&s, layer, prop), vec![15.0, 40.0, 65.0]); } +#[test] +fn one_undo_restores_every_offset_key() { + let (mut s, layer, prop) = setup(); + select_all(&mut s, layer, prop); + s.execute_checked("time.set", json!({"time": 1.0})).unwrap(); + s.execute_checked("prop.set", json!({"layer": layer, "path": "transform/opacity", "value": 40})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(values(&s, layer, prop), vec![0.0, 25.0, 50.0]); +} + #[test] fn offset_selected_keys_stay_in_the_slider_range() { let (mut s, layer, prop) = setup(); From de83c004edd4604fb91ee52c3fc7718869ff5c1d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 17:33:40 +0100 Subject: [PATCH 10/38] Camera tools: After Effects' variants of Orbit, Pan and Dolly Fixes #2586. The Tools bar's Orbit, Pan and Dolly slots now hold After Effects' eight camera tools, picked from each slot's flyout (Alt-click cycles; C, 1, 2 and 3 keep the variant last picked): - Orbit Around Cursor / Around Scene / Around Camera POI - Pan Under Cursor / Pan Camera POI - Dolly Towards Cursor / Dolly to Cursor / Dolly to Camera POI camera.orbit, camera.pan and camera.dolly take a `mode` and the point it needs (`cursor` in comp pixels, or a resolved world `point`) and return the world pivot they used, which the viewer keeps for the rest of the drag. The cursor variants now really use the point under the cursor (the nearest visible 3D layer the ray hits, else the point at the depth of the point of interest); before, all three worked about the point of interest. Without `mode` the commands behave as before. A parented camera picks its point in world space and moves in its parent's space. The camera math is pure (Rig::orbit_about, pan_at, dolly_towards, pixel_ray, point_under, bounds_center) and never writes a non-finite camera; Dolly Towards Cursor keeps going past its point during a drag, and Dolly to Camera POI no longer backs off when closer than 1 px. --- crates/engine/src/cmd/three_d.rs | 187 ++++++++++++++++++-- crates/engine/src/tests/three_d.rs | 98 ++++++++++ crates/render/src/three_d/camera.rs | 139 ++++++++++++++- crates/render/src/three_d/tests.rs | 171 ++++++++++++++++++ crates/ui-egui/src/header.rs | 44 +++++ crates/ui-egui/src/i18n/ui.rs | 15 ++ crates/ui-egui/src/menus/commands.rs | 1 + crates/ui-egui/src/menus/invoke.rs | 24 ++- crates/ui-egui/src/menus/shortcuts.rs | 2 +- crates/ui-egui/src/menus/tests.rs | 94 ++++++++++ crates/ui-egui/src/panels/viewer.rs | 55 ++++-- crates/ui-egui/src/panels/viewer/gesture.rs | 4 + crates/ui-egui/src/state.rs | 71 ++++++-- docs/control-protocol.md | 8 + 14 files changed, 857 insertions(+), 56 deletions(-) diff --git a/crates/engine/src/cmd/three_d.rs b/crates/engine/src/cmd/three_d.rs index 009a33b2e..10c87e5e5 100644 --- a/crates/engine/src/cmd/three_d.rs +++ b/crates/engine/src/cmd/three_d.rs @@ -449,37 +449,170 @@ fn get_3d(s: &mut Session, p: &Value) -> Result { // ---------------------------------------------------------------- camera tools +#[derive(Clone, Copy)] enum ToolOp { Orbit(f64, f64), Pan(f64, f64), Dolly(f64), } +/// Which of After Effects' variants of a camera tool runs: what it turns about, pans at or +/// dollies towards (`mode` of `camera.orbit` / `camera.pan` / `camera.dolly`). +#[derive(Clone, Copy, PartialEq, Eq)] +enum ToolMode { + /// Without `mode`, `camera.dolly` keeps its original behaviour: a camera layer travels with + /// its point of interest along the view axis, a 3D view approaches its point of interest. + Plain, + /// The point under the cursor: Orbit Around Cursor, Pan Under Cursor, Dolly Towards Cursor. + Cursor, + /// Dolly to Cursor: towards the point under the cursor, stopping short of it. + ToCursor, + /// Orbit Around Scene: the centre of the comp's 3D layers. + Scene, + /// The camera's point of interest: Orbit Around Camera POI, Pan Camera POI, Dolly to Camera POI. + Target, +} + +impl ToolMode { + fn parse(p: &Value, op: ToolOp, cmd: &str) -> Result { + let Some(raw) = str_p(p, "mode") else { + return Ok(match op { + ToolOp::Dolly(_) => ToolMode::Plain, + _ => ToolMode::Target, + }); + }; + let k: String = raw.chars().filter(char::is_ascii_alphanumeric).collect::().to_ascii_lowercase(); + let mode = match (op, k.as_str()) { + (ToolOp::Orbit(..), "aroundcursor" | "cursor") => ToolMode::Cursor, + (ToolOp::Orbit(..), "aroundscene" | "scene") => ToolMode::Scene, + (ToolOp::Orbit(..), "aroundcamerapoi" | "camerapoi" | "aroundcameratarget" | "aroundtarget" | "cameratarget" | "target" | "poi") => { + ToolMode::Target + } + (ToolOp::Pan(..), "undercursor" | "cursor") => ToolMode::Cursor, + (ToolOp::Pan(..), "camerapoi" | "tocamerapoi" | "tocameratarget" | "totarget" | "cameratarget" | "target" | "poi") => ToolMode::Target, + (ToolOp::Dolly(_), "towardscursor" | "cursor") => ToolMode::Cursor, + (ToolOp::Dolly(_), "tocursor") => ToolMode::ToCursor, + (ToolOp::Dolly(_), "tocamerapoi" | "camerapoi" | "tocameratarget" | "totarget" | "cameratarget" | "target" | "poi") => ToolMode::Target, + _ => return Err(bad(cmd, format!("unknown mode `{raw}`"))), + }; + Ok(mode) + } +} + +/// The 3D layers that make up the scene at comp time `t`: active, visible (Video on, not a guide) +/// and with pixels (no cameras, lights or nulls). +fn scene_layers(comp: &Comp, t: Tick) -> Vec { + comp.layers.iter().filter(|l| l.is_active_at(t) && l.switches.three_d && l.switches.video && !l.switches.guide && l.source.is_av()).map(|l| l.id).collect() +} + +/// World-space rectangles of the layers' content at comp time `t` (for picking the point under +/// the cursor); layers without content bounds are left out. +fn layer_quads(s: &Session, cid: ItemId, ids: &[LayerId], t: Tick) -> Vec<[Vec3; 4]> { + let Some(comp) = s.project.comp(cid) else { return vec![] }; + let ctx = + EvalCtx { project: &s.project, comp_id: cid, comp, time: t, expr: s.expr.as_deref(), footage: None, property_overrides: &[], media_overrides: &[] }; + comp.layers + .iter() + .filter(|l| ids.contains(&l.id)) + .filter_map(|l| { + let m = ctx.world_matrix(l); + let [x0, y0, x1, y1] = effectcraft_render::content_bounds(&ctx, l)?; + Some([m.apply(vec3(x0, y0, 0.0)), m.apply(vec3(x1, y0, 0.0)), m.apply(vec3(x1, y1, 0.0)), m.apply(vec3(x0, y1, 0.0))]) + }) + .collect() +} + +/// The world point a camera tool turns about, pans at or dollies towards, for the modes that +/// need one: `point` when given (the UI resolves it once at mouse-down and sends it with every +/// step of the drag), else the scene's centre, or the point under `cursor` (comp pixels; default +/// the comp's centre) as `cam` sees it, falling back to the depth of `poi`. +fn tool_pivot(s: &Session, cid: ItemId, p: &Value, mode: ToolMode, cam: &camera::CameraState, poi: Vec3, t: Tick) -> Option { + if matches!(mode, ToolMode::Plain | ToolMode::Target) { + return None; + } + if let Some(pt) = v3_p(p, "point").map(Vec3::from).filter(|v| v.x.is_finite() && v.y.is_finite() && v.z.is_finite()) { + return Some(pt); + } + let comp = s.project.comp(cid)?; + let (w, h) = (comp.width as f64, comp.height as f64); + let ids = scene_layers(comp, t); + if mode == ToolMode::Scene { + let pts = layer_points(s, cid, &ids, t); + return Some(camera::bounds_center(&pts).unwrap_or(vec3(w / 2.0, h / 2.0, 0.0))); + } + let px = v3_p(p, "cursor").map(|c| [c[0], c[1]]).filter(|c| c[0].is_finite() && c[1].is_finite()).unwrap_or([w / 2.0, h / 2.0]); + Some(camera::point_under(cam, w, h, px, &layer_quads(s, cid, &ids, t), poi)) +} + fn camera_tool(s: &mut Session, p: &Value, op: ToolOp, cmd: &str, label: &str) -> Result { let cid = comp_id(s, p)?; let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone(); let (w, h) = (comp.width as f64, comp.height as f64); let cur = s.state.views3d.get(&cid).map(|v| v.current).unwrap_or_default(); - let apply = |r: &mut Rig, layer: bool| match op { - ToolOp::Orbit(yaw, pitch) => r.orbit(yaw, pitch), - ToolOp::Pan(dx, dy) => r.pan(dx, dy), - ToolOp::Dolly(a) => r.dolly(a, layer), - }; - if cur != View3D::ActiveCamera { - let vs = views(s, cid); - let vc = vs.cam(cur, w, h); - let mut r = Rig::from_view(&vc); - apply(&mut r, false); - let nc = ViewCam { eye: camera::arr(r.eye), poi: camera::arr(r.poi), zoom: r.zoom, ..vc }; - vs.cams.insert(cur, nc); - return Ok(json!({"view": cur.id(), "eye": nc.eye, "poi": nc.poi, "zoom": nc.zoom})); - } + let mode = ToolMode::parse(p, op, cmd)?; let t = s.state.times.get(&cid).copied().unwrap_or(Tick::ZERO); + // One step of the tool; a step that would leave a non-finite camera is dropped. + let apply = |r: &mut Rig, layer: bool, pivot: Option, mode: ToolMode| { + let before = *r; + let at = pivot.unwrap_or(r.poi); + match (op, mode) { + (ToolOp::Orbit(yaw, pitch), ToolMode::Cursor | ToolMode::Scene | ToolMode::ToCursor) => r.orbit_about(at, yaw, pitch), + (ToolOp::Orbit(yaw, pitch), _) => r.orbit(yaw, pitch), + (ToolOp::Pan(dx, dy), ToolMode::Cursor | ToolMode::Scene | ToolMode::ToCursor) => r.pan_at(dx, dy, at), + (ToolOp::Pan(dx, dy), _) => r.pan(dx, dy), + (ToolOp::Dolly(a), ToolMode::Plain) => r.dolly(a, layer), + (ToolOp::Dolly(a), ToolMode::Target) => r.dolly(a, false), + (ToolOp::Dolly(a), ToolMode::Cursor | ToolMode::Scene) => r.dolly_towards(a, at, false), + (ToolOp::Dolly(a), ToolMode::ToCursor) => r.dolly_towards(a, at, true), + } + if !r.is_finite() { + *r = before; + } + }; + let pivot_json = |pv: Option| pv.map(camera::arr).map_or(Value::Null, |a| json!(a)); + if cur != View3D::ActiveCamera { + let vc = views(s, cid).cam(cur, w, h); + let mut r = Rig::from_view(&vc); + let pivot = tool_pivot(s, cid, p, mode, &vc.state(), r.poi, t); + apply(&mut r, false, pivot, mode); + let nc = ViewCam { eye: camera::arr(r.eye), poi: camera::arr(r.poi), zoom: r.zoom, ..vc }; + views(s, cid).cams.insert(cur, nc); + return Ok(json!({"view": cur.id(), "eye": nc.eye, "poi": nc.poi, "zoom": nc.zoom, "pivot": pivot_json(pivot)})); + } let cam = match p.get("layer") { Some(v) => super::resolve_layer(&comp, v).filter(|id| comp.layer(*id).is_some_and(|l| l.is_camera())), None => comp.active_camera(t).map(|l| l.id), } .ok_or_else(|| bad(cmd, "the comp has no active camera layer (Layer ▸ New ▸ Camera), or switch to a custom 3D view"))?; + // The point under the cursor as the camera layer shows it, in world space (returned, and + // sent back by the viewer as `point`) and in the camera's parent space (what the rig edits). + let (pivot, local_pivot) = match comp.layer(cam) { + Some(l) if !matches!(mode, ToolMode::Plain | ToolMode::Target) => { + let ctx = EvalCtx { + project: &s.project, + comp_id: cid, + comp: &comp, + time: t, + expr: s.expr.as_deref(), + footage: None, + property_overrides: &[], + media_overrides: &[], + }; + let state = camera::layer_camera(&ctx, l); + let pw = camera::parent_world(&ctx, l); + let poi = match get_at(l, "transform/poi", t) { + Some(v) if camera::is_two_node(l) => pw.apply(Vec3::from(v.as_vec3())), + _ => state.eye + state.forward() * state.zoom, + }; + let world = tool_pivot(s, cid, p, mode, &state, poi, t); + let local = world.and_then(|w| pw.inverse().map(|m| m.apply(w))).filter(|v| v.x.is_finite() && v.y.is_finite() && v.z.is_finite()); + (world, local) + } + _ => (None, None), + }; + // A parent that cannot be inverted leaves no pivot in the camera's space: work about its + // point of interest instead. + let mode = if pivot.is_some() && local_pivot.is_none() { ToolMode::Target } else { mode }; let merge = merge_p(p).map(str::to_string); let r = s.edit(label, merge.as_deref(), |proj, _| { let l = layer_mut(proj, cid, cam)?; @@ -496,7 +629,7 @@ fn camera_tool(s: &mut Session, p: &Value, op: ToolOp, cmd: &str, label: &str) - pos + fwd * zoom }; let mut rig = Rig { eye: pos, poi, zoom, ortho: false }; - apply(&mut rig, true); + apply(&mut rig, true, local_pivot, mode); set_at(l, "transform/position", t, KV::Vec3(camera::arr(rig.eye))); if two { set_at(l, "transform/poi", t, KV::Vec3(camera::arr(rig.poi))); @@ -505,7 +638,7 @@ fn camera_tool(s: &mut Session, p: &Value, op: ToolOp, cmd: &str, label: &str) - set_at(l, "transform/rotationX", t, KV::Scalar(0.0)); set_at(l, "transform/rotationY", t, KV::Scalar(0.0)); } - Ok(json!({"layer": cam.0, "position": camera::arr(rig.eye), "poi": camera::arr(rig.poi)})) + Ok(json!({"layer": cam.0, "position": camera::arr(rig.eye), "poi": camera::arr(rig.poi), "pivot": pivot_json(pivot)})) })?; Ok(r) } @@ -767,12 +900,28 @@ pub fn specs() -> Vec { "Orbit Camera", [], None, - "{yaw|dx deg, pitch|dy deg, layer?, merge?} — current 3D view (camera layer in Active Camera)", + "{yaw|dx deg, pitch|dy deg, mode?: aroundCursor|aroundScene|aroundCameraPoi (default; alias aroundCameraTarget), cursor? [x,y] comp px, point? [x,y,z] pivot, layer?, merge?} — current 3D view (camera layer in Active Camera); returns the pivot used", has_comp, orbit ), - cmd!("camera.pan", "Pan Camera", [], None, "{dx, dy (comp px), layer?, merge?}", has_comp, pan), - cmd!("camera.dolly", "Dolly Camera", [], None, "{amount (px, + = forward), layer?, merge?}", has_comp, dolly), + cmd!( + "camera.pan", + "Pan Camera", + [], + None, + "{dx, dy (comp px), mode?: underCursor|cameraPoi (default; alias toCameraTarget), cursor? [x,y], point? [x,y,z], layer?, merge?}", + has_comp, + pan + ), + cmd!( + "camera.dolly", + "Dolly Camera", + [], + None, + "{amount (px, + = forward), mode?: towardsCursor|toCursor|toCameraPoi (alias toCameraTarget; default: along the view axis), cursor? [x,y], point? [x,y,z], layer?, merge?}", + has_comp, + dolly + ), query!("view.get3D", "3D View State", "{comp?} → current 3D view, view camera, active camera layer, lights", get_3d), ] } diff --git a/crates/engine/src/tests/three_d.rs b/crates/engine/src/tests/three_d.rs index 5b5af594d..4520c8fcc 100644 --- a/crates/engine/src/tests/three_d.rs +++ b/crates/engine/src/tests/three_d.rs @@ -325,6 +325,104 @@ fn camera_tools_edit_active_camera_with_undo() { assert!(o[1].abs() > 1.0, "{o:?}"); } +fn dist3(a: [f64; 3], b: [f64; 3]) -> f64 { + ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt() +} + +fn arr3(v: &serde_json::Value) -> [f64; 3] { + let a = v.as_array().unwrap_or_else(|| panic!("not a point: {v}")); + [a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()] +} + +/// Orbit Around Scene (#2586) turns a 3D view about the centre of the comp's 3D layers, not +/// about the view's point of interest. +#[test] +fn orbit_around_scene_turns_the_view_about_the_layers_centre() { + let mut s = session(); + let cid = s.active_comp_id().unwrap(); + let id = s.execute("layer.newSolid", json!({"width": 100, "height": 100})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layer": id, "switch": "threeD", "value": true})).unwrap(); + s.execute("prop.set", json!({"layer": id, "path": "transform/position", "value": [500, 100, 300]})).unwrap(); + s.execute("view.3d.custom1", json!({})).unwrap(); + let cam0 = s.state.views3d[&cid].cam(View3D::Custom1, 640.0, 360.0); + let r = s.execute("camera.orbit", json!({"yaw": 25, "mode": "aroundScene"})).unwrap(); + let pivot = arr3(&r["pivot"]); + assert!(dist3(pivot, [500.0, 100.0, 300.0]) < 1e-6, "{pivot:?}"); + let cam1 = s.state.views3d[&cid].cam(View3D::Custom1, 640.0, 360.0); + assert!(dist3(cam1.poi, cam0.poi) > 1.0, "the point of interest goes round the scene too"); + assert!((dist3(cam1.eye, pivot) - dist3(cam0.eye, pivot)).abs() < 1e-6); + // Around Camera POI (the default; the old mode name still works) keeps the point of interest. + s.execute("camera.orbit", json!({"yaw": 25, "mode": "aroundCameraTarget"})).unwrap(); + assert!(dist3(s.state.views3d[&cid].cam(View3D::Custom1, 640.0, 360.0).poi, cam1.poi) < 1e-9); + assert!(s.execute("camera.orbit", json!({"yaw": 5, "mode": "sideways"})).is_err()); + assert!(s.execute("camera.pan", json!({"dx": 5, "mode": "aroundScene"})).is_err(), "Pan has no scene variant"); +} + +/// The cursor variants on a camera layer pick the point under the cursor on a 3D layer; +/// Dolly to Cursor and Dolly to Camera POI stop short of their point (#2586). +#[test] +fn cursor_and_target_camera_tools_on_a_camera_layer() { + let mut s = session(); + let id = s.execute("layer.newSolid", json!({"width": 640, "height": 360})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layer": id, "switch": "threeD", "value": true})).unwrap(); + let cam = s.execute("layer.newCamera", json!({})).unwrap()["layer"].as_u64().unwrap(); + let poi0 = prop(&s, cam, "transform/poi").as_vec3(); + // The cursor off centre picks a point on the solid (z = 0), not the point of interest. + let r = s.execute("camera.pan", json!({"dx": 0, "dy": 0, "mode": "underCursor", "cursor": [100, 60]})).unwrap(); + let pivot = arr3(&r["pivot"]); + assert!(pivot[2].abs() < 1e-6, "{pivot:?}"); + assert!(dist3(pivot, poi0) > 50.0, "{pivot:?}"); + // Dolly to Cursor: a long dolly ends just short of the point, with the aim kept. + let aim0 = { + let (p, q) = (prop(&s, cam, "transform/position").as_vec3(), prop(&s, cam, "transform/poi").as_vec3()); + [q[0] - p[0], q[1] - p[1], q[2] - p[2]] + }; + s.execute("camera.dolly", json!({"amount": 1.0e7, "mode": "toCursor", "point": pivot})).unwrap(); + let (p1, q1) = (prop(&s, cam, "transform/position").as_vec3(), prop(&s, cam, "transform/poi").as_vec3()); + assert!((dist3(p1, pivot) - 1.0).abs() < 1e-6, "{p1:?}"); + assert!(dist3([q1[0] - p1[0], q1[1] - p1[1], q1[2] - p1[2]], aim0) < 1e-6); + s.undo(); + // Dolly to Camera POI: the point of interest stays and the camera stops 1 px from it. + s.execute("camera.dolly", json!({"amount": 1.0e7, "mode": "toCameraTarget"})).unwrap(); + assert_eq!(prop(&s, cam, "transform/poi").as_vec3(), poi0); + assert!((dist3(prop(&s, cam, "transform/position").as_vec3(), poi0) - 1.0).abs() < 1e-6); + s.undo(); + // Orbit Around Cursor keeps both distances to the picked point. + let p0 = prop(&s, cam, "transform/position").as_vec3(); + s.execute("camera.orbit", json!({"yaw": 20, "pitch": -5, "mode": "aroundCursor", "point": pivot})).unwrap(); + let p2 = prop(&s, cam, "transform/position").as_vec3(); + assert!((dist3(p2, pivot) - dist3(p0, pivot)).abs() < 1e-6); + assert!(dist3(prop(&s, cam, "transform/poi").as_vec3(), poi0) > 1.0); +} + +/// A camera parented to a moved and turned null: the tools pick their point in world space and +/// move the camera about it, converting into the camera's parent space (#2586). +#[test] +fn camera_tools_on_a_parented_camera_use_the_world_point() { + let mut s = session(); + let id = s.execute("layer.newSolid", json!({"width": 100, "height": 100})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layer": id, "switch": "threeD", "value": true})).unwrap(); + s.execute("prop.set", json!({"layer": id, "path": "transform/position", "value": [400, 120, 200]})).unwrap(); + let parent = s.execute("layer.newNull", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layer": parent, "switch": "threeD", "value": true})).unwrap(); + s.execute("prop.set", json!({"layer": parent, "path": "transform/position", "value": [150, -60, 250]})).unwrap(); + s.execute("prop.set", json!({"layer": parent, "path": "transform/rotationY", "value": 30})).unwrap(); + s.execute("prop.set", json!({"layer": parent, "path": "transform/rotationX", "value": 15})).unwrap(); + let cam = s.execute("layer.newCamera", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setParent", json!({"layers": [cam], "parent": parent})).unwrap(); + let world_eye = |s: &mut Session| arr3(&s.execute("view.get3D", json!({})).unwrap()["camera"]["eye"]); + let e0 = world_eye(&mut s); + let r = s.execute("camera.orbit", json!({"yaw": 25, "pitch": -10, "mode": "aroundScene"})).unwrap(); + let pivot = arr3(&r["pivot"]); + assert!(dist3(pivot, [400.0, 120.0, 200.0]) < 1e-6, "the scene centre is a world point: {pivot:?}"); + let e1 = world_eye(&mut s); + assert!(dist3(e1, e0) > 10.0); + assert!((dist3(e1, pivot) - dist3(e0, pivot)).abs() < 1e-6, "{e0:?} → {e1:?} about {pivot:?}"); + s.undo(); + s.execute("camera.dolly", json!({"amount": 1.0e7, "mode": "toCursor", "point": pivot})).unwrap(); + assert!((dist3(world_eye(&mut s), pivot) - 1.0).abs() < 1e-6); +} + #[test] fn demo_has_3d_showcase() { let mut s = Session::default(); diff --git a/crates/render/src/three_d/camera.rs b/crates/render/src/three_d/camera.rs index 6aee50a78..9452a6bf1 100644 --- a/crates/render/src/three_d/camera.rs +++ b/crates/render/src/three_d/camera.rs @@ -577,11 +577,19 @@ impl Rig { pub fn from_view(v: &ViewCam) -> Rig { Rig { eye: Vec3::from(v.eye), poi: Vec3::from(v.poi), zoom: v.zoom, ortho: v.ortho } } + /// The camera this rig looks through (screen-down hint world Y, as the tools use). + pub fn state(&self) -> CameraState { + CameraState { view: basis_view(self.eye, self.poi - self.eye, vec3(0.0, 1.0, 0.0)), eye: self.eye, zoom: self.zoom, ortho: self.ortho, dof: None } + } fn frame(&self) -> (Vec3, Vec3, Vec3) { - let s = - CameraState { view: basis_view(self.eye, self.poi - self.eye, vec3(0.0, 1.0, 0.0)), eye: self.eye, zoom: self.zoom, ortho: self.ortho, dof: None }; + let s = self.state(); (s.forward(), s.right(), s.down()) } + /// Every coordinate and the zoom are finite numbers (a tool step that would leave NaN or + /// infinity behind is dropped instead of written into the camera). + pub fn is_finite(&self) -> bool { + [self.eye, self.poi].iter().all(|v| v.x.is_finite() && v.y.is_finite() && v.z.is_finite()) && self.zoom.is_finite() + } /// Orbit the eye around the point of interest: `yaw` about world Y, `pitch` about the /// camera's right axis (degrees). Pitch is limited short of straight up/down. pub fn orbit(&mut self, yaw: f64, pitch: f64) { @@ -621,8 +629,133 @@ impl Rig { self.poi += f * amount; } else { let dist = (self.poi - self.eye).length(); - let d = amount.min(dist - 1.0); + let d = amount.min((dist - 1.0).max(0.0)); self.eye += f * d; } } + /// Orbit Around Cursor / Orbit Around Scene: turn the whole camera (eye and point of + /// interest together) about `pivot`: `yaw` about world Y, `pitch` about the camera's + /// horizontal right axis (degrees, same senses as [`Rig::orbit`]). The pivot keeps its place + /// on screen and both distances to it; the view is limited short of straight up/down. + pub fn orbit_about(&mut self, pivot: Vec3, yaw: f64, pitch: f64) { + if self.ortho || !(pivot.x.is_finite() && pivot.y.is_finite() && pivot.z.is_finite()) { + return; + } + let off = self.eye - self.poi; + let dist = off.length(); + if !(dist.is_finite() && dist > 1e-9) { + return; + } + let cur = (off.y / dist).clamp(-1.0, 1.0).asin().to_degrees(); + let pitch = (cur + pitch).clamp(-89.0, 89.0) - cur; + let up = vec3(0.0, 1.0, 0.0); + let horiz = vec3(off.x, 0.0, off.z); + // Rotating about (horizontal offset × up) raises the eye's offset, as `orbit` does. + let axis = if horiz.length() > 1e-9 { horiz.normalize().cross(up).normalize() } else { self.frame().1 }; + let turn = |v: Vec3| rotate_about(rotate_about(v, axis, pitch), up, -yaw); + self.eye = pivot + turn(self.eye - pivot); + self.poi = pivot + turn(self.poi - pivot); + } + /// Pan Under Cursor: move the camera in its image plane so the world point `at` (the point + /// under the cursor) follows the drag of (`dx`, `dy`) comp pixels. Falls back to [`Rig::pan`] + /// (the point of interest's depth) when `at` is not in front of the camera. + pub fn pan_at(&mut self, dx: f64, dy: f64, at: Vec3) { + let (f, r, d) = self.frame(); + let depth = (at - self.eye).dot(f); + if self.ortho || !(depth.is_finite() && depth > 1e-6) { + self.pan(dx, dy); + return; + } + let k = depth / self.zoom.max(1e-9); + let delta = r * (-dx * k) + d * (-dy * k); + self.eye += delta; + self.poi += delta; + } + /// Dolly Towards Cursor (`stop_short` false) / Dolly to Cursor (`stop_short` true): move the + /// camera (eye and point of interest together, so its aim is kept) by `amount` pixels along + /// the line from the eye through `target`, the point under the cursor, which therefore keeps + /// its place on screen. Dolly to Cursor stops 1 px short of the target instead of passing it. + /// Orthographic views scale, as [`Rig::dolly`]. + pub fn dolly_towards(&mut self, amount: f64, target: Vec3, stop_short: bool) { + if self.ortho { + self.dolly(amount, false); + return; + } + let to = target - self.eye; + let dist = to.length(); + if !(dist.is_finite() && dist > 1e-9) { + // The eye sits on the target: nothing to approach (Towards Cursor goes straight on). + if !stop_short { + self.dolly(amount, true); + } + return; + } + // Once Dolly Towards Cursor has passed the point, the line through it still runs the same + // way: keep moving along the view, never back towards the point. + let dir = to / dist; + let dir = if !stop_short && dir.dot(self.frame().0) < 0.0 { -dir } else { dir }; + let d = if stop_short { amount.min((dist - 1.0).max(0.0)) } else { amount }; + self.eye += dir * d; + self.poi += dir * d; + } +} + +/// `v` turned by `deg` degrees about the unit `axis` (right-handed, Rodrigues). +fn rotate_about(v: Vec3, axis: Vec3, deg: f64) -> Vec3 { + let (s, c) = deg.to_radians().sin_cos(); + v * c + axis.cross(v) * s + axis * (axis.dot(v) * (1.0 - c)) +} + +/// The ray through comp pixel `px` of a `w`×`h` comp seen by `cam`: origin and direction. The +/// direction's component along the view axis is 1, so `origin + dir * z` is the ray's point at +/// view depth `z` (perspective and orthographic alike). +pub fn pixel_ray(cam: &CameraState, w: f64, h: f64, px: [f64; 2]) -> (Vec3, Vec3) { + let zoom = if cam.zoom.is_finite() && cam.zoom.abs() > 1e-9 { cam.zoom } else { 1e-9 }; + let (x, y) = ((px[0] - w * 0.5) / zoom, (px[1] - h * 0.5) / zoom); + let (f, r, d) = (cam.forward(), cam.right(), cam.down()); + if cam.ortho { (cam.eye + r * x + d * y, f) } else { (cam.eye, r * x + d * y + f) } +} + +/// The world point under comp pixel `px`: the nearest place the ray hits one of `quads` (planar +/// layer rectangles, four corners in order), else the ray's point at the view depth of +/// `fallback` (the point of interest), else `fallback` itself. +pub fn point_under(cam: &CameraState, w: f64, h: f64, px: [f64; 2], quads: &[[Vec3; 4]], fallback: Vec3) -> Vec3 { + let (o, dir) = pixel_ray(cam, w, h, px); + let finite = |v: Vec3| v.x.is_finite() && v.y.is_finite() && v.z.is_finite(); + let mut best: Option = None; + for q in quads { + let n = (q[1] - q[0]).cross(q[3] - q[0]); + let den = n.dot(dir); + if !(den.is_finite() && den.abs() > 1e-12) { + continue; + } + let t = n.dot(q[0] - o) / den; + if !(t.is_finite() && t > 1e-6) || best.is_some_and(|b| b <= t) { + continue; + } + let hit = o + dir * t; + let side = |i: usize| { + let (a, b) = (q[i % 4], q[(i + 1) % 4]); + (b - a).cross(hit - a).dot(n) + }; + let s = [side(0), side(1), side(2), side(3)]; + if s.iter().all(|v| *v >= -1e-9) || s.iter().all(|v| *v <= 1e-9) { + best = Some(t); + } + } + let at_depth = || { + let z = (fallback - o).dot(cam.forward()); + (z.is_finite() && z > 1e-6).then(|| o + dir * z) + }; + best.map(|t| o + dir * t).or_else(at_depth).filter(|p| finite(*p)).unwrap_or(fallback) +} + +/// The centre of the box around `points` (Orbit Around Scene's pivot); None without points. +pub fn bounds_center(points: &[Vec3]) -> Option { + let first = *points.first()?; + let (lo, hi) = points + .iter() + .fold((first, first), |(lo, hi), q| (vec3(lo.x.min(q.x), lo.y.min(q.y), lo.z.min(q.z)), vec3(hi.x.max(q.x), hi.y.max(q.y), hi.z.max(q.z)))); + let c = (lo + hi) * 0.5; + (c.x.is_finite() && c.y.is_finite() && c.z.is_finite()).then_some(c) } diff --git a/crates/render/src/three_d/tests.rs b/crates/render/src/three_d/tests.rs index 026929623..8fcd2d5b8 100644 --- a/crates/render/src/three_d/tests.rs +++ b/crates/render/src/three_d/tests.rs @@ -719,3 +719,174 @@ fn rig_orbit_keeps_distance_and_pan_moves_both() { let off = r.eye - r.poi; assert!(off.y.abs() / off.length() < 0.9999); } + +// ---- the eight camera tools (#2586): pivots of the Cursor / Scene / Camera POI variants + +const CW: f64 = 1920.0; +const CH: f64 = 1080.0; + +fn custom_rig() -> Rig { + Rig::from_view(&default_view_cam(View3D::Custom1, CW, CH)) +} + +fn screen(r: &Rig, p: Vec3) -> effectcraft_geom::Vec2 { + r.state().project(CW, CH, p).expect("in front of the camera") +} + +#[test] +fn orbit_around_camera_poi_is_orbit_about_the_poi() { + let (mut a, mut b) = (custom_rig(), custom_rig()); + a.orbit(25.0, -10.0); + b.orbit_about(b.poi, 25.0, -10.0); + assert!((a.eye - b.eye).length() < 1e-6, "{:?} vs {:?}", a.eye, b.eye); + assert!((a.poi - b.poi).length() < 1e-9); +} + +#[test] +fn orbit_around_a_pivot_keeps_it_on_screen_and_turns_the_whole_camera() { + let mut r = custom_rig(); + // A pivot well off the point of interest (the cursor over a layer, or the scene's centre). + let pivot = r.poi + vec3(300.0, -120.0, 400.0); + let (s0, de, dp, poi0) = (screen(&r, pivot), (r.eye - pivot).length(), (r.poi - pivot).length(), r.poi); + r.orbit_about(pivot, 30.0, -12.0); + let s1 = screen(&r, pivot); + assert!((s1.x - s0.x).abs() < 1e-6 && (s1.y - s0.y).abs() < 1e-6, "{s0:?} → {s1:?}"); + assert!(((r.eye - pivot).length() - de).abs() < 1e-6); + assert!(((r.poi - pivot).length() - dp).abs() < 1e-6); + // Unlike Orbit Around Camera POI, the point of interest goes round too. + assert!((r.poi - poi0).length() > 10.0); + // Pitch stops short of the poles; a pivot that is not a number leaves the camera alone. + r.orbit_about(pivot, 0.0, 500.0); + let off = r.eye - r.poi; + assert!(off.y.abs() / off.length() < 0.9999); + let before = r; + r.orbit_about(vec3(f64::NAN, 0.0, 0.0), 10.0, 10.0); + assert_eq!(r, before); +} + +#[test] +fn pan_under_cursor_keeps_the_grabbed_point_under_the_pointer() { + // A point nearer than the point of interest: Pan Camera POI moves it by less + // than the drag, Pan Under Cursor by exactly the drag. + let r0 = custom_rig(); + let at = r0.eye + (r0.poi - r0.eye) * 0.3 + vec3(40.0, 25.0, 0.0); + let s0 = screen(&r0, at); + let mut r = r0; + r.pan_at(30.0, -12.0, at); + let s1 = screen(&r, at); + assert!((s1.x - s0.x - 30.0).abs() < 1e-6 && (s1.y - s0.y + 12.0).abs() < 1e-6, "{s0:?} → {s1:?}"); + assert!(((r.eye - r.poi) - (r0.eye - r0.poi)).length() < 1e-9, "the aim is kept"); + let mut target = r0; + target.pan(30.0, -12.0); + let st = screen(&target, at); + assert!((st.x - s0.x - 30.0).abs() > 1.0, "Pan Camera POI scales by the POI depth"); + // A point behind the camera falls back to the point of interest's depth. + let mut back = r0; + back.pan_at(30.0, -12.0, r0.eye - (r0.poi - r0.eye)); + assert!((back.eye - target.eye).length() < 1e-9); +} + +#[test] +fn dolly_towards_and_to_cursor_move_along_the_cursor_ray() { + let r0 = custom_rig(); + let target = r0.poi + vec3(-200.0, 90.0, 150.0); + let (s0, d0) = (screen(&r0, target), (r0.eye - target).length()); + let mut r = r0; + r.dolly_towards(150.0, target, false); + let s1 = screen(&r, target); + assert!((s1.x - s0.x).abs() < 1e-6 && (s1.y - s0.y).abs() < 1e-6, "the point under the cursor stays put"); + assert!(((r.eye - target).length() - (d0 - 150.0)).abs() < 1e-6); + assert!(((r.eye - r.poi) - (r0.eye - r0.poi)).length() < 1e-9, "the aim is kept"); + // Dolly Towards Cursor goes on past the point; Dolly to Cursor stops just short of it. + let mut past = r0; + past.dolly_towards(d0 + 500.0, target, false); + assert!(((past.eye - target).length() - 500.0).abs() < 1e-6); + let mut to = r0; + to.dolly_towards(d0 + 500.0, target, true); + assert!(((to.eye - target).length() - 1.0).abs() < 1e-6); + to.dolly_towards(50.0, target, true); + assert!(((to.eye - target).length() - 1.0).abs() < 1e-6, "no further"); + // Backwards is not limited. + to.dolly_towards(-100.0, target, true); + assert!(((to.eye - target).length() - 101.0).abs() < 1e-6); +} + +/// A Dolly Towards Cursor drag is many small steps towards one point: past the point it keeps +/// going forward instead of turning back towards it. +#[test] +fn dolly_towards_cursor_keeps_going_past_the_point() { + let r0 = custom_rig(); + let target = r0.poi + vec3(-200.0, 90.0, 150.0); + let f = (r0.poi - r0.eye).normalize(); + let d0 = (r0.eye - target).length(); + let mut r = r0; + let mut last = r.eye.dot(f); + let steps = (d0 / 50.0) as usize + 40; + for _ in 0..steps { + r.dolly_towards(50.0, target, false); + let now = r.eye.dot(f); + assert!(now > last + 1.0, "the drag turned back at {:?}", r.eye); + last = now; + } + assert!((r.eye - target).length() > 1000.0, "well past the point"); +} + +#[test] +fn dolly_to_camera_poi_never_backs_off_when_closer_than_a_pixel() { + let mut r = custom_rig(); + let f = (r.poi - r.eye).normalize(); + r.eye = r.poi - f * 0.5; + let eye = r.eye; + r.dolly(10.0, false); + assert!((r.eye - eye).length() < 1e-12, "{:?}", r.eye); +} + +#[test] +fn camera_tools_never_produce_nan_cameras() { + let nan_free = |r: &Rig| assert!(r.is_finite(), "{r:?}"); + // Eye on the point of interest, zero zoom, and pivots / targets on the eye. + let mut r = Rig { eye: vec3(10.0, 20.0, 30.0), poi: vec3(10.0, 20.0, 30.0), zoom: 0.0, ortho: false }; + r.orbit(10.0, 10.0); + nan_free(&r); + r.orbit_about(r.eye, 10.0, 10.0); + nan_free(&r); + r.pan_at(5.0, 5.0, r.eye); + nan_free(&r); + r.dolly_towards(10.0, r.eye, false); + nan_free(&r); + r.dolly_towards(10.0, r.eye, true); + nan_free(&r); + r.dolly(10.0, false); + nan_free(&r); + // Looking straight down: orbiting about a pivot still has an axis to pitch about. + let mut down = Rig { eye: vec3(0.0, -500.0, 0.0), poi: Vec3::ZERO, zoom: 800.0, ortho: false }; + down.orbit_about(vec3(50.0, 0.0, 50.0), 20.0, -30.0); + nan_free(&down); + let cam = down.state(); + nan_free(&Rig { eye: super::camera::point_under(&cam, CW, CH, [10.0, 10.0], &[], down.poi), ..down }); +} + +#[test] +fn the_point_under_the_cursor_is_on_the_layer_it_hits() { + let r = Rig::from_view(&default_view_cam(View3D::Default, CW, CH)); + let cam = r.state(); + // A comp-sized layer at z = 0 maps 1:1 to the default camera's pixels. + let quad = [vec3(0.0, 0.0, 0.0), vec3(CW, 0.0, 0.0), vec3(CW, CH, 0.0), vec3(0.0, CH, 0.0)]; + let p = super::camera::point_under(&cam, CW, CH, [100.0, 200.0], &[quad], r.poi); + assert!((p - vec3(100.0, 200.0, 0.0)).length() < 1e-6, "{p:?}"); + // The nearer of two layers wins. + let near: [Vec3; 4] = quad.map(|c| c + vec3(0.0, 0.0, -300.0)); + let p = super::camera::point_under(&cam, CW, CH, [960.0, 540.0], &[quad, near], r.poi); + assert!((p.z + 300.0).abs() < 1e-6, "{p:?}"); + // Off every layer: the cursor's point at the depth of the point of interest. + let small = [vec3(0.0, 0.0, 0.0), vec3(10.0, 0.0, 0.0), vec3(10.0, 10.0, 0.0), vec3(0.0, 10.0, 0.0)]; + let off = r.poi + vec3(0.0, 0.0, 200.0); + let p = super::camera::point_under(&cam, CW, CH, [1500.0, 700.0], &[small], off); + assert!((cam.depth(p) - cam.depth(off)).abs() < 1e-6); + let s = cam.project(CW, CH, p).unwrap(); + assert!((s.x - 1500.0).abs() < 1e-6 && (s.y - 700.0).abs() < 1e-6, "{s:?}"); + // The scene's centre is the middle of the box around the points. + let c = super::camera::bounds_center(&[vec3(0.0, 0.0, 0.0), vec3(100.0, 50.0, -40.0), vec3(20.0, 10.0, 60.0)]).unwrap(); + assert!((c - vec3(50.0, 25.0, 10.0)).length() < 1e-12); + assert!(super::camera::bounds_center(&[]).is_none()); +} diff --git a/crates/ui-egui/src/header.rs b/crates/ui-egui/src/header.rs index 140a0bbaf..205c6b114 100644 --- a/crates/ui-egui/src/header.rs +++ b/crates/ui-egui/src/header.rs @@ -975,6 +975,50 @@ mod tests { assert!(!app.auto.elements.iter().any(|w| w.id == "tools.select.TypeVertical")); } + /// The Orbit, Pan and Dolly slots carry After Effects' variants of each camera tool, each + /// picked from the slot's flyout by its automation id (#2586). + #[test] + fn every_camera_tool_is_picked_from_its_flyout() { + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + let ctx = egui::Context::default(); + crate::theme::install(&ctx, &app.tokens, crate::i18n::language(&app)); + frame(&mut app, &ctx, 0.0, vec![]); + frame(&mut app, &ctx, 0.1, vec![]); + let center = |element: &crate::automation::Element| { + let [x, y, w, h] = element.rect; + egui::pos2(x + w / 2.0, y + h / 2.0) + }; + let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let picks = [ + (3, Tool::OrbitScene), + (3, Tool::OrbitTarget), + (3, Tool::Orbit), + (4, Tool::PanTarget), + (4, Tool::PanCamera), + (5, Tool::DollyToCursor), + (5, Tool::DollyTarget), + (5, Tool::Dolly), + ]; + let mut time = 1.0; + for (slot, tool) in picks { + let shown = app.ui.slot_tools[slot]; + let at = center(app.auto.elements.iter().find(|w| w.id == format!("tools.{shown:?}")).unwrap_or_else(|| panic!("no slot tools.{shown:?}"))); + // Press and hold opens the flyout. + frame(&mut app, &ctx, time, vec![egui::Event::PointerMoved(at), pointer(at, true)]); + frame(&mut app, &ctx, time + 0.36, vec![]); + frame(&mut app, &ctx, time + 0.4, vec![pointer(at, false)]); + frame(&mut app, &ctx, time + 0.45, vec![]); + let id = format!("tools.select.{tool:?}"); + let row = center(app.auto.elements.iter().find(|w| w.id == id).unwrap_or_else(|| panic!("no {id}"))); + frame(&mut app, &ctx, time + 0.6, vec![egui::Event::PointerMoved(row), pointer(row, true)]); + frame(&mut app, &ctx, time + 0.65, vec![pointer(row, false)]); + assert_eq!(app.ui.tool, tool, "{id}"); + assert_eq!(app.ui.slot_tools[slot], tool); + frame(&mut app, &ctx, time + 0.7, vec![]); + time += 1.0; + } + } + /// Alt/Option-click cycles a Tools-bar flyout slot without opening the menu. #[test] fn alt_click_cycles_the_type_slot() { diff --git a/crates/ui-egui/src/i18n/ui.rs b/crates/ui-egui/src/i18n/ui.rs index 15bf774f9..82da1b878 100644 --- a/crates/ui-egui/src/i18n/ui.rs +++ b/crates/ui-egui/src/i18n/ui.rs @@ -944,6 +944,11 @@ const JAPANESE: &[(&str, &str)] = &[ ("Orbit Around Cursor Tool", "カーソルのまわりを周回ツール"), ("Pan Under Cursor Tool", "カーソルの下でパンツール"), ("Dolly Towards Cursor Tool", "カーソルに向かってドリーツール"), + ("Orbit Around Scene Tool", "シーンのまわりを周回ツール"), + ("Orbit Around Camera POI Tool", "カメラ目標点のまわりを周回"), + ("Pan Camera POI Tool", "カメラの目標点にパンツール"), + ("Dolly to Cursor Tool", "カーソルにドリーツール"), + ("Dolly to Camera POI Tool", "カメラの目標点にドリーツール"), ("Rotation Tool", "回転ツール"), ("Pan Behind (Anchor Point) Tool", "アンカーポイントツール"), ("Rectangle Tool", "長方形ツール"), @@ -3230,6 +3235,11 @@ const SWEDISH: &[(&str, &str)] = &[ ("Orbit Around Cursor Tool", "Verktyg för att kretsa kring pekaren"), ("Pan Under Cursor Tool", "Verktyg för att panorera under pekaren"), ("Dolly Towards Cursor Tool", "Verktyget Dolly mot pekaren"), + ("Orbit Around Scene Tool", "Verktyg för att kretsa kring scenen"), + ("Orbit Around Camera POI Tool", "Verktyg för att kretsa kring kamerans intressepunkt"), + ("Pan Camera POI Tool", "Verktyg för att panorera kamerans intressepunkt"), + ("Dolly to Cursor Tool", "Verktyget Dolly till pekaren"), + ("Dolly to Camera POI Tool", "Verktyget Dolly till kamerans intressepunkt"), ("Rotation Tool", "Rotationsverktyg"), ("Pan Behind (Anchor Point) Tool", "Verktyg för att panorera bakom (ankarpunkt)"), ("Rectangle Tool", "Rektangelverktyg"), @@ -9954,6 +9964,11 @@ const FRENCH: &[(&str, &str)] = &[ ("Orbit Around Cursor Tool", "Outil Orbite autour du curseur"), ("Pan Under Cursor Tool", "Outil Panoramique sous le curseur"), ("Dolly Towards Cursor Tool", "Outil Travelling vers le curseur"), + ("Orbit Around Scene Tool", "Outil Orbite autour de la scène"), + ("Orbit Around Camera POI Tool", "Outil Orbite autour du point ciblé de la caméra"), + ("Pan Camera POI Tool", "Outil Panoramique du point ciblé de la caméra"), + ("Dolly to Cursor Tool", "Outil Travelling jusqu'au curseur"), + ("Dolly to Camera POI Tool", "Outil Travelling jusqu'au point ciblé de la caméra"), ("Rotation Tool", "Outil Rotation"), ("Pan Behind (Anchor Point) Tool", "Outil Déplacement derrière (point d’ancrage)"), ("Rectangle Tool", "Outil Rectangle"), diff --git a/crates/ui-egui/src/menus/commands.rs b/crates/ui-egui/src/menus/commands.rs index c162bbd3a..8817b94d6 100644 --- a/crates/ui-egui/src/menus/commands.rs +++ b/crates/ui-egui/src/menus/commands.rs @@ -92,6 +92,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[ uic!("tool.selection", "Selection Tool", [], Some("V")), uic!("tool.hand", "Hand Tool", [], Some("H")), uic!("tool.zoom", "Zoom Tool", [], Some("Z")), + // 1, 2 and 3 select the Orbit, Pan and Dolly slots' variant as the slot last showed it. uic!("tool.orbit", "Orbit Tool", [], Some("1")), uic!("tool.panCamera", "Pan Camera Tool", [], Some("2")), uic!("tool.dolly", "Dolly Tool", [], Some("3")), diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 0c7573c91..e38c74d4f 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -334,13 +334,23 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V return frontend(app, ctx, "window.workspace", json!({"name": ws})); } if let Some(t) = id.strip_prefix("tool.") { - // C cycles through the camera tools. - if t == "camera" { - let tools = [Tool::Orbit, Tool::PanCamera, Tool::Dolly]; - let next = match tools.iter().position(|x| *x == app.ui.tool) { - Some(i) => tools[(i + 1) % tools.len()], - None => Tool::Orbit, - }; + // The camera tools: the Orbit, Pan and Dolly slots, each showing the variant last picked + // from its flyout. C cycles the three; 1, 2 and 3 pick one. + let camera_tool = |g: usize| { + let lead = [Tool::Orbit, Tool::PanCamera, Tool::Dolly].get(g).copied().unwrap_or(Tool::Orbit); + let Some(si) = Tool::SLOTS.iter().position(|s| s.contains(&lead)) else { return lead }; + let slot = Tool::SLOTS.get(si).copied().unwrap_or(&[]); + app.ui.slot_tools.get(si).copied().filter(|x| slot.contains(x)).unwrap_or(lead) + }; + let group = match t { + "camera" => Some(app.ui.tool.camera_group().map_or(0, |g| (g + 1) % 3)), + "orbit" => Some(0), + "panCamera" => Some(1), + "dolly" => Some(2), + _ => None, + }; + if let Some(g) = group { + let next = camera_tool(g); app.ui.tool = next; return Ok(json!({"tool": next})); } diff --git a/crates/ui-egui/src/menus/shortcuts.rs b/crates/ui-egui/src/menus/shortcuts.rs index dc4efd384..1be26f3da 100644 --- a/crates/ui-egui/src/menus/shortcuts.rs +++ b/crates/ui-egui/src/menus/shortcuts.rs @@ -189,7 +189,7 @@ pub fn active_contexts(app: &EffectcraftApp) -> Vec<&'static str> { } match app.ui.tool { Tool::Brush | Tool::Clone | Tool::Eraser => out.push("Paint"), - Tool::Orbit | Tool::PanCamera | Tool::Dolly => out.push("Camera"), + t if t.is_camera() => out.push("Camera"), _ => {} } if app.session.selected_mask().is_some() { diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index b12483b0a..06da434cb 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -228,6 +228,100 @@ fn c_cycles_the_camera_tools() { assert_eq!(seen, [Tool::Orbit, Tool::PanCamera, Tool::Dolly, Tool::Orbit]); } +/// Each camera tool's command and `mode` (what the viewer sends while dragging) run in the +/// engine and move a 3D view as the tool's name says (#2586). +#[test] +fn every_camera_tool_runs_its_engine_variant() { + use effectcraft_render::three_d::View3D; + let d = |a: [f64; 3], b: [f64; 3]| ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt(); + let tools: Vec = Tool::ALL.into_iter().filter(|t| t.is_camera()).collect(); + assert_eq!(tools.len(), 8); + for tool in tools { + let mut s = effectcraft_engine::Session::default(); + s.execute("comp.new", json!({"name": "C", "width": 640, "height": 360, "duration": 2})).unwrap(); + let cid = s.active_comp_id().unwrap(); + let id = s.execute("layer.newSolid", json!({"width": 100, "height": 100})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layer": id, "switch": "threeD", "value": true})).unwrap(); + s.execute("prop.set", json!({"layer": id, "path": "transform/position", "value": [400, 120, 200]})).unwrap(); + s.execute("view.3d.custom1", json!({})).unwrap(); + let cam = |s: &effectcraft_engine::Session| s.state.views3d[&cid].cam(View3D::Custom1, 640.0, 360.0); + let c0 = cam(&s); + let (id, mode) = tool.camera_command().unwrap(); + let mut p = match id { + "camera.orbit" => json!({"yaw": 20, "pitch": -5}), + "camera.pan" => json!({"dx": 30, "dy": 10}), + _ => json!({"amount": 1.0e7}), + }; + p["mode"] = json!(mode); + p["cursor"] = json!([400.0, 120.0]); + let r = s.execute(id, p).unwrap_or_else(|e| panic!("{tool:?}: {e}")); + let c1 = cam(&s); + let pivot = r["pivot"].as_array().map(|a| [a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()]); + match tool { + Tool::OrbitTarget => { + assert!(pivot.is_none(), "{tool:?}"); + assert!(d(c1.poi, c0.poi) < 1e-9 && d(c1.eye, c0.eye) > 1.0, "{tool:?}"); + } + Tool::PanTarget => { + assert!(pivot.is_none(), "{tool:?}"); + assert!(d(c1.poi, c0.poi) > 1.0, "{tool:?}"); + } + Tool::DollyTarget => { + assert!(pivot.is_none(), "{tool:?}"); + assert!(d(c1.poi, c0.poi) < 1e-9 && (d(c1.eye, c1.poi) - 1.0).abs() < 1e-6, "{tool:?}"); + } + Tool::Orbit | Tool::OrbitScene => { + let pv = pivot.unwrap_or_else(|| panic!("{tool:?}: no pivot")); + if tool == Tool::OrbitScene { + assert!(d(pv, [400.0, 120.0, 200.0]) < 1e-6, "{pv:?}"); + } + assert!(d(c1.poi, c0.poi) > 1.0, "{tool:?}"); + assert!((d(c1.eye, pv) - d(c0.eye, pv)).abs() < 1e-6, "{tool:?}"); + } + Tool::PanCamera => { + assert!(pivot.is_some(), "{tool:?}"); + assert!(d(c1.poi, c0.poi) > 1.0, "{tool:?}"); + } + Tool::Dolly => { + let pv = pivot.unwrap_or_else(|| panic!("{tool:?}: no pivot")); + assert!(d(c1.eye, pv) > 1.0e6, "Dolly Towards Cursor goes on past the point"); + } + Tool::DollyToCursor => { + let pv = pivot.unwrap_or_else(|| panic!("{tool:?}: no pivot")); + assert!((d(c1.eye, pv) - 1.0).abs() < 1e-6, "Dolly to Cursor stops short of the point"); + } + other => panic!("not a camera tool: {other:?}"), + } + } +} + +/// C and 1 / 2 / 3 pick each camera slot's variant as its flyout last left it (#2586). +#[test] +fn camera_keys_keep_each_slots_variant() { + let ctx = egui::Context::default(); + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + app.ui.tool = Tool::Selection; + app.ui.slot_tools[3] = Tool::OrbitScene; + app.ui.slot_tools[4] = Tool::PanTarget; + app.ui.slot_tools[5] = Tool::DollyToCursor; + let mut seen = vec![]; + for _ in 0..4 { + invoke(&mut app, &ctx, "tool.camera", json!({})).unwrap(); + seen.push(app.ui.tool); + } + assert_eq!(seen, [Tool::OrbitScene, Tool::PanTarget, Tool::DollyToCursor, Tool::OrbitScene]); + app.ui.slot_tools[5] = Tool::DollyTarget; + for (id, tool) in [("tool.dolly", Tool::DollyTarget), ("tool.panCamera", Tool::PanTarget), ("tool.orbit", Tool::OrbitScene)] { + invoke(&mut app, &ctx, id, json!({})).unwrap(); + assert_eq!(app.ui.tool, tool, "{id}"); + } + // Every variant is reachable by name, as the control channel selects tools. + for tool in [Tool::OrbitScene, Tool::OrbitTarget, Tool::PanTarget, Tool::DollyToCursor, Tool::DollyTarget] { + invoke(&mut app, &ctx, &format!("tool.{tool:?}"), json!({})).unwrap(); + assert_eq!(app.ui.tool, tool); + } +} + #[test] fn dispatch_uses_the_active_custom_preset() { let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); diff --git a/crates/ui-egui/src/panels/viewer.rs b/crates/ui-egui/src/panels/viewer.rs index b1899e1f8..b6da2aa81 100644 --- a/crates/ui-egui/src/panels/viewer.rs +++ b/crates/ui-egui/src/panels/viewer.rs @@ -952,9 +952,9 @@ fn phase_hover(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, resp Tool::Hand => egui::CursorIcon::Grab, Tool::Zoom => egui::CursorIcon::ZoomIn, Tool::Type | Tool::TypeVertical => egui::CursorIcon::Text, - Tool::Orbit => egui::CursorIcon::Alias, - Tool::PanCamera => egui::CursorIcon::Move, - Tool::Dolly => egui::CursorIcon::ResizeVertical, + Tool::Orbit | Tool::OrbitScene | Tool::OrbitTarget => egui::CursorIcon::Alias, + Tool::PanCamera | Tool::PanTarget => egui::CursorIcon::Move, + Tool::Dolly | Tool::DollyToCursor | Tool::DollyTarget => egui::CursorIcon::ResizeVertical, t if t.is_pen() => { pen_cursor( &ctx, @@ -1261,7 +1261,9 @@ fn phase_dragstart(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, } Some(Gesture::PuppetPin { layer: h.layer, pin: h.pin, inv }) }), - Tool::Orbit | Tool::PanCamera | Tool::Dolly => Some(Gesture::Camera { tool }), + // The cursor variants turn about / pan at / dolly towards the point under the press; + // the engine resolves it on the first step and the drag keeps it (`pivot`). + t if t.is_camera() => Some(Gesture::Camera { tool, cursor: map.to_comp(press), pivot: None }), Tool::Selection if super::tracker::hit_at(&track_hits, press).is_some() => { let hit = super::tracker::hit_at(&track_hits, press); track_cur.zip(hit).and_then(|((tl, tu), hit)| { @@ -1426,6 +1428,36 @@ fn edge_pan_speed(area: Rect, pos: Pos2) -> egui::Vec2 { vec2(axis(pos.x, area.min.x, area.max.x), axis(pos.y, area.min.y, area.max.y)) } +/// One step of a camera tool's drag: the tool's command with its `mode`, the press point and, once +/// known, the point it works about. Returns the point the first step found, for the drag to keep. +fn camera_drag(app: &mut EffectcraftApp, tool: Tool, cursor: [f64; 2], pivot: Option<[f64; 3]>, d: egui::Vec2, zoom: f32, merge: String) -> Option<[f64; 3]> { + let (id, mode) = tool.camera_command()?; + if d == egui::Vec2::ZERO { + return None; + } + let (dx, dy) = ((d.x / zoom) as f64, (d.y / zoom) as f64); + let mut params = match id { + "camera.orbit" => json!({"yaw": -d.x as f64 * 0.4, "pitch": d.y as f64 * 0.4}), + "camera.pan" => json!({"dx": dx, "dy": dy}), + _ => json!({"amount": -dy * 2.0}), + }; + params["mode"] = json!(mode); + params["merge"] = json!(merge); + params["cursor"] = json!(cursor); + if let Some(pv) = pivot { + params["point"] = json!(pv); + } + match app.session.execute(id, params) { + // Keep the point the first step found for the rest of the drag. + Ok(r) if pivot.is_none() => r["pivot"].as_array().and_then(|a| Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?])), + Ok(_) => None, + Err(e) => { + app.ui.status = e.to_string(); + None + } + } +} + fn phase_drag(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, resp: &egui::Response, v: &mut Vw<'_>) { let t = v.t; let zoom = v.zoom; @@ -1507,18 +1539,9 @@ fn phase_drag(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, resp: let _ = app.session.execute("prop.set", json!({"layer": layer.0, "path": "transform/position", "value": np, "merge": merge})); } } - Gesture::Camera { tool } => { - let d = resp.drag_delta(); - if d != egui::Vec2::ZERO { - let (dx, dy) = ((d.x / zoom) as f64, (d.y / zoom) as f64); - let (id, params) = match tool { - Tool::Orbit => ("camera.orbit", json!({"yaw": -d.x as f64 * 0.4, "pitch": d.y as f64 * 0.4, "merge": merge})), - Tool::PanCamera => ("camera.pan", json!({"dx": dx, "dy": dy, "merge": merge})), - _ => ("camera.dolly", json!({"amount": -dy * 2.0, "merge": merge})), - }; - if let Err(e) = app.session.execute(id, params) { - app.ui.status = e.to_string(); - } + Gesture::Camera { tool, cursor, pivot } => { + if let Some(found) = camera_drag(app, tool, cursor, pivot, resp.drag_delta(), zoom, merge) { + ui.data_mut(|dd| dd.insert_temp(gid, Gesture::Camera { tool, cursor, pivot: Some(found) })); } } Gesture::Create { tool, start } => { diff --git a/crates/ui-egui/src/panels/viewer/gesture.rs b/crates/ui-egui/src/panels/viewer/gesture.rs index 72ef22a84..0b59172e4 100644 --- a/crates/ui-egui/src/panels/viewer/gesture.rs +++ b/crates/ui-egui/src/panels/viewer/gesture.rs @@ -12,6 +12,10 @@ pub(super) enum Gesture { }, Camera { tool: Tool, + /// Where the drag began (comp pixels): the cursor variants' point is under it. + cursor: [f64; 2], + /// The world point the tool turns about / pans at / dollies towards, once resolved. + pivot: Option<[f64; 3]>, }, /// A bounding-box handle: scales about the anchor point so the grabbed point follows the /// pointer (corners both axes, edges one), relative to the layer as the drag began; the diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 60a30e97e..0d69fb33e 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -13,9 +13,22 @@ pub enum Tool { Selection, Hand, Zoom, + /// Orbit Around Cursor. Orbit, + /// Pan Under Cursor. PanCamera, + /// Dolly Towards Cursor. Dolly, + /// Orbit Around Scene (the centre of the comp's 3D layers). + OrbitScene, + /// Orbit Around Camera POI (the camera's point of interest). + OrbitTarget, + /// Pan Camera POI (moves as far as the point of interest's depth asks). + PanTarget, + /// Dolly to Cursor (stops short of the point under the cursor). + DollyToCursor, + /// Dolly to Camera POI (approaches the point of interest, which stays). + DollyTarget, Rotate, PanBehind, Rectangle, @@ -50,9 +63,9 @@ impl Tool { &[Tool::Selection], &[Tool::Hand], &[Tool::Zoom], - &[Tool::Orbit], - &[Tool::PanCamera], - &[Tool::Dolly], + &[Tool::Orbit, Tool::OrbitScene, Tool::OrbitTarget], + &[Tool::PanCamera, Tool::PanTarget], + &[Tool::Dolly, Tool::DollyToCursor, Tool::DollyTarget], &[Tool::Rotate], &[Tool::PanBehind], &[Tool::Rectangle, Tool::RoundedRect, Tool::Ellipse, Tool::Polygon, Tool::Star], @@ -64,13 +77,20 @@ impl Tool { &[Tool::RotoBrush, Tool::RefineEdge, Tool::ObjectMatte], &[Tool::Puppet, Tool::PuppetStarch, Tool::PuppetBend, Tool::PuppetAdvanced, Tool::PuppetOverlap], ]; - pub const ALL: [Tool; 31] = [ + /// Each slot's first tool comes before its variants: [`Tool::from_name`] matches labels by + /// prefix, so `orbit` stays Orbit Around Cursor. + pub const ALL: [Tool; 36] = [ Tool::Selection, Tool::Hand, Tool::Zoom, Tool::Orbit, Tool::PanCamera, Tool::Dolly, + Tool::OrbitScene, + Tool::OrbitTarget, + Tool::PanTarget, + Tool::DollyToCursor, + Tool::DollyTarget, Tool::Rotate, Tool::PanBehind, Tool::Rectangle, @@ -105,6 +125,11 @@ impl Tool { Tool::Orbit => "Orbit Around Cursor Tool", Tool::PanCamera => "Pan Under Cursor Tool", Tool::Dolly => "Dolly Towards Cursor Tool", + Tool::OrbitScene => "Orbit Around Scene Tool", + Tool::OrbitTarget => "Orbit Around Camera POI Tool", + Tool::PanTarget => "Pan Camera POI Tool", + Tool::DollyToCursor => "Dolly to Cursor Tool", + Tool::DollyTarget => "Dolly to Camera POI Tool", Tool::Rotate => "Rotation Tool", Tool::PanBehind => "Pan Behind (Anchor Point) Tool", Tool::Rectangle => "Rectangle Tool", @@ -137,9 +162,9 @@ impl Tool { Tool::Selection => Some("V"), Tool::Hand => Some("H"), Tool::Zoom => Some("Z"), - Tool::Orbit => Some("1"), - Tool::PanCamera => Some("2"), - Tool::Dolly => Some("3"), + Tool::Orbit | Tool::OrbitScene | Tool::OrbitTarget => Some("1"), + Tool::PanCamera | Tool::PanTarget => Some("2"), + Tool::Dolly | Tool::DollyToCursor | Tool::DollyTarget => Some("3"), Tool::Rotate => Some("W"), Tool::PanBehind => Some("Y"), Tool::Rectangle | Tool::RoundedRect | Tool::Ellipse | Tool::Polygon | Tool::Star => Some("Q"), @@ -155,9 +180,9 @@ impl Tool { Tool::Selection => Icon::Selection, Tool::Hand => Icon::Hand, Tool::Zoom => Icon::Zoom, - Tool::Orbit => Icon::Orbit, - Tool::PanCamera => Icon::PanCamera, - Tool::Dolly => Icon::Dolly, + Tool::Orbit | Tool::OrbitScene | Tool::OrbitTarget => Icon::Orbit, + Tool::PanCamera | Tool::PanTarget => Icon::PanCamera, + Tool::Dolly | Tool::DollyToCursor | Tool::DollyTarget => Icon::Dolly, Tool::Rotate => Icon::Rotate, Tool::PanBehind => Icon::PanBehind, Tool::Rectangle => Icon::Rectangle, @@ -189,6 +214,32 @@ impl Tool { let n = s.to_ascii_lowercase().replace([' ', '_', '-'], ""); Tool::ALL.into_iter().find(|t| format!("{t:?}").to_ascii_lowercase() == n || t.label().to_ascii_lowercase().replace(' ', "").starts_with(&n)) } + /// The camera tools' toolbar slot (0 = the Orbit tools, 1 = Pan, 2 = Dolly); None for other tools. + pub fn camera_group(self) -> Option { + match self { + Tool::Orbit | Tool::OrbitScene | Tool::OrbitTarget => Some(0), + Tool::PanCamera | Tool::PanTarget => Some(1), + Tool::Dolly | Tool::DollyToCursor | Tool::DollyTarget => Some(2), + _ => None, + } + } + pub fn is_camera(self) -> bool { + self.camera_group().is_some() + } + /// A camera tool's engine command and its `mode` (After Effects' variant of the tool). + pub fn camera_command(self) -> Option<(&'static str, &'static str)> { + Some(match self { + Tool::Orbit => ("camera.orbit", "aroundCursor"), + Tool::OrbitScene => ("camera.orbit", "aroundScene"), + Tool::OrbitTarget => ("camera.orbit", "aroundCameraPoi"), + Tool::PanCamera => ("camera.pan", "underCursor"), + Tool::PanTarget => ("camera.pan", "cameraPoi"), + Tool::Dolly => ("camera.dolly", "towardsCursor"), + Tool::DollyToCursor => ("camera.dolly", "toCursor"), + Tool::DollyTarget => ("camera.dolly", "toCameraPoi"), + _ => return None, + }) + } /// Puppet pin tools, with the pin kind they place (`puppet.addPin` kind). pub fn puppet_kind(self) -> Option<&'static str> { Some(match self { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9f3d69ea5..acd60ecdb 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -175,6 +175,14 @@ step; `ui.set {viewer: {res}}` sets the active comp's, and `ui.inspect` reports shape paths by uid), `keys.setSpatialTangents` (motion-path handles) and `keys.transform` (Graph Editor transform box, timeline Alt-drag scaling). +Camera tools: the Tools bar's Orbit, Pan and Dolly slots hold After Effects' variants +(`tools.Orbit|OrbitScene|OrbitTarget`, `tools.PanCamera|PanTarget`, +`tools.Dolly|DollyToCursor|DollyTarget`; flyout rows `tools.select.`). `tool.orbit`, +`tool.panCamera` and `tool.dolly` (1, 2, 3) select the variant the slot last showed, `tool.camera` +(C) cycles the three slots, and `tool.` (e.g. `tool.OrbitScene`) selects one directly. A drag +runs `camera.orbit` / `camera.pan` / `camera.dolly` with the tool's `mode` and the press point as +`cursor`; the result's `pivot` is the world point used, sent back as `point` for the rest of the drag. + The MCP server's bridge mode (`effectcraft-cli mcp --bridge 9877`) is a thin client of this protocol; see [agents.md](agents.md). From 5f661d9862e28b4ebda490bb0fcf74ad3cf6fa30 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 18:21:18 +0100 Subject: [PATCH 11/38] =?UTF-8?q?i18n:=20Japanese=20Orbit=20Around=20Camer?= =?UTF-8?q?a=20POI=20Tool=20ends=20in=20=E3=83=84=E3=83=BC=E3=83=AB=20like?= =?UTF-8?q?=20the=20other=20camera=20tools=20(#2586)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-egui/src/i18n/ui.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/ui.rs b/crates/ui-egui/src/i18n/ui.rs index 82da1b878..d01100f36 100644 --- a/crates/ui-egui/src/i18n/ui.rs +++ b/crates/ui-egui/src/i18n/ui.rs @@ -945,7 +945,7 @@ const JAPANESE: &[(&str, &str)] = &[ ("Pan Under Cursor Tool", "カーソルの下でパンツール"), ("Dolly Towards Cursor Tool", "カーソルに向かってドリーツール"), ("Orbit Around Scene Tool", "シーンのまわりを周回ツール"), - ("Orbit Around Camera POI Tool", "カメラ目標点のまわりを周回"), + ("Orbit Around Camera POI Tool", "カメラ目標点のまわりを周回ツール"), ("Pan Camera POI Tool", "カメラの目標点にパンツール"), ("Dolly to Cursor Tool", "カーソルにドリーツール"), ("Dolly to Camera POI Tool", "カメラの目標点にドリーツール"), From 63d9fa76aad142c7d4eb90313c9063457565d4c1 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 19:50:33 +0100 Subject: [PATCH 12/38] Doc comments for the functions this PR touches --- crates/engine/src/cmd/three_d.rs | 5 +++++ crates/engine/src/tests/three_d.rs | 2 ++ crates/render/src/three_d/camera.rs | 1 + crates/render/src/three_d/tests.rs | 9 +++++++++ crates/ui-egui/src/panels/viewer.rs | 3 +++ crates/ui-egui/src/state.rs | 4 ++++ 6 files changed, 24 insertions(+) diff --git a/crates/engine/src/cmd/three_d.rs b/crates/engine/src/cmd/three_d.rs index 10c87e5e5..25690a4e9 100644 --- a/crates/engine/src/cmd/three_d.rs +++ b/crates/engine/src/cmd/three_d.rs @@ -474,6 +474,8 @@ enum ToolMode { } impl ToolMode { + /// Reads the `mode` parameter of a camera tool into the variant that applies to `op`. + /// Without a mode, orbit and pan act about the point of interest and dolly moves plainly; an unknown name is an error. fn parse(p: &Value, op: ToolOp, cmd: &str) -> Result { let Some(raw) = str_p(p, "mode") else { return Ok(match op { @@ -544,6 +546,8 @@ fn tool_pivot(s: &Session, cid: ItemId, p: &Value, mode: ToolMode, cam: &camera: Some(camera::point_under(cam, w, h, px, &layer_quads(s, cid, &ids, t), poi)) } +/// Applies one orbit, pan or dolly step to the active camera, or to the current custom view, about the pivot its mode picks. +/// A step that would leave a non-finite camera is dropped; returns the layer and the view it came from. fn camera_tool(s: &mut Session, p: &Value, op: ToolOp, cmd: &str, label: &str) -> Result { let cid = comp_id(s, p)?; let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone(); @@ -811,6 +815,7 @@ fn camera_from_view(s: &mut Session, p: &Value) -> Result { Ok(json!({"layer": id.0, "from": cur.id()})) } +/// Returns the command specs of the 3D commands, including the eight camera tools. pub fn specs() -> Vec { vec![ cmd!( diff --git a/crates/engine/src/tests/three_d.rs b/crates/engine/src/tests/three_d.rs index 4520c8fcc..df60b762e 100644 --- a/crates/engine/src/tests/three_d.rs +++ b/crates/engine/src/tests/three_d.rs @@ -325,10 +325,12 @@ fn camera_tools_edit_active_camera_with_undo() { assert!(o[1].abs() > 1.0, "{o:?}"); } +/// Returns the Euclidean distance between two 3D points. fn dist3(a: [f64; 3], b: [f64; 3]) -> f64 { ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt() } +/// Reads a JSON array of three numbers as a point; panics on anything else. fn arr3(v: &serde_json::Value) -> [f64; 3] { let a = v.as_array().unwrap_or_else(|| panic!("not a point: {v}")); [a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()] diff --git a/crates/render/src/three_d/camera.rs b/crates/render/src/three_d/camera.rs index 9452a6bf1..daa929f3a 100644 --- a/crates/render/src/three_d/camera.rs +++ b/crates/render/src/three_d/camera.rs @@ -581,6 +581,7 @@ impl Rig { pub fn state(&self) -> CameraState { CameraState { view: basis_view(self.eye, self.poi - self.eye, vec3(0.0, 1.0, 0.0)), eye: self.eye, zoom: self.zoom, ortho: self.ortho, dof: None } } + /// Returns the camera's forward, right and down unit vectors. fn frame(&self) -> (Vec3, Vec3, Vec3) { let s = self.state(); (s.forward(), s.right(), s.down()) diff --git a/crates/render/src/three_d/tests.rs b/crates/render/src/three_d/tests.rs index 8fcd2d5b8..c329377dd 100644 --- a/crates/render/src/three_d/tests.rs +++ b/crates/render/src/three_d/tests.rs @@ -725,14 +725,17 @@ fn rig_orbit_keeps_distance_and_pan_moves_both() { const CW: f64 = 1920.0; const CH: f64 = 1080.0; +/// Returns the rig of the default Custom View 1 camera in a comp of size `CW` by `CH`. fn custom_rig() -> Rig { Rig::from_view(&default_view_cam(View3D::Custom1, CW, CH)) } +/// Projects the world point `p` through the rig's camera to comp pixels; panics when the point is behind the camera. fn screen(r: &Rig, p: Vec3) -> effectcraft_geom::Vec2 { r.state().project(CW, CH, p).expect("in front of the camera") } +/// Checks that orbiting about the point of interest equals the plain orbit step. #[test] fn orbit_around_camera_poi_is_orbit_about_the_poi() { let (mut a, mut b) = (custom_rig(), custom_rig()); @@ -742,6 +745,7 @@ fn orbit_around_camera_poi_is_orbit_about_the_poi() { assert!((a.poi - b.poi).length() < 1e-9); } +/// Checks that orbiting about a pivot keeps the pivot's distance and screen position while the point of interest turns too, and that a NaN pivot is ignored. #[test] fn orbit_around_a_pivot_keeps_it_on_screen_and_turns_the_whole_camera() { let mut r = custom_rig(); @@ -764,6 +768,7 @@ fn orbit_around_a_pivot_keeps_it_on_screen_and_turns_the_whole_camera() { assert_eq!(r, before); } +/// Checks that Pan Under Cursor moves a point by exactly the drag, unlike Pan Camera POI, and falls back to the POI depth behind the camera. #[test] fn pan_under_cursor_keeps_the_grabbed_point_under_the_pointer() { // A point nearer than the point of interest: Pan Camera POI moves it by less @@ -786,6 +791,7 @@ fn pan_under_cursor_keeps_the_grabbed_point_under_the_pointer() { assert!((back.eye - target.eye).length() < 1e-9); } +/// Checks that both cursor dollies keep the point under the cursor fixed and that Dolly to Cursor stops short of it. #[test] fn dolly_towards_and_to_cursor_move_along_the_cursor_ray() { let r0 = custom_rig(); @@ -831,6 +837,7 @@ fn dolly_towards_cursor_keeps_going_past_the_point() { assert!((r.eye - target).length() > 1000.0, "well past the point"); } +/// Checks that Dolly to Camera POI leaves the camera in place when it is already within a pixel of the point. #[test] fn dolly_to_camera_poi_never_backs_off_when_closer_than_a_pixel() { let mut r = custom_rig(); @@ -841,6 +848,7 @@ fn dolly_to_camera_poi_never_backs_off_when_closer_than_a_pixel() { assert!((r.eye - eye).length() < 1e-12, "{:?}", r.eye); } +/// Checks that every camera tool keeps the rig finite for degenerate cameras, pivots and targets. #[test] fn camera_tools_never_produce_nan_cameras() { let nan_free = |r: &Rig| assert!(r.is_finite(), "{r:?}"); @@ -866,6 +874,7 @@ fn camera_tools_never_produce_nan_cameras() { nan_free(&Rig { eye: super::camera::point_under(&cam, CW, CH, [10.0, 10.0], &[], down.poi), ..down }); } +/// Checks that the point under the cursor lies on the nearest layer it hits, else at the POI depth. #[test] fn the_point_under_the_cursor_is_on_the_layer_it_hits() { let r = Rig::from_view(&default_view_cam(View3D::Default, CW, CH)); diff --git a/crates/ui-egui/src/panels/viewer.rs b/crates/ui-egui/src/panels/viewer.rs index b6da2aa81..14be2d875 100644 --- a/crates/ui-egui/src/panels/viewer.rs +++ b/crates/ui-egui/src/panels/viewer.rs @@ -918,6 +918,7 @@ fn wheel_scrub_frames(ctx: &egui::Context, pref: bool, scroll: &super::ViewerScr scrub.then_some((scroll.wheel_lines.round() as i64).clamp(-30, 30)) } +/// Handles the pointer moving over the viewer without a drag: hover feedback, cursors and tool hints. fn phase_hover(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, resp: &egui::Response, v: &mut Vw<'_>) { let area = v.area; let zoom = v.zoom; @@ -1130,6 +1131,7 @@ fn led_by_a_moved_ancestor(comp: &Comp, layers: &[MoveLayer]) -> Vec { layers.iter().map(|l| led(l.0)).collect() } +/// Starts a drag gesture in the viewer on the first drag frame: picks what the active tool and the item under the pointer begin to move, draw or select. fn phase_dragstart(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, resp: &egui::Response, v: &mut Vw<'_>) { let comp_rect = v.comp_rect; let zoom = v.zoom; @@ -1458,6 +1460,7 @@ fn camera_drag(app: &mut EffectcraftApp, tool: Tool, cursor: [f64; 2], pivot: Op } } +/// Continues the viewer gesture that `phase_dragstart` began, applying the pointer's movement to it. fn phase_drag(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, resp: &egui::Response, v: &mut Vw<'_>) { let t = v.t; let zoom = v.zoom; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0d69fb33e..81d2fee96 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -117,6 +117,7 @@ impl Tool { Tool::PuppetAdvanced, Tool::PuppetOverlap, ]; + /// Returns the tool's name as After Effects shows it, e.g. `Orbit Around Cursor Tool`. pub fn label(self) -> &'static str { match self { Tool::Selection => "Selection Tool", @@ -157,6 +158,7 @@ impl Tool { Tool::PuppetOverlap => "Puppet Overlap Pin Tool", } } + /// Returns the tool's key, shared by the variants in one toolbar slot, or `None` when it has none. pub fn shortcut(self) -> Option<&'static str> { match self { Tool::Selection => Some("V"), @@ -175,6 +177,7 @@ impl Tool { Tool::Puppet | Tool::PuppetStarch | Tool::PuppetBend | Tool::PuppetAdvanced | Tool::PuppetOverlap => Some("Cmd+P"), } } + /// Returns the toolbar icon of the tool; the variants of one slot share an icon. pub fn icon(self) -> Icon { match self { Tool::Selection => Icon::Selection, @@ -223,6 +226,7 @@ impl Tool { _ => None, } } + /// Returns whether the tool is one of the orbit, pan or dolly camera tools. pub fn is_camera(self) -> bool { self.camera_group().is_some() } From 438315e020e3074e9f4b8fe1a9f88742a7f46ab4 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 02:34:22 +0100 Subject: [PATCH 13/38] Camera tools: report the point used when a parent cannot be inverted; cover picking (#2586) When a camera's parent cannot be inverted (scale 0), the cursor and scene variants fall back to the point of interest; the result's `pivot` is now that world point instead of the point the camera could not turn about. The help strings and the control protocol say when `pivot` is null. New engine tests: Pan Under Cursor moves a grabbed point nearer than the point of interest by exactly the drag; picking and the scene's centre skip guides, Video-off layers and nulls; Orbit Around Scene without 3D layers uses the comp centre; the scale-0 parent fallback. --- crates/engine/src/cmd/three_d.rs | 19 +++--- crates/engine/src/tests/three_d.rs | 98 ++++++++++++++++++++++++++++++ docs/control-protocol.md | 4 +- 3 files changed, 112 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/three_d.rs b/crates/engine/src/cmd/three_d.rs index 25690a4e9..909d7cec0 100644 --- a/crates/engine/src/cmd/three_d.rs +++ b/crates/engine/src/cmd/three_d.rs @@ -590,7 +590,7 @@ fn camera_tool(s: &mut Session, p: &Value, op: ToolOp, cmd: &str, label: &str) - .ok_or_else(|| bad(cmd, "the comp has no active camera layer (Layer ▸ New ▸ Camera), or switch to a custom 3D view"))?; // The point under the cursor as the camera layer shows it, in world space (returned, and // sent back by the viewer as `point`) and in the camera's parent space (what the rig edits). - let (pivot, local_pivot) = match comp.layer(cam) { + let (pivot, local_pivot, world_poi) = match comp.layer(cam) { Some(l) if !matches!(mode, ToolMode::Plain | ToolMode::Target) => { let ctx = EvalCtx { project: &s.project, @@ -610,13 +610,16 @@ fn camera_tool(s: &mut Session, p: &Value, op: ToolOp, cmd: &str, label: &str) - }; let world = tool_pivot(s, cid, p, mode, &state, poi, t); let local = world.and_then(|w| pw.inverse().map(|m| m.apply(w))).filter(|v| v.x.is_finite() && v.y.is_finite() && v.z.is_finite()); - (world, local) + (world, local, poi) } - _ => (None, None), + _ => (None, None, Vec3::ZERO), }; // A parent that cannot be inverted leaves no pivot in the camera's space: work about its - // point of interest instead. - let mode = if pivot.is_some() && local_pivot.is_none() { ToolMode::Target } else { mode }; + // point of interest instead, and report that point as the one used (sent back as `point`, + // it lands here again). + let fallback = pivot.is_some() && local_pivot.is_none(); + let mode = if fallback { ToolMode::Target } else { mode }; + let pivot = if fallback { Some(world_poi).filter(|v| v.x.is_finite() && v.y.is_finite() && v.z.is_finite()) } else { pivot }; let merge = merge_p(p).map(str::to_string); let r = s.edit(label, merge.as_deref(), |proj, _| { let l = layer_mut(proj, cid, cam)?; @@ -905,7 +908,7 @@ pub fn specs() -> Vec { "Orbit Camera", [], None, - "{yaw|dx deg, pitch|dy deg, mode?: aroundCursor|aroundScene|aroundCameraPoi (default; alias aroundCameraTarget), cursor? [x,y] comp px, point? [x,y,z] pivot, layer?, merge?} — current 3D view (camera layer in Active Camera); returns the pivot used", + "{yaw|dx deg, pitch|dy deg, mode?: aroundCursor|aroundScene|aroundCameraPoi (default; alias aroundCameraTarget), cursor? [x,y] comp px, point? [x,y,z] pivot, layer?, merge?} — current 3D view (camera layer in Active Camera); returns `pivot`, the world point used (null when the tool works about the point of interest)", has_comp, orbit ), @@ -914,7 +917,7 @@ pub fn specs() -> Vec { "Pan Camera", [], None, - "{dx, dy (comp px), mode?: underCursor|cameraPoi (default; alias toCameraTarget), cursor? [x,y], point? [x,y,z], layer?, merge?}", + "{dx, dy (comp px), mode?: underCursor|cameraPoi (default; alias toCameraTarget), cursor? [x,y], point? [x,y,z], layer?, merge?} — returns `pivot` (null: the point of interest)", has_comp, pan ), @@ -923,7 +926,7 @@ pub fn specs() -> Vec { "Dolly Camera", [], None, - "{amount (px, + = forward), mode?: towardsCursor|toCursor|toCameraPoi (alias toCameraTarget; default: along the view axis), cursor? [x,y], point? [x,y,z], layer?, merge?}", + "{amount (px, + = forward), mode?: towardsCursor|toCursor|toCameraPoi (alias toCameraTarget; default: along the view axis), cursor? [x,y], point? [x,y,z], layer?, merge?} — returns `pivot` (null: the point of interest or, without mode, the view axis)", has_comp, dolly ), diff --git a/crates/engine/src/tests/three_d.rs b/crates/engine/src/tests/three_d.rs index df60b762e..9fbe9e440 100644 --- a/crates/engine/src/tests/three_d.rs +++ b/crates/engine/src/tests/three_d.rs @@ -425,6 +425,104 @@ fn camera_tools_on_a_parented_camera_use_the_world_point() { assert!((dist3(world_eye(&mut s), pivot) - 1.0).abs() < 1e-6); } +/// The comp's active camera as rendered (world space). +fn active_cam(s: &Session) -> effectcraft_render::three_d::CameraState { + let cid = s.active_comp_id().unwrap(); + let comp = s.project.comp(cid).unwrap(); + let ctx = effectcraft_render::EvalCtx { + project: &s.project, + comp_id: cid, + comp, + time: s.time(), + expr: s.expr.as_deref(), + footage: None, + property_overrides: &[], + media_overrides: &[], + }; + effectcraft_render::three_d::camera::active_camera(&ctx) +} + +fn solid3d(s: &mut Session, w: u32, h: u32, pos: [f64; 3]) -> u64 { + let id = s.execute("layer.newSolid", json!({"width": w, "height": h})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layer": id, "switch": "threeD", "value": true})).unwrap(); + s.execute("prop.set", json!({"layer": id, "path": "transform/position", "value": pos})).unwrap(); + id +} + +/// Pan Under Cursor on a camera layer: the grabbed point, nearer than the point of interest, +/// follows the drag exactly (#2586). +#[test] +fn pan_under_cursor_moves_the_grabbed_point_by_the_drag() { + let mut s = session(); + solid3d(&mut s, 640, 360, [320.0, 180.0, -300.0]); + s.execute("layer.newCamera", json!({})).unwrap(); + let r = s.execute("camera.pan", json!({"dx": 0, "dy": 0, "mode": "underCursor", "cursor": [200, 100]})).unwrap(); + let pivot = arr3(&r["pivot"]); + assert!((pivot[2] + 300.0).abs() < 1e-6, "on the nearer solid: {pivot:?}"); + let at = effectcraft_geom::Vec3::from(pivot); + let before = active_cam(&s).project(640.0, 360.0, at).unwrap(); + s.execute("camera.pan", json!({"dx": 30, "dy": -12, "mode": "underCursor", "point": pivot})).unwrap(); + let after = active_cam(&s).project(640.0, 360.0, at).unwrap(); + assert!((after.x - before.x - 30.0).abs() < 1e-6 && (after.y - before.y + 12.0).abs() < 1e-6, "{before:?} → {after:?}"); +} + +/// The point under the cursor is on a visible 3D layer: guides, layers with Video off, nulls, +/// cameras and lights in front of it are not picked (#2586). +#[test] +fn the_point_under_the_cursor_skips_hidden_and_guide_layers() { + let mut s = session(); + solid3d(&mut s, 640, 360, [320.0, 180.0, 0.0]); + let guide = solid3d(&mut s, 640, 360, [320.0, 180.0, -200.0]); + s.execute("layer.setSwitch", json!({"layer": guide, "switch": "guide", "value": true})).unwrap(); + let hidden = solid3d(&mut s, 640, 360, [320.0, 180.0, -300.0]); + s.execute("layer.setSwitch", json!({"layer": hidden, "switch": "video", "value": false})).unwrap(); + let nul = s.execute("layer.newNull", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layer": nul, "switch": "threeD", "value": true})).unwrap(); + s.execute("prop.set", json!({"layer": nul, "path": "transform/position", "value": [320, 180, -400]})).unwrap(); + s.execute("layer.newCamera", json!({})).unwrap(); + let r = s.execute("camera.orbit", json!({"yaw": 0, "mode": "aroundCursor", "cursor": [300, 170]})).unwrap(); + let pivot = arr3(&r["pivot"]); + assert!(pivot[2].abs() < 1e-6, "the visible solid at z = 0: {pivot:?}"); + // The scene's centre counts only that solid too. + let r = s.execute("camera.orbit", json!({"yaw": 0, "mode": "aroundScene"})).unwrap(); + assert!(dist3(arr3(&r["pivot"]), [320.0, 180.0, 0.0]) < 1e-6, "{}", r["pivot"]); +} + +/// Orbit Around Scene without 3D layers turns about the comp's centre (#2586). +#[test] +fn orbit_around_scene_without_3d_layers_uses_the_comp_centre() { + let mut s = session(); + s.execute("layer.newSolid", json!({"width": 100, "height": 100})).unwrap(); + s.execute("layer.newCamera", json!({})).unwrap(); + let r = s.execute("camera.orbit", json!({"yaw": 10, "mode": "aroundScene"})).unwrap(); + assert!(dist3(arr3(&r["pivot"]), [320.0, 180.0, 0.0]) < 1e-9, "{}", r["pivot"]); +} + +/// A camera whose parent cannot be inverted (scale 0) works about its point of interest, stays +/// finite, and reports that point as the one used (#2586). +#[test] +fn a_parent_that_cannot_be_inverted_falls_back_to_the_point_of_interest() { + let mut s = session(); + solid3d(&mut s, 100, 100, [400.0, 120.0, 200.0]); + let parent = s.execute("layer.newNull", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layer": parent, "switch": "threeD", "value": true})).unwrap(); + let cam = s.execute("layer.newCamera", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setParent", json!({"layers": [cam], "parent": parent, "compensate": false})).unwrap(); + s.execute("prop.set", json!({"layer": parent, "path": "transform/scale", "value": [0, 0, 0]})).unwrap(); + let poi0 = prop(&s, cam, "transform/poi").as_vec3(); + // Through a scale-0 parent every point of the camera lands on the parent's position. + let world_poi = prop(&s, parent, "transform/position").as_vec3(); + let r = s.execute("camera.orbit", json!({"yaw": 20, "pitch": -5, "mode": "aroundScene"})).unwrap(); + let pivot = arr3(&r["pivot"]); + assert!(dist3(pivot, world_poi) < 1e-9, "the point of interest, not the scene's centre: {pivot:?}"); + assert_eq!(prop(&s, cam, "transform/poi").as_vec3(), poi0, "Orbit Around Camera POI keeps the point of interest"); + let pos = prop(&s, cam, "transform/position").as_vec3(); + assert!(pos.iter().all(|v| v.is_finite()), "{pos:?}"); + // Sent back as `point`, it falls back the same way. + let r2 = s.execute("camera.orbit", json!({"yaw": 5, "mode": "aroundScene", "point": pivot})).unwrap(); + assert!(dist3(arr3(&r2["pivot"]), pivot) < 1e-9); +} + #[test] fn demo_has_3d_showcase() { let mut s = Session::default(); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index acd60ecdb..58b7b670c 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -181,7 +181,9 @@ Camera tools: the Tools bar's Orbit, Pan and Dolly slots hold After Effects' var `tool.panCamera` and `tool.dolly` (1, 2, 3) select the variant the slot last showed, `tool.camera` (C) cycles the three slots, and `tool.` (e.g. `tool.OrbitScene`) selects one directly. A drag runs `camera.orbit` / `camera.pan` / `camera.dolly` with the tool's `mode` and the press point as -`cursor`; the result's `pivot` is the world point used, sent back as `point` for the rest of the drag. +`cursor`; the result's `pivot` is the world point used, sent back as `point` for the rest of the drag +(null when the tool works about the camera's point of interest: the POI variants, and `camera.dolly` +without `mode`). The MCP server's bridge mode (`effectcraft-cli mcp --bridge 9877`) is a thin client of this protocol; see [agents.md](agents.md). From a85829f6bcd4c48fd8ede746b81ee5e84fd59b05 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 04:49:45 +0100 Subject: [PATCH 14/38] Camera tools: a one-node camera's fallback pivot is the rig's point of interest (#2586) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When a camera's parent cannot be inverted, the reported pivot was the rendered camera's eye + forward × zoom; for a one-node camera under a scale-0 parent that is not the point the rig works about. It is now the rig's parent-space point of interest through the parent. Test: Pan Under Cursor and Dolly to Cursor on such a camera report the parent's position and match their Camera POI variants. --- crates/engine/src/cmd/three_d.rs | 14 ++++++------ crates/engine/src/tests/three_d.rs | 35 ++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/three_d.rs b/crates/engine/src/cmd/three_d.rs index 860038549..577a141f6 100644 --- a/crates/engine/src/cmd/three_d.rs +++ b/crates/engine/src/cmd/three_d.rs @@ -609,7 +609,7 @@ fn camera_tool(s: &mut Session, p: &Value, op: ToolOp, cmd: &str, label: &str) - .ok_or_else(|| bad(cmd, "the comp has no active camera layer (Layer ▸ New ▸ Camera), or switch to a custom 3D view"))?; // The point under the cursor as the camera layer shows it, in world space (returned, and // sent back by the viewer as `point`) and in the camera's parent space (what the rig edits). - let (pivot, local_pivot, world_poi) = match comp.layer(cam) { + let (pivot, local_pivot, pw) = match comp.layer(cam) { Some(l) if !matches!(mode, ToolMode::Plain | ToolMode::Target) => { let ctx = EvalCtx { project: &s.project, @@ -630,16 +630,15 @@ fn camera_tool(s: &mut Session, p: &Value, op: ToolOp, cmd: &str, label: &str) - }; let world = tool_pivot(s, cid, p, mode, &state, poi, t); let local = world.and_then(|w| pw.inverse().map(|m| m.apply(w))).filter(|v| v.x.is_finite() && v.y.is_finite() && v.z.is_finite()); - (world, local, poi) + (world, local, pw) } - _ => (None, None, Vec3::ZERO), + _ => (None, None, Mat4::IDENTITY), }; // A parent that cannot be inverted leaves no pivot in the camera's space: work about its - // point of interest instead, and report that point as the one used (sent back as `point`, - // it lands here again). + // point of interest instead, and report that point (the rig's, through the parent) as the one + // used; sent back as `point`, it lands here again. let fallback = pivot.is_some() && local_pivot.is_none(); let mode = if fallback { ToolMode::Target } else { mode }; - let pivot = if fallback { Some(world_poi).filter(|v| v.x.is_finite() && v.y.is_finite() && v.z.is_finite()) } else { pivot }; let merge = merge_p(p).map(str::to_string); let r = s.edit(label, merge.as_deref(), |proj, _| { let l = layer_mut(proj, cid, cam)?; @@ -655,6 +654,7 @@ fn camera_tool(s: &mut Session, p: &Value, op: ToolOp, cmd: &str, label: &str) - let fwd = (Mat4::orientation(Vec3::from(o)) * Mat4::rotation_xyz(rx, ry, 0.0)).apply_vec(vec3(0.0, 0.0, 1.0)); pos + fwd * zoom }; + let used = if fallback { Some(pw.apply(poi)).filter(|v| v.x.is_finite() && v.y.is_finite() && v.z.is_finite()) } else { pivot }; let mut rig = Rig { eye: pos, poi, zoom, ortho: false }; apply(&mut rig, true, local_pivot, mode); set_at(l, "transform/position", t, KV::Vec3(camera::arr(rig.eye))); @@ -665,7 +665,7 @@ fn camera_tool(s: &mut Session, p: &Value, op: ToolOp, cmd: &str, label: &str) - set_at(l, "transform/rotationX", t, KV::Scalar(0.0)); set_at(l, "transform/rotationY", t, KV::Scalar(0.0)); } - Ok(json!({"layer": cam.0, "position": camera::arr(rig.eye), "poi": camera::arr(rig.poi), "pivot": pivot_json(pivot)})) + Ok(json!({"layer": cam.0, "position": camera::arr(rig.eye), "poi": camera::arr(rig.poi), "pivot": pivot_json(used)})) })?; Ok(r) } diff --git a/crates/engine/src/tests/three_d.rs b/crates/engine/src/tests/three_d.rs index 5847112ed..92bef6642 100644 --- a/crates/engine/src/tests/three_d.rs +++ b/crates/engine/src/tests/three_d.rs @@ -524,6 +524,41 @@ fn a_parent_that_cannot_be_inverted_falls_back_to_the_point_of_interest() { assert!(dist3(arr3(&r2["pivot"]), pivot) < 1e-9); } +/// A one-node camera under a scale-0 parent: Pan Under Cursor and Dolly to Cursor work as their +/// Camera POI variants, and report the rig's point of interest through the parent, which is +/// where the parent puts every point (#2586). +#[test] +fn a_one_node_camera_under_a_scale_0_parent_pans_and_dollies_about_its_poi() { + let setup = || { + let mut s = session(); + solid3d(&mut s, 100, 100, [400.0, 120.0, 200.0]); + let parent = s.execute("layer.newNull", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setSwitch", json!({"layer": parent, "switch": "threeD", "value": true})).unwrap(); + s.execute("prop.set", json!({"layer": parent, "path": "transform/position", "value": [100, 50, 30]})).unwrap(); + let cam = s.execute("layer.newCamera", json!({"type": "oneNode"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setParent", json!({"layers": [cam], "parent": parent, "compensate": false})).unwrap(); + s.execute("prop.set", json!({"layer": parent, "path": "transform/scale", "value": [0, 0, 0]})).unwrap(); + (s, cam) + }; + for (cmd, params, poi_mode) in [ + ("camera.pan", json!({"dx": 30, "dy": -12, "mode": "underCursor", "cursor": [200, 100]}), "cameraPoi"), + ("camera.dolly", json!({"amount": 80, "mode": "toCursor", "cursor": [200, 100]}), "toCameraPoi"), + ] { + let (mut s, cam) = setup(); + let r = s.execute(cmd, params.clone()).unwrap(); + let pivot = arr3(&r["pivot"]); + assert!(dist3(pivot, [100.0, 50.0, 30.0]) < 1e-9, "{cmd}: {pivot:?}"); + let moved = (prop(&s, cam, "transform/position").as_vec3(), prop(&s, cam, "transform/orientation").as_vec3()); + assert!(moved.0.iter().chain(moved.1.iter()).all(|v| v.is_finite()), "{cmd}: {moved:?}"); + let (mut t, cam_t) = setup(); + let mut poi_params = params; + poi_params["mode"] = json!(poi_mode); + t.execute(cmd, poi_params).unwrap(); + let want = (prop(&t, cam_t, "transform/position").as_vec3(), prop(&t, cam_t, "transform/orientation").as_vec3()); + assert!(dist3(moved.0, want.0) < 1e-9 && dist3(moved.1, want.1) < 1e-9, "{cmd}: {moved:?} vs {want:?}"); + } +} + #[test] fn demo_has_3d_showcase() { let mut s = Session::default(); From b4a18c381ea3e4f4e674d8704a00c424e38b8e3d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 17:25:48 -0800 Subject: [PATCH 15/38] Import: a PDF picked with a PhotoCraft file keeps the Page field Importing a .pcraft file together with a PDF or Illustrator file showed the PhotoCraft dialog without the Page field, so the PDF always imported its first page. The dialog now adds Page when a PDF or Illustrator file is in the import. --- crates/ui-egui/src/panels/forms.rs | 35 +++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/panels/forms.rs b/crates/ui-egui/src/panels/forms.rs index 89efe0ce2..7e12d5a4a 100644 --- a/crates/ui-egui/src/panels/forms.rs +++ b/crates/ui-egui/src/panels/forms.rs @@ -516,16 +516,18 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool { "file.import" if !has(p, &["importAs"]) && imports_ext(p, &["pcraft"]) && !is_layered(p) => { let drag = p.get("drag").and_then(Value::as_bool).unwrap_or(false); let sel = usize::from(drag && s.prefs.drag_import_as() != "footage"); - ( - "Import PhotoCraft File".into(), - vec![ - Field::choice("importAs", "Import Kind", &[("Footage", json!("footage")), ("Composition", json!("composition"))], sel), - Field::note( - "pcraftNote", - "Composition uses canvas-sized saved pixels. Masks, effects and profiles may differ; use Footage for the saved appearance.", - ), - ], - ) + let mut fields = vec![ + Field::choice("importAs", "Import Kind", &[("Footage", json!("footage")), ("Composition", json!("composition"))], sel), + Field::note( + "pcraftNote", + "Composition uses canvas-sized saved pixels. Masks, effects and profiles may differ; use Footage for the saved appearance.", + ), + ]; + // A PDF or Illustrator file picked with it keeps its Page field. + if is_pdf(p) && !has(p, &["page"]) { + fields.push(Field::num("page", "Page", 1.0)); + } + ("Import PhotoCraft File".into(), fields) } // Photoshop files: Import Kind (Footage / Composition / – Retain Layer Sizes). Dropped // files start at Settings ▸ Import ▸ Default Drag Import As. @@ -1078,6 +1080,19 @@ mod tests { assert!(app.dialog_state.form.params().get("pcraftNote").is_none()); let FieldKind::Choice { options, .. } = &app.dialog_state.form.fields[0].kind else { panic!("no import choices") }; assert_eq!(options.len(), 2, "Retain Layer Sizes is not offered for canvas-sized PhotoCraft pixels"); + assert!(app.dialog_state.form.params().get("page").is_none(), "no page without a PDF"); + } + } + + #[test] + fn photocraft_import_with_a_pdf_keeps_the_page_field() { + for pdf in ["/picked.pdf", "/picked.ai"] { + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + let reply = + crate::menus::invoke(&mut app, &egui::Context::default(), "file.import", json!({"paths": ["/picked.pcraft", pdf], "drag": true})).unwrap(); + assert_eq!(reply["dialog"], "file.import"); + assert_eq!(app.dialog_state.form.title, "Import PhotoCraft File"); + assert_eq!(app.dialog_state.form.params()["page"], json!(1.0), "{pdf}"); } } From 1ee51f5e2c671c5a273b9b24585443bc8f6dd0f6 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 14 Nov 2026 17:10:47 +0100 Subject: [PATCH 16/38] M2586: camera tool pivot respects solo (scene_layers uses Comp::any_solo like the renderer) --- crates/engine/src/cmd/three_d.rs | 10 ++++++++-- crates/engine/src/tests/three_d.rs | 23 +++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/three_d.rs b/crates/engine/src/cmd/three_d.rs index 577a141f6..786787dd2 100644 --- a/crates/engine/src/cmd/three_d.rs +++ b/crates/engine/src/cmd/three_d.rs @@ -512,9 +512,15 @@ impl ToolMode { } /// The 3D layers that make up the scene at comp time `t`: active, visible (Video on, not a guide) -/// and with pixels (no cameras, lights or nulls). +/// and with pixels (no cameras, lights or nulls). Solo applies as the renderer's +/// `Renderer::visible_layers` does (`Comp::any_solo`): with a layer soloed, only soloed layers count. fn scene_layers(comp: &Comp, t: Tick) -> Vec { - comp.layers.iter().filter(|l| l.is_active_at(t) && l.switches.three_d && l.switches.video && !l.switches.guide && l.source.is_av()).map(|l| l.id).collect() + let any_solo = comp.any_solo(); + comp.layers + .iter() + .filter(|l| l.is_active_at(t) && l.switches.three_d && l.switches.video && !l.switches.guide && l.source.is_av() && (!any_solo || l.switches.solo)) + .map(|l| l.id) + .collect() } /// World-space rectangles of the layers' content at comp time `t` (for picking the point under diff --git a/crates/engine/src/tests/three_d.rs b/crates/engine/src/tests/three_d.rs index 92bef6642..67d6ee6b6 100644 --- a/crates/engine/src/tests/three_d.rs +++ b/crates/engine/src/tests/three_d.rs @@ -489,6 +489,29 @@ fn the_point_under_the_cursor_skips_hidden_and_guide_layers() { assert!(dist3(arr3(&r["pivot"]), [320.0, 180.0, 0.0]) < 1e-6, "{}", r["pivot"]); } +/// With a layer soloed, a nearer non-solo plane is not drawn and so not picked: the cursor modes +/// take the soloed plane's depth, and Orbit Around Scene's centre ignores the hidden plane (#2586). +#[test] +fn the_camera_tool_pivot_respects_solo() { + let mut s = session(); + let far = solid3d(&mut s, 640, 360, [320.0, 180.0, 0.0]); + let near = solid3d(&mut s, 200, 200, [320.0, 180.0, -300.0]); + s.execute("layer.newCamera", json!({})).unwrap(); + // Nothing soloed: the nearer plane under the cursor is picked. + let r = s.execute("camera.orbit", json!({"yaw": 0, "mode": "aroundCursor", "cursor": [320, 180]})).unwrap(); + assert!((arr3(&r["pivot"])[2] + 300.0).abs() < 1e-6, "{}", r["pivot"]); + s.execute("layer.setSwitch", json!({"layer": far, "switch": "solo", "value": true})).unwrap(); + assert_ne!(far, near); + for (cmd, mode) in [("camera.orbit", "aroundCursor"), ("camera.pan", "underCursor"), ("camera.dolly", "towardsCursor")] { + let r = s.execute(cmd, json!({"yaw": 0, "dx": 0, "dy": 0, "amount": 0, "mode": mode, "cursor": [320, 180]})).unwrap(); + let pivot = arr3(&r["pivot"]); + assert!(pivot[2].abs() < 1e-6, "{cmd}: the soloed plane's depth, not the hidden one's: {pivot:?}"); + } + // The scene centre is the soloed plane's, not the middle of both. + let r = s.execute("camera.orbit", json!({"yaw": 0, "mode": "aroundScene"})).unwrap(); + assert!(dist3(arr3(&r["pivot"]), [320.0, 180.0, 0.0]) < 1e-6, "{}", r["pivot"]); +} + /// Orbit Around Scene without 3D layers turns about the comp's centre (#2586). #[test] fn orbit_around_scene_without_3d_layers_uses_the_comp_centre() { From 644c8f6f88e8e65950246905ee7a3f33bb0bb563 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 14 Nov 2026 18:18:18 +0100 Subject: [PATCH 17/38] ui-egui tests: DialogAnswer.paths is a Result on main (fix test build after merge) --- crates/ui-egui/src/menus/tests.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 556087782..da11416db 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -917,7 +917,7 @@ fn import_file_dialog_offers_and_imports_after_effects_projects() { assert!(many && exts.iter().any(|e| e == "aep") && exts.iter().any(|e| e == "aepx"), "{exts:?}"); assert!(exts.iter().any(|e| e == "png"), "footage too"); - super::frontend::dialog_answered(&mut app, crate::DialogAnswer { command: "file.import".into(), key: "paths", params: json!({}), paths: vec![aep] }); + super::frontend::dialog_answered(&mut app, crate::DialogAnswer { command: "file.import".into(), key: "paths", params: json!({}), paths: Ok(vec![aep]) }); let comp = app.session.project.item(app.session.active_comp_id().expect("a composition is open")).unwrap(); assert_eq!(comp.name, "Intro"); assert_eq!(app.session.project.item(comp.parent.expect("in a folder")).unwrap().name, "Intro.aep"); @@ -978,7 +978,7 @@ fn picked_projects_report_every_error() { std::fs::write(&aep, b"not an aep").unwrap(); std::fs::write(&ecproj, b"not a project").unwrap(); let paths = vec![aep.to_string_lossy().to_string(), ecproj.to_string_lossy().to_string()]; - super::frontend::dialog_answered(&mut app, crate::DialogAnswer { command: "file.import".into(), key: "paths", params: json!({}), paths: paths.clone() }); + super::frontend::dialog_answered(&mut app, crate::DialogAnswer { command: "file.import".into(), key: "paths", params: json!({}), paths: Ok(paths.clone()) }); let status = &app.ui.status; assert!(status.contains("broken.aep") && status.contains("broken.ecproj"), "{status}"); assert!(!status.contains('"'), "messages, not quoted JSON: {status}"); @@ -1009,7 +1009,7 @@ fn a_picked_project_with_losses_asks_and_the_next_waits() { source.execute("comp.new", json!({"name": "Intro", "width": 64, "height": 36, "frameRate": 30, "duration": 1})).unwrap(); source.execute("file.exportAep", json!({"path": intro, "allowLosses": true})).unwrap(); let paths = vec![lossy.to_string_lossy().to_string(), intro.clone()]; - super::frontend::dialog_answered(&mut app, crate::DialogAnswer { command: "file.import".into(), key: "paths", params: json!({}), paths }); + super::frontend::dialog_answered(&mut app, crate::DialogAnswer { command: "file.import".into(), key: "paths", params: json!({}), paths: Ok(paths) }); assert_eq!(app.dialog, Some(crate::Dialog::AepLosses)); assert_eq!(app.dialog_state.aep_losses.queue, [intro]); assert!(app.session.project.items.is_empty(), "nothing imported before the answer"); From 8fd534a54bc4f08b3a62cea979cf84004ab11ba2 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 14 Nov 2026 19:06:16 +0100 Subject: [PATCH 18/38] ui-egui tests: rustfmt --- crates/ui-egui/src/menus/tests.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index da11416db..f542cf9f5 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -978,7 +978,10 @@ fn picked_projects_report_every_error() { std::fs::write(&aep, b"not an aep").unwrap(); std::fs::write(&ecproj, b"not a project").unwrap(); let paths = vec![aep.to_string_lossy().to_string(), ecproj.to_string_lossy().to_string()]; - super::frontend::dialog_answered(&mut app, crate::DialogAnswer { command: "file.import".into(), key: "paths", params: json!({}), paths: Ok(paths.clone()) }); + super::frontend::dialog_answered( + &mut app, + crate::DialogAnswer { command: "file.import".into(), key: "paths", params: json!({}), paths: Ok(paths.clone()) }, + ); let status = &app.ui.status; assert!(status.contains("broken.aep") && status.contains("broken.ecproj"), "{status}"); assert!(!status.contains('"'), "messages, not quoted JSON: {status}"); From 9fe7f5d5b641f75a5840a2bd1d0571f5ece7493e Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 13:21:42 +0100 Subject: [PATCH 19/38] Export log shows where the time went: render, encode, write When an export or Render Queue job ends, the render log (and the effectcraft_export log target) gets one summary line: wall time, busy time of rendering, the encoder and writing the file (they overlap, so not a sum), the compositor and why, the encoder and its settings, and frames per second. Formats that cannot time a stage apart say so. effectcraft-cli render --json returns it as timing and timingSummary. #3713 --- apps/effectcraft-cli/src/main.rs | 5 +- crates/engine/src/background/offload.rs | 1 + crates/engine/src/background/offload/tests.rs | 4 +- crates/engine/src/cmd/render_queue.rs | 1 + crates/engine/src/render_queue.rs | 58 ++++++-- crates/export/src/encode.rs | 25 ++-- crates/export/src/lib.rs | 41 +++++- crates/export/src/pipeline.rs | 126 +++++++++++++++-- crates/export/src/webm.rs | 16 ++- crates/export/src/webm_av1.rs | 9 +- crates/export/tests/it/export_timing.rs | 130 ++++++++++++++++++ crates/export/tests/it/main.rs | 1 + crates/host/src/lib.rs | 1 + crates/project/src/render_queue.rs | 74 ++++++++++ docs/preferences.md | 5 + 15 files changed, 454 insertions(+), 43 deletions(-) create mode 100644 crates/export/tests/it/export_timing.rs diff --git a/apps/effectcraft-cli/src/main.rs b/apps/effectcraft-cli/src/main.rs index f52401a00..a80476f25 100644 --- a/apps/effectcraft-cli/src/main.rs +++ b/apps/effectcraft-cli/src/main.rs @@ -1018,7 +1018,10 @@ fn render(args: &Args, json_out: bool) -> Result<(), Failure> { match &it.status { RenderStatus::Done => { note!("done: {name} → {} in {:.2}s", it.last_output.as_deref().unwrap_or("?"), it.render_time.unwrap_or(0.0)); - results.push(json!({"comp": name, "output": it.last_output, "seconds": it.render_time})); + if let Some(t) = &it.last_timing { + note!("timing: {}", t.summary()); + } + results.push(json!({"comp": name, "output": it.last_output, "seconds": it.render_time, "timing": it.last_timing, "timingSummary": it.last_timing.as_ref().map(|t| t.summary())})); } RenderStatus::Failed(e) => failed.push(format!("{name}: {e}")), other => failed.push(format!("{name}: {}", other.label())), diff --git a/crates/engine/src/background/offload.rs b/crates/engine/src/background/offload.rs index b28527f02..cf27a0a9c 100644 --- a/crates/engine/src/background/offload.rs +++ b/crates/engine/src/background/offload.rs @@ -913,6 +913,7 @@ impl Session { status: RenderStatus::Failed(error), seconds: 0.0, output: None, + timing: None, }); } } diff --git a/crates/engine/src/background/offload/tests.rs b/crates/engine/src/background/offload/tests.rs index c08623189..495012ed8 100644 --- a/crates/engine/src/background/offload/tests.rs +++ b/crates/engine/src/background/offload/tests.rs @@ -136,7 +136,9 @@ fn protocol_round_trips() { for r in [ WorkerReply::Render { state: JobState { current: Some(3), done: 4, total: 10, items_total: 1, ..Default::default() } }, WorkerReply::Item { update: ItemUpdate::Started { id: 3, unix: 1_700_000_000 } }, - WorkerReply::Item { update: ItemUpdate::Finished { id: 3, status: RenderStatus::Failed("x".into()), seconds: 1.5, output: Some("/a.gif".into()) } }, + WorkerReply::Item { + update: ItemUpdate::Finished { id: 3, status: RenderStatus::Failed("x".into()), seconds: 1.5, output: Some("/a.gif".into()), timing: None }, + }, WorkerReply::Progress { done: 1, total: 2 }, WorkerReply::WarpPlan { key: [1, u64::MAX], diff --git a/crates/engine/src/cmd/render_queue.rs b/crates/engine/src/cmd/render_queue.rs index 9881f578f..a30eec1aa 100644 --- a/crates/engine/src/cmd/render_queue.rs +++ b/crates/engine/src/cmd/render_queue.rs @@ -697,6 +697,7 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { it.started = None; it.render_time = None; it.last_output = None; + it.last_timing = None; let id = it.id; proj.render_queue.insert(i + 1, it); Ok(id) diff --git a/crates/engine/src/render_queue.rs b/crates/engine/src/render_queue.rs index 7c10af40c..f8023307f 100644 --- a/crates/engine/src/render_queue.rs +++ b/crates/engine/src/render_queue.rs @@ -10,7 +10,9 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; -use effectcraft_project::render_queue::{OutputFormat, OutputModule, PostRenderAction, RenderQueueItem, RenderStatus, TemplateVars, expand_template}; +use effectcraft_project::render_queue::{ + OutputFormat, OutputModule, PostRenderAction, RenderQueueItem, RenderStatus, RenderTiming, TemplateVars, expand_template, +}; use effectcraft_project::{ItemId, ItemKind, LayerSource, Project}; use effectcraft_render::{ExprHost, FootageSource}; use serde::{Deserialize, Serialize}; @@ -88,6 +90,9 @@ pub struct ExportResult { /// Files that went to storage overflow folders. #[serde(skip_serializing_if = "Vec::is_empty")] pub overflow: Vec, + /// Where the time went and what ran the job (the render log's summary line). + #[serde(skip_serializing_if = "Option::is_none")] + pub timing: Option, } /// Encodes render queue items (implemented by the export layer). @@ -141,8 +146,19 @@ pub struct JobState { #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(tag = "event", rename_all = "camelCase")] pub enum ItemUpdate { - Started { id: u64, unix: u64 }, - Finished { id: u64, status: RenderStatus, seconds: f64, output: Option }, + Started { + id: u64, + unix: u64, + }, + Finished { + id: u64, + status: RenderStatus, + seconds: f64, + output: Option, + /// Where the time went (done items only). + #[serde(default)] + timing: Option, + }, } #[derive(Default)] @@ -194,8 +210,12 @@ impl JobShared { item.insert("statusLabel".into(), json!(RenderStatus::Rendering.label())); item.insert("started".into(), json!(unix)); item.insert("render_time".into(), Value::Null); + item.remove("last_timing"); } - ItemUpdate::Finished { status, seconds, output, .. } => { + ItemUpdate::Finished { status, seconds, output, timing, .. } => { + if let Some(timing) = timing { + item.insert("last_timing".into(), json!(timing)); + } item.insert("status".into(), json!(status)); item.insert("statusLabel".into(), json!(status.label())); item.insert("render_time".into(), json!(seconds)); @@ -361,7 +381,7 @@ async fn run_work(w: Work, shared: &JobShared, notify: &mut dyn FnMut(&JobShared for (k, modules) in w.items.iter().enumerate() { let Some((item, _)) = modules.first() else { continue }; if shared.cancel.load(Ordering::Relaxed) { - lock(&shared.updates).push(ItemUpdate::Finished { id: item.id, status: RenderStatus::UserStopped, seconds: 0.0, output: None }); + lock(&shared.updates).push(ItemUpdate::Finished { id: item.id, status: RenderStatus::UserStopped, seconds: 0.0, output: None, timing: None }); continue; } let t1 = web_time::Instant::now(); @@ -422,11 +442,11 @@ async fn run_work(w: Work, shared: &JobShared, notify: &mut dyn FnMut(&JobShared } let seconds = t1.elapsed().as_secs_f64(); let up = match r { - Ok(res) => ItemUpdate::Finished { id: item.id, status: RenderStatus::Done, seconds, output: Some(res.path) }, - Err(e) if e == CANCELLED => ItemUpdate::Finished { id: item.id, status: RenderStatus::UserStopped, seconds, output: None }, + Ok(res) => ItemUpdate::Finished { id: item.id, status: RenderStatus::Done, seconds, output: Some(res.path), timing: res.timing }, + Err(e) if e == CANCELLED => ItemUpdate::Finished { id: item.id, status: RenderStatus::UserStopped, seconds, output: None, timing: None }, Err(e) => { log::warn!("render queue: item {} failed: {e}", item.id); - ItemUpdate::Finished { id: item.id, status: RenderStatus::Failed(e), seconds, output: None } + ItemUpdate::Finished { id: item.id, status: RenderStatus::Failed(e), seconds, output: None, timing: None } } }; lock(&shared.updates).push(up); @@ -675,7 +695,13 @@ impl Session { let mut updates = lock(&sh.updates); for id in pending.into_iter().skip(completed) { if !updates.iter().any(|u| matches!(u, ItemUpdate::Finished { id: done, .. } if *done == id)) { - updates.push(ItemUpdate::Finished { id, status: RenderStatus::Failed(error.to_string()), seconds: 0.0, output: None }); + updates.push(ItemUpdate::Finished { + id, + status: RenderStatus::Failed(error.to_string()), + seconds: 0.0, + output: None, + timing: None, + }); } } lock(&sh.state).finished = true; @@ -707,7 +733,13 @@ impl Session { let done = finished.contains(id) || self.project.render_queue.iter().any(|i| i.id == *id && matches!(i.status, RenderStatus::Done | RenderStatus::Failed(_))); if !done { - lock(&j.shared.updates).push(ItemUpdate::Finished { id: *id, status: RenderStatus::UserStopped, seconds: 0.0, output: None }); + lock(&j.shared.updates).push(ItemUpdate::Finished { + id: *id, + status: RenderStatus::UserStopped, + seconds: 0.0, + output: None, + timing: None, + }); } } lock(&j.shared.state).finished = true; @@ -739,15 +771,19 @@ impl Session { i.status = RenderStatus::Rendering; i.started = Some(*unix); i.render_time = None; + i.last_timing = None; } } - ItemUpdate::Finished { id, status, seconds, output } => { + ItemUpdate::Finished { id, status, seconds, output, timing } => { if let Some(i) = p.render_queue.iter_mut().find(|i| i.id == *id) { i.status = status.clone(); i.render_time = Some(*seconds); if output.is_some() { i.last_output = output.clone(); } + if timing.is_some() { + i.last_timing = timing.clone(); + } if let (RenderStatus::Done, Some(o)) = (status, output) && !i.post_render.is_none() { diff --git a/crates/export/src/encode.rs b/crates/export/src/encode.rs index 8caad8dea..e229d40b5 100644 --- a/crates/export/src/encode.rs +++ b/crates/export/src/encode.rs @@ -9,7 +9,9 @@ use effectcraft_project::render_queue::{AudioFormat, Channels, OutputFormat, Pro use effectcraft_project::{Comp, ProjectSettings}; use effectcraft_time::{FrameRate, Tick}; use rayon::prelude::*; +use web_time::Instant; +use crate::pipeline::Stage; use crate::{Cx, ExportError, Report, Result, State, batch_size, wants_audio}; fn enc(e: impl std::fmt::Display) -> ExportError { @@ -381,7 +383,7 @@ pub(crate) async fn movie(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut St .beside(beside, batch_frames((first_end..next_end).collect()), || -> Result> { let mut pending = Vec::new(); for (k, px) in first.iter().enumerate() { - pending.extend(encode(&mut venc, px, k as u64)?); + pending.extend(job.timed(Stage::Encode, || encode(&mut venc, px, k as u64))?); } Ok(pending) }) @@ -465,8 +467,8 @@ pub(crate) async fn movie(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut St Ok(()) }; let frame_end_time = |k: u64| -> Tick { if k >= total { span_end } else { job.settings.frame_time(comp, k) } }; - write_video(&mut mux, pending)?; - write_audio_until(&mut mux, frame_end_time(first_end), &mut cursor)?; + job.timed(Stage::Write, || write_video(&mut mux, pending))?; + job.timed_if(with_audio, Stage::Audio, || write_audio_until(&mut mux, frame_end_time(first_end), &mut cursor))?; let mut i = first_end; while i < total { let end = (i + batch).min(total); @@ -475,10 +477,10 @@ pub(crate) async fn movie(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut St let (done, next) = job .beside(beside, batch_frames((end..next_end).collect()), || -> Result<()> { for (k, px) in frames.iter().enumerate() { - let ps = encode(&mut venc, px, i + k as u64)?; - write_video(&mut mux, ps)?; + let ps = job.timed(Stage::Encode, || encode(&mut venc, px, i + k as u64))?; + job.timed(Stage::Write, || write_video(&mut mux, ps))?; } - write_audio_until(&mut mux, frame_end_time(end), &mut cursor) + job.timed_if(with_audio, Stage::Audio, || write_audio_until(&mut mux, frame_end_time(end), &mut cursor)) }) .await?; done?; @@ -486,17 +488,22 @@ pub(crate) async fn movie(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut St st.advance(end - i)?; i = end; } - write_video(&mut mux, venc.flush()?)?; - write_audio_until(&mut mux, span_end, &mut cursor)?; + let tail = job.timed(Stage::Encode, || venc.flush())?; + job.timed(Stage::Write, || write_video(&mut mux, tail))?; + job.timed_if(with_audio, Stage::Audio, || write_audio_until(&mut mux, span_end, &mut cursor))?; if let Some((Audio::Aac(e), at)) = audio.as_mut() { + let t = Instant::now(); for au in e.flush() { mux.write_sample(*at, WriteSample { data: &au, duration: 1024, composition_offset: 0, is_sync: true }).map_err(mux_err)?; } + job.add_time(Stage::Audio, t); } + let t = Instant::now(); let out = mux.finish().map_err(mux_err)?; out.flush().map_err(mux_err)?; let bytes = file.finish()?; - Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio, log: None, overflow: vec![] }) + job.add_time(Stage::Write, t); + Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio, log: None, overflow: vec![], timing: Default::default() }) } #[cfg(test)] diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs index d9af7b2aa..d3ffc1c57 100644 --- a/crates/export/src/lib.rs +++ b/crates/export/src/lib.rs @@ -44,7 +44,9 @@ mod webm_av1; use web_time::Instant; -use effectcraft_project::render_queue::{AudioOutput, Channels, OutputFormat, OutputModule, RenderLog, RenderQuality, RenderSettings, sequence_path}; +use effectcraft_project::render_queue::{ + AudioOutput, Channels, OutputFormat, OutputModule, RenderLog, RenderQuality, RenderSettings, RenderTiming, sequence_path, +}; use effectcraft_project::{Comp, ItemId, Project}; use effectcraft_raster::Image; use effectcraft_render::{ExprHost, FootageSource}; @@ -168,7 +170,7 @@ impl Progress { } /// What an export produced. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct Report { /// The movie file, or the first file of a sequence. pub path: String, @@ -182,6 +184,8 @@ pub struct Report { pub log: Option, /// Files that went to an overflow folder. pub overflow: Vec, + /// Where the time went and what ran the job; the same as the summary line in the render log. + pub timing: RenderTiming, } /// Formats this build can write (all of them; kept as the hook for optional encoders). @@ -220,12 +224,23 @@ pub async fn export_async(job: &Job<'_>, progress: &mut dyn FnMut(&Progress) -> let render = RenderEnd(job.accel.filter(|_| job.options.caches.is_none())); let mut r = export_with(&cx, progress, t0).await; drop(render); + let wall = t0.elapsed().as_secs_f64(); + if let Err(e) = &r { + // A stopped or failed export gets its line too: slow ones are the ones people stop. + let how = if matches!(e, ExportError::Cancelled) { "stopped" } else { "failed" }; + log::info!(target: "effectcraft_export", "{}: {}", cx.job.options.label, cx.timing(wall, 0).summary_of_unfinished(how)); + } if matches!(r, Err(ExportError::Cancelled)) { cx.remove_cancelled_outputs()?; return r; } - let log = cx.write_log(&r, t0.elapsed().as_secs_f64()); + let timing = r.as_ref().ok().map(|rep| cx.timing(wall, rep.frames)); + if let Some(t) = &timing { + log::info!(target: "effectcraft_export", "{}: {}", cx.job.options.label, t.summary()); + } + let log = cx.write_log(&r, wall, timing.as_ref()); if let Ok(rep) = &mut r { + rep.timing = timing.unwrap_or_default(); rep.log = log; rep.overflow = cx.overflowed.lock().unwrap_or_else(|e| e.into_inner()).clone(); } @@ -341,7 +356,18 @@ async fn sequence(cx: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_>) st.advance(end - i)?; i = end; } - Ok(Report { path: sequence_path(cx.path, f0), frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: false, log: None, overflow: vec![] }) + Ok(Report { + path: sequence_path(cx.path, f0), + frames: 0, + width: w, + height: h, + seconds: 0.0, + bytes, + audio: false, + log: None, + overflow: vec![], + timing: Default::default(), + }) } struct StillOutput { @@ -443,6 +469,7 @@ async fn gif_export(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_ gif::Frame::from_rgba_speed(w as u16, h as u16, &mut px, 10) }) .await; + let t = Instant::now(); for mut f in frames { clock += cs_per_frame; let d = (clock.round() as u64).saturating_sub(emitted).max(1); @@ -453,12 +480,16 @@ async fn gif_export(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_ } enc.write_frame(&f).map_err(|e| ExportError::Encode(e.to_string()))?; } + // The GIF writer compresses as it writes: the two are not measured apart. + job.add_time(pipeline::Stage::EncodeWrite, t); st.advance(end - i)?; i = end; } + let t = Instant::now(); drop(enc); let bytes = file.finish()?; - Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: false, log: None, overflow: vec![] }) + job.add_time(pipeline::Stage::EncodeWrite, t); + Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: false, log: None, overflow: vec![], timing: Default::default() }) } #[cfg(test)] diff --git a/crates/export/src/pipeline.rs b/crates/export/src/pipeline.rs index a0e4980ec..e1494fabb 100644 --- a/crates/export/src/pipeline.rs +++ b/crates/export/src/pipeline.rs @@ -4,7 +4,9 @@ use std::sync::Mutex; -use effectcraft_project::render_queue::{AlphaMode, Channels, CurrentOrOff, EffectsMode, FrameSample, RenderLog, ResizeQuality, SwitchOverride, log_path}; +use effectcraft_project::render_queue::{ + AlphaMode, Channels, CurrentOrOff, EffectsMode, FrameSample, OutputFormat, OutputModule, RenderLog, RenderTiming, ResizeQuality, SwitchOverride, log_path, +}; use effectcraft_project::{BitDepth, Comp, Project}; use effectcraft_raster::Image; use effectcraft_render::{Backend, LayerCache, RenderOpts, Renderer}; @@ -272,6 +274,46 @@ pub(crate) struct Cx<'a> { /// Files written to an overflow folder. pub overflowed: Mutex>, written: Mutex>, + /// Busy time per stage, for the log's timing line (#3713). + phases: Phases, +} + +/// The stages of a job whose busy time is measured. +#[derive(Clone, Copy)] +pub(crate) enum Stage { + /// Rendering frames (and, for formats that encode and write inside the frame loop, that too). + Render, + Encode, + Write, + Audio, + /// An encoder that writes as it encodes (the GIF writer): the two are not apart. + EncodeWrite, +} + +/// Busy time per [`Stage`] in nanoseconds. The stages overlap (the encoder works on one batch +/// while the next renders), so each is its own total, not a share of the wall time. +#[derive(Default)] +struct Phases { + nanos: [std::sync::atomic::AtomicU64; 5], + /// Bit per stage that was timed: a stage a format doesn't have has no time, not zero. + used: std::sync::atomic::AtomicU8, +} + +impl Phases { + fn add(&self, stage: Stage, since: Instant) { + self.used.fetch_or(1 << stage as u8, std::sync::atomic::Ordering::Relaxed); + let n = u64::try_from(since.elapsed().as_nanos()).unwrap_or(u64::MAX); + if let Some(slot) = self.nanos.get(stage as usize) { + slot.fetch_add(n, std::sync::atomic::Ordering::Relaxed); + } + } + fn seconds(&self, stage: Stage) -> f64 { + self.nanos.get(stage as usize).map_or(0.0, |n| n.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e9) + } + /// The stage's busy time, or `None` when the format never timed it. + fn measured(&self, stage: Stage) -> Option { + (self.used.load(std::sync::atomic::Ordering::Relaxed) & (1 << stage as u8) != 0).then(|| self.seconds(stage)) + } } /// A job's layer caches: its own, or those of the Render Queue run it belongs to. @@ -355,6 +397,7 @@ impl<'a> Cx<'a> { frame_times, overflowed: Mutex::new(vec![]), written: Mutex::new(vec![]), + phases: Phases::default(), }; if let Some(c) = cx.fixed_choice(std::env::var(RENDERER_ENV).ok().as_deref()) { cx.decide(c); @@ -362,6 +405,42 @@ impl<'a> Cx<'a> { cx } + /// Run `f` and add its time to `stage`'s busy time. Formats that encode and write outside + /// the frame loop time those stages this way; a stage never timed is reported as measured + /// together with rendering. + pub(crate) fn timed(&self, stage: Stage, f: impl FnOnce() -> T) -> T { + let t = Instant::now(); + let out = f(); + self.add_time(stage, t); + out + } + + /// [`Cx::timed`] when `on`; otherwise just run `f` (a stage the job doesn't have). + pub(crate) fn timed_if(&self, on: bool, stage: Stage, f: impl FnOnce() -> T) -> T { + if on { self.timed(stage, f) } else { f() } + } + + /// Add the time since `since` to `stage`'s busy time (where a closure cannot wrap the work). + pub(crate) fn add_time(&self, stage: Stage, since: Instant) { + self.phases.add(stage, since); + } + + /// Where the job's time went, for the render log and the [`crate::Report`]. + pub(crate) fn timing(&self, wall: f64, frames: u64) -> RenderTiming { + RenderTiming { + wall_seconds: wall, + render_seconds: self.phases.seconds(Stage::Render), + encode_seconds: self.phases.measured(Stage::Encode), + write_seconds: self.phases.measured(Stage::Write), + encode_write_seconds: self.phases.measured(Stage::EncodeWrite), + audio_seconds: self.phases.measured(Stage::Audio), + frames, + frames_per_second: if wall > 0.0 { frames as f64 / wall } else { 0.0 }, + renderer: self.choice().map_or_else(|| "none was needed".to_string(), |c| describe_choice(&c)), + encoder: describe_encoder(self.job.output), + } + } + /// The project's compositor: the GPU's for GPU Acceleration with an accelerator. fn project_renderer(&self) -> crate::JobRenderer { if self.project.settings.gpu_acceleration && self.job.accel.is_some() { crate::JobRenderer::Gpu } else { crate::JobRenderer::Cpu } @@ -485,15 +564,19 @@ impl<'a> Cx<'a> { /// Output frames `ks`, each mapped by `f` (encoding): rendered in parallel batches, or one /// by one in passes when readbacks are deferred ([`Cx::deferred`]). pub async fn frames(&self, comp: &Comp, ks: Vec, f: impl Fn(u64, Image) -> T + Sync + Send) -> Vec { - if self.deferred() { + let t = Instant::now(); + let out = if self.deferred() { let mut out = Vec::with_capacity(ks.len()); for k in ks { let img = self.frame_async(comp, k).await; out.push(f(k, img)); } - return out; - } - self.render_frames(ks, |k, on| self.frame_on(comp, k, on), f) + out + } else { + self.render_frames(ks, |k, on| self.frame_on(comp, k, on), f) + }; + self.phases.add(Stage::Render, t); + out } /// `render` then `encode` over the frames `ks` on the job's compositor, results in `ks` @@ -807,14 +890,17 @@ impl<'a> Cx<'a> { fallback: impl Fn(u64, Image) -> T + Sync + Send, ) -> Vec { // As in `frames`: once the GPU has stopped for good, the rest render in parallel. - self.render_frames( + let t = Instant::now(); + let out = self.render_frames( ks, |k, on| self.yuv420_frame(comp, k, w, h, on).ok_or_else(|| self.frame_on(comp, k, on)), |k, r| match r { Ok(p) => planes(p), Err(img) => fallback(k, img), }, - ) + ); + self.phases.add(Stage::Render, t); + out } /// Output Module ▸ Crop, then Resize. @@ -927,7 +1013,7 @@ impl<'a> Cx<'a> { } /// Write the render log next to the output, as the Log setting asks. Returns its path. - pub fn write_log(&self, result: &Result, seconds: f64) -> Option { + pub fn write_log(&self, result: &Result, seconds: f64, timing: Option<&RenderTiming>) -> Option { let level = self.job.options.log; // Errors Only: a log for failures (a user stop is not an error). if level == RenderLog::ErrorsOnly && matches!(result, Ok(_) | Err(crate::ExportError::Cancelled)) { @@ -946,6 +1032,13 @@ impl<'a> Cx<'a> { if let Some(c) = self.choice() { s.push_str(&format!("Renderer: {}\n", describe_choice(&c))); } + if let Some(t) = timing { + s.push_str(&format!( + "Timing: {} +", + t.summary() + )); + } if self.backend() == crate::JobRenderer::Gpu && let Some((n, why)) = &*self.gpu_frames.lock().unwrap_or_else(std::sync::PoisonError::into_inner) { @@ -982,6 +1075,23 @@ impl<'a> Cx<'a> { } } +/// The render log's account of the encoder: every encoder here is built in and runs on the +/// CPU (no hardware encoder is used), with the codec settings of the Output Module. +pub(crate) fn describe_encoder(om: &OutputModule) -> String { + let rate = |om: &OutputModule| match om.codec.rate_control { + effectcraft_project::render_queue::RateControlMode::Bitrate => format!("{} kbps", om.bitrate_kbps), + effectcraft_project::render_queue::RateControlMode::Quality => format!("constant quality {}", om.codec.quality), + }; + let settings = match om.format { + OutputFormat::H264 => format!(", {} kbps", om.bitrate_kbps), + OutputFormat::Hevc | OutputFormat::Av1 => format!(", profile {}, {}", om.codec.profile.label(), rate(om)), + OutputFormat::ProRes => format!(", profile {}", om.prores_profile.label()), + OutputFormat::WebM => format!(", {:?}{}", om.webm_codec, if om.webm_bitrate { format!(", {} kbps", om.bitrate_kbps) } else { String::new() }), + _ => String::new(), + }; + format!("{}{settings}, built-in software encoder (not a hardware encoder)", om.format.label()) +} + /// The render log's account of a job's compositor: which, why, and what was measured. pub(crate) fn describe_choice(c: &Choice) -> String { let name = match c.renderer { diff --git a/crates/export/src/webm.rs b/crates/export/src/webm.rs index 2802ac928..8525be0f1 100644 --- a/crates/export/src/webm.rs +++ b/crates/export/src/webm.rs @@ -17,8 +17,10 @@ use std::io::{Seek, SeekFrom, Write}; use effectcraft_project::Comp; use effectcraft_project::render_queue::{AudioFormat, Channels}; use effectcraft_time::{TICKS_PER_SECOND, Tick}; +use web_time::Instant; use crate::encode::{mix, pcm_bytes}; +use crate::pipeline::Stage; use crate::{Cx, Report, Result, State, batch_size, io, wants_audio}; pub(crate) const OPUS_RATE: u32 = 48_000; @@ -263,6 +265,7 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta let pixels: Vec> = job.frames(comp, (i..end).collect(), |_, img| job.pixels(&img, comp, if alpha { Channels::Rgba } else { colour_channels }, w, h)).await; let mut frames: Vec = Vec::with_capacity(pixels.len()); + let t = Instant::now(); for (j, px) in pixels.iter().enumerate() { let (color, a) = rayon::join( || { @@ -280,11 +283,14 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta frames.push(Frame { ms: frame_ms(k), track: 1, key: color.key, prev_ms: (k > 0).then(|| frame_ms(k - 1)), data: color.data, alpha: a }); } drop(pixels); + job.add_time(Stage::Encode, t); let t_end = if end >= total { span_end } else { job.settings.frame_time(comp, end) }; - audio_until(t_end, &mut frames, end >= total); + job.timed_if(with_audio, Stage::Audio, || audio_until(t_end, &mut frames, end >= total)); + let t = Instant::now(); let c = cluster(&mut frames); file.write_all(&c).map_err(io)?; seg_len += c.len() as u64; + job.add_time(Stage::Write, t); st.advance(end - i)?; i = end; } @@ -305,7 +311,7 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta file.write_all(&size).map_err(io)?; file.seek(SeekFrom::End(0)).map_err(io)?; let bytes = file.finish()?; - Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio, log: None, overflow: vec![] }) + Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio, log: None, overflow: vec![], timing: Default::default() }) } // ---------------------------------------------------------------- audio-only outputs @@ -349,7 +355,7 @@ pub(crate) fn audio_file(job: &Cx, comp: &Comp, aiff: bool, st: &mut State) -> R let sample = start + done as i64; let t = Tick::from_units(sample, i64::from(sr)); let t = if t.to_units_floor(i64::from(sr)) < sample { Tick(t.0.saturating_add(1)) } else { t }; - pcm.extend(pcm_bytes(&mix(job, t, k, sr), fmt, aiff)); + pcm.extend(job.timed(Stage::Audio, || pcm_bytes(&mix(job, t, k, sr), fmt, aiff))); done += k; let now = (done as u64 * total_frames / n.max(1) as u64).min(total_frames); if now > reported && st.total > 0 { @@ -421,11 +427,13 @@ pub(crate) fn audio_file(job: &Cx, comp: &Comp, aiff: bool, st: &mut State) -> R out.push(0); } } + let t = Instant::now(); let path = job.place(job.path, out.len() as u64); let mut file = job.create(&path)?; file.write_all(&out).map_err(io)?; let bytes = file.finish()?; - Ok(Report { path, frames: 0, width: 0, height: 0, seconds: 0.0, bytes, audio: true, log: None, overflow: vec![] }) + job.add_time(Stage::Write, t); + Ok(Report { path, frames: 0, width: 0, height: 0, seconds: 0.0, bytes, audio: true, log: None, overflow: vec![], timing: Default::default() }) } #[cfg(test)] diff --git a/crates/export/src/webm_av1.rs b/crates/export/src/webm_av1.rs index 2e75257f7..15e849c31 100644 --- a/crates/export/src/webm_av1.rs +++ b/crates/export/src/webm_av1.rs @@ -12,6 +12,7 @@ use effectcraft_time::{TICKS_PER_SECOND, Tick}; use crate::encode::VideoEncoder; use crate::encode::mix; +use crate::pipeline::Stage; use crate::webm::{CLUSTER, EBML, INFO, OPUS_RATE, SEGMENT, TRACK_ENTRY, TRACKS, el, el_float, el_str, el_uint, id_bytes, opus_encoder, vint}; use crate::{Cx, Report, Result, State, batch_size, io, wants_audio}; @@ -154,13 +155,13 @@ pub(crate) async fn webm_av1(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut let frames: Vec> = job.frames(comp, (i..end).collect(), |_, img| job.pixels(&img, comp, channels, w, h)).await; for (j, px) in frames.iter().enumerate() { let k = i + j as u64; - for p in venc.encode(px, k)? { + for p in job.timed(Stage::Encode, || venc.encode(px, k))? { blocks.push(Block { ms: frame_ms(k), track: 1, key: p.key, data: p.data }); } } let t_end = if end >= total { span_end } else { job.settings.frame_time(comp, end) }; - audio_until(t_end, &mut blocks, end >= total); - flush_blocks(&mut blocks, &mut file, &mut seg_len)?; + job.timed_if(with_audio, Stage::Audio, || audio_until(t_end, &mut blocks, end >= total)); + job.timed(Stage::Write, || flush_blocks(&mut blocks, &mut file, &mut seg_len))?; st.advance(end - i)?; i = end; } @@ -175,5 +176,5 @@ pub(crate) async fn webm_av1(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut file.write_all(&size).map_err(io)?; file.seek(SeekFrom::End(0)).map_err(io)?; let bytes = file.finish()?; - Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio, log: None, overflow: vec![] }) + Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio, log: None, overflow: vec![], timing: Default::default() }) } diff --git a/crates/export/tests/it/export_timing.rs b/crates/export/tests/it/export_timing.rs new file mode 100644 index 000000000..621988bce --- /dev/null +++ b/crates/export/tests/it/export_timing.rs @@ -0,0 +1,130 @@ +//! The summary line of an export (#3713): where the time went and what ran the job. + +use std::sync::{Arc, Mutex}; + +use effectcraft_color::Label; +use effectcraft_export::render_queue::{OutputFormat, OutputModule, RenderLog, RenderSettings, TimeSpan}; +use effectcraft_export::{Job, JobOptions, Sink, export}; +use effectcraft_project::{Comp, ItemId, ItemKind, LayerSource, Project, Solid, build}; +use effectcraft_render::NoFootage; +use effectcraft_time::{FrameRate, Tick}; + +fn project() -> (Project, ItemId) { + let mut p = Project::default(); + let comp = Comp::new(64, 48, FrameRate::new(30, 1), Tick::from_seconds_f64(1.0)); + let sid = p.add_item("Solid", Label::Red, None, ItemKind::Solid(Solid { color: [0.9, 0.5, 0.1], width: 64, height: 48, pixel_aspect: 1.0 })); + let layer = build::layer(&mut p, &comp, "Solid", LayerSource::Solid { item: sid }, (64, 48), None); + let mut comp = comp; + comp.layers = vec![layer].into(); + let cid = p.add_item("Comp 1", Label::Sandstone, None, ItemKind::Comp(comp.into())); + (p, cid) +} + +#[test] +fn a_movie_export_reports_where_the_time_went() { + let (p, cid) = project(); + let settings = RenderSettings { time_span: TimeSpan::LengthOfComp, ..Default::default() }; + let om = OutputModule::for_format(OutputFormat::H264); + let files: Arc)>>> = Arc::default(); + let sink_files = files.clone(); + let sink: &Sink = &move |path: &str, data: Vec| sink_files.lock().unwrap().push((path.to_string(), data)); + let job = Job { + project: &p, + footage: &NoFootage, + expr: None, + accel: None, + comp: cid, + settings: &settings, + output: &om, + path: "/out/timing.mp4", + sink: Some(sink), + options: JobOptions { log: RenderLog::PlusSettings, label: "#1 Comp 1".into(), ..Default::default() }, + nested_switches: true, + }; + let r = export(&job, &mut |_| true).expect("export"); + let t = &r.timing; + assert_eq!(t.frames, 30); + assert!(t.wall_seconds > 0.0); + // The movie formats time encoding and writing apart from rendering. + let (encode, write) = (t.encode_seconds.expect("encode time"), t.write_seconds.expect("write time")); + for (name, secs) in [("render", t.render_seconds), ("encode", encode), ("write", write)] { + assert!(secs >= 0.0 && secs <= t.wall_seconds, "{name} {secs} s of {} s wall", t.wall_seconds); + } + assert!(t.render_seconds > 0.0 && encode > 0.0, "{t:?}"); + assert_eq!(t.audio_seconds, None); + assert!((t.frames_per_second - 30.0 / t.wall_seconds).abs() < 1e-9); + assert!(t.renderer.starts_with("Software Rendering"), "{}", t.renderer); + assert!(t.encoder.contains("H.264") && t.encoder.contains("software"), "{}", t.encoder); + + let line = t.summary(); + for part in + ["export took", "30 frames", "frames/s", "overlap", "rendering frames", "encoder", "writing output", "Compositor: Software Rendering", "Encoder: H.264"] + { + assert!(line.contains(part), "{part:?} missing from {line}"); + } + // The render log carries the same line. + let files = files.lock().unwrap(); + let log = files.iter().find(|(path, _)| path.ends_with(".txt")).map(|(_, d)| String::from_utf8_lossy(d).into_owned()).expect("render log"); + assert!(log.contains(&format!("Timing: {line}")), "{log}"); +} + +fn job_of<'a>(p: &'a Project, cid: ItemId, settings: &'a RenderSettings, om: &'a OutputModule, path: &'a str, sink: &'a Sink) -> Job<'a> { + Job { + project: p, + footage: &NoFootage, + expr: None, + accel: None, + comp: cid, + settings, + output: om, + path, + sink: Some(sink), + options: Default::default(), + nested_switches: true, + } +} + +#[test] +fn an_image_sequence_says_the_stages_are_measured_together() { + let (p, cid) = project(); + let settings = RenderSettings { time_span: TimeSpan::LengthOfComp, ..Default::default() }; + let om = OutputModule::for_format(OutputFormat::PngSequence); + let sink: &Sink = &|_: &str, _: Vec| {}; + let r = export(&job_of(&p, cid, &settings, &om, "/out/timing_[#####].png", sink), &mut |_| true).expect("export"); + let t = &r.timing; + assert_eq!((t.encode_seconds, t.write_seconds, t.encode_write_seconds), (None, None, None)); + assert!(t.render_seconds <= t.wall_seconds); + assert!(t.summary().contains("rendering, encoding and writing measured together"), "{}", t.summary()); +} + +#[test] +fn gif_and_webm_time_the_stages_they_have() { + let (p, cid) = project(); + let settings = RenderSettings { time_span: TimeSpan::LengthOfComp, ..Default::default() }; + let sink: &Sink = &|_: &str, _: Vec| {}; + let gif = OutputModule::for_format(OutputFormat::Gif); + let t = export(&job_of(&p, cid, &settings, &gif, "/out/timing.gif", sink), &mut |_| true).expect("gif").timing; + assert_eq!((t.encode_seconds, t.write_seconds), (None, None)); + let both = t.encode_write_seconds.expect("encode and write time"); + assert!(both >= 0.0 && both <= t.wall_seconds && t.render_seconds <= t.wall_seconds); + assert!(t.summary().contains("encoding and writing output measured together"), "{}", t.summary()); + + let webm = OutputModule::for_format(OutputFormat::WebM); + let t = export(&job_of(&p, cid, &settings, &webm, "/out/timing.webm", sink), &mut |_| true).expect("webm").timing; + let (e, w) = (t.encode_seconds.expect("encode"), t.write_seconds.expect("write")); + assert!(e <= t.wall_seconds && w <= t.wall_seconds && t.render_seconds <= t.wall_seconds, "{t:?}"); +} + +#[test] +fn a_stopped_export_has_a_summary_without_a_frame_count() { + let t = effectcraft_export::render_queue::RenderTiming { + wall_seconds: 2.0, + render_seconds: 1.5, + renderer: "Software Rendering (x)".into(), + encoder: "H.264".into(), + ..Default::default() + }; + let line = t.summary_of_unfinished("stopped"); + assert!(line.starts_with("export stopped after 2.00 s. Busy time per stage"), "{line}"); + assert!(!line.contains("frames/s"), "{line}"); +} diff --git a/crates/export/tests/it/main.rs b/crates/export/tests/it/main.rs index 77dc22b49..441d0551d 100644 --- a/crates/export/tests/it/main.rs +++ b/crates/export/tests/it/main.rs @@ -3,6 +3,7 @@ mod audio_sample_positions; mod av1_encoder; mod banding; +mod export_timing; mod exr_scene_linear; mod h264_gpu_yuv; mod hevc_av1_roundtrip; diff --git a/crates/host/src/lib.rs b/crates/host/src/lib.rs index 7212fd730..6416d6dc0 100644 --- a/crates/host/src/lib.rs +++ b/crates/host/src/lib.rs @@ -83,6 +83,7 @@ impl Exporter for FileExporter { audio: r.audio, log: r.log, overflow: r.overflow, + timing: Some(r.timing), }), Err(effectcraft_export::ExportError::Cancelled) => Err(effectcraft_engine::render_queue::CANCELLED.into()), Err(e) => Err(e.to_string()), diff --git a/crates/project/src/render_queue.rs b/crates/project/src/render_queue.rs index b935c2fc8..cef9b6ec2 100644 --- a/crates/project/src/render_queue.rs +++ b/crates/project/src/render_queue.rs @@ -1473,6 +1473,76 @@ impl RenderStatus { } } +/// Where one export's time went, and what it ran on (the render log's summary line, #3713). +/// The stages overlap (the encoder works on one batch while the next renders), so the +/// `*_seconds` are each stage's busy time and not a sum; none of them is more than `wall_seconds`. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct RenderTiming { + /// The whole job, start to end. + pub wall_seconds: f64, + /// Time rendering frames (the compositor, including the conversion to the encoder's pixels). + /// For formats that encode and write inside the frame loop (image sequences) it also holds + /// the encoding and writing: `encode_seconds` and `write_seconds` are `None`. + pub render_seconds: f64, + /// Time in the video encoder (`None`: not measured apart from rendering). + #[serde(skip_serializing_if = "Option::is_none")] + pub encode_seconds: Option, + /// Time writing and muxing the output file (`None`: not measured apart from rendering). + #[serde(skip_serializing_if = "Option::is_none")] + pub write_seconds: Option, + /// Time in an encoder that writes as it encodes (GIF): encoding and writing are not apart. + #[serde(skip_serializing_if = "Option::is_none")] + pub encode_write_seconds: Option, + /// Time mixing and encoding the audio track (`None`: no separate audio stage). + #[serde(skip_serializing_if = "Option::is_none")] + pub audio_seconds: Option, + pub frames: u64, + /// Frames per second of wall time over the whole job. + pub frames_per_second: f64, + /// The compositor and why it was used. + pub renderer: String, + /// The encoder: name, software or hardware, codec settings. + pub encoder: String, +} + +impl RenderTiming { + /// The one-line summary for the render log. + pub fn summary(&self) -> String { + let head = format!("export took {:.2} s for {} frames ({:.2} frames/s)", self.wall_seconds, self.frames, self.frames_per_second); + self.line(&head) + } + + /// The summary of a job that was stopped or failed `how` (the frames done are not counted). + pub fn summary_of_unfinished(&self, how: &str) -> String { + self.line(&format!("export {how} after {:.2} s", self.wall_seconds)) + } + + fn line(&self, head: &str) -> String { + let (r, mut s) = (self.render_seconds, String::new()); + if self.encode_seconds.is_none() && self.write_seconds.is_none() && self.encode_write_seconds.is_none() { + s.push_str(&format!("rendering, encoding and writing measured together {r:.2} s")); + } else if self.encode_write_seconds.is_some() { + // The GIF palette is quantised on the render threads, so it counts as rendering. + s.push_str(&format!("rendering frames (GIF: including palette quantizing) {r:.2} s")); + } else if r > 0.0 { + s.push_str(&format!("rendering frames {r:.2} s")); + } + for (label, v) in [ + ("encoder", self.encode_seconds), + ("writing output", self.write_seconds), + ("encoding and writing output measured together", self.encode_write_seconds), + ("audio", self.audio_seconds), + ] { + if let Some(v) = v { + s.push_str(&format!("{}{label} {v:.2} s", if s.is_empty() { "" } else { ", " })); + } + } + let stages = s; + format!("{head}. Busy time per stage (the stages overlap, so this is not a sum): {stages}. Compositor: {}. Encoder: {}", self.renderer, self.encoder) + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RenderQueueItem { /// Stable id (unique within the queue). @@ -1495,6 +1565,9 @@ pub struct RenderQueueItem { /// Resolved path of the last render (first file for sequences). #[serde(default)] pub last_output: Option, + /// Where the last render's time went (see [`RenderTiming`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_timing: Option, /// Further Output Modules (Composition ▸ Add Output Module): the same frames are encoded /// once per module. #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -1624,6 +1697,7 @@ impl RenderQueueItem { started: None, render_time: None, last_output: None, + last_timing: None, extra_outputs: vec![], post_render: PostRenderAction::None, log: RenderLog::ErrorsOnly, diff --git a/docs/preferences.md b/docs/preferences.md index c35d2c793..def2f7dcc 100644 --- a/docs/preferences.md +++ b/docs/preferences.md @@ -114,6 +114,11 @@ Commands (CLI, MCP, control channel): names it and why). `EFFECTCRAFT_RQ_RENDERER` set to `gpu` or `cpu` skips it and renders on that compositor; `auto` (the default) measures. A queue item's later output modules reuse its first one's choice, and Software Rendering projects always render on the CPU. + When a job ends, the render log gets one `Timing:` line (and the log target `effectcraft_export` + the same line): the wall time, the busy time of rendering, the encoder and writing the file + (the stages overlap, so they are not a sum), the compositor and why, the encoder and its + settings, and frames per second ([#3713](https://github.com/storytold/effectcraft/issues/3713)). + `effectcraft-cli render --json` returns it as `timing` and `timingSummary`. - `threeD.defaultRenderer`: Default 3D Renderer - `labels.N.name` / `labels.N.color`: the 16 label names and colours, used by the Label menu, the timeline, project panel, render queue and viewer handles From 4a1a845b21404fd52fa1e5c0ff304c6679b07c42 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 23:42:42 +0100 Subject: [PATCH 20/38] Camera tools: a layer nearer than the near plane is not under the cursor (#3259 review) --- crates/render/src/three_d/camera.rs | 5 +++++ crates/render/src/three_d/tests.rs | 15 +++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/crates/render/src/three_d/camera.rs b/crates/render/src/three_d/camera.rs index 776f153d1..fae868ccd 100644 --- a/crates/render/src/three_d/camera.rs +++ b/crates/render/src/three_d/camera.rs @@ -760,6 +760,11 @@ pub fn point_under(cam: &CameraState, w: f64, h: f64, px: [f64; 2], quads: &[[Ve if !(t.is_finite() && t > 1e-6) || best.is_some_and(|b| b <= t) { continue; } + // (a perspective camera sees nothing nearer than its near plane: such a layer is not under + // the cursor; `t` is the view depth, as the direction's part along the view is 1) + if !cam.ortho && t < NEAR { + continue; + } let hit = o + dir * t; let side = |i: usize| { let (a, b) = (q[i % 4], q[(i + 1) % 4]); diff --git a/crates/render/src/three_d/tests.rs b/crates/render/src/three_d/tests.rs index c329377dd..e8d194e89 100644 --- a/crates/render/src/three_d/tests.rs +++ b/crates/render/src/three_d/tests.rs @@ -874,6 +874,21 @@ fn camera_tools_never_produce_nan_cameras() { nan_free(&Rig { eye: super::camera::point_under(&cam, CW, CH, [10.0, 10.0], &[], down.poi), ..down }); } +/// #3259 review: a layer between the eye and the near plane is not on screen, so it is not under +/// the cursor; the layer behind it is. An orthographic camera has no such cut. +#[test] +fn a_layer_nearer_than_the_near_plane_is_not_under_the_cursor() { + let r = Rig::from_view(&default_view_cam(View3D::Default, CW, CH)); + let cam = r.state(); + let quad = [vec3(0.0, 0.0, 0.0), vec3(CW, 0.0, 0.0), vec3(CW, CH, 0.0), vec3(0.0, CH, 0.0)]; + // A big plane 0.5 in front of the eye (the near plane is 1). + let (f, rt, dn) = (cam.forward(), cam.right(), cam.down()); + let c = cam.eye + f * 0.5; + let inside = [c - rt * 1e5 - dn * 1e5, c + rt * 1e5 - dn * 1e5, c + rt * 1e5 + dn * 1e5, c - rt * 1e5 + dn * 1e5]; + let p = super::camera::point_under(&cam, CW, CH, [960.0, 540.0], &[quad, inside], r.poi); + assert!(cam.depth(p) > 1.0 && (p - vec3(960.0, 540.0, 0.0)).length() < 1e-6, "the layer behind it is picked: {p:?}"); +} + /// Checks that the point under the cursor lies on the nearest layer it hits, else at the POI depth. #[test] fn the_point_under_the_cursor_is_on_the_layer_it_hits() { From bff19871490fd3239895b68c1db285ac01e523da Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 00:53:49 +0100 Subject: [PATCH 21/38] Export log: the encoder line names the ProRes profile and the WebM codec that are written (#3724 review) --- crates/engine/src/render_queue.rs | 2 ++ crates/export/src/pipeline.rs | 34 +++++++++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/render_queue.rs b/crates/engine/src/render_queue.rs index f8023307f..b45932217 100644 --- a/crates/engine/src/render_queue.rs +++ b/crates/engine/src/render_queue.rs @@ -431,6 +431,8 @@ async fn run_work(w: Work, shared: &JobShared, notify: &mut dyn FnMut(&JobShared !shared.cancel.load(Ordering::Relaxed) }) .await; + // (the item's timing and output are those of the first output module's export; the + // others, and the later segments of a split output, are not part of it) match rr { Ok(res) if mi == 0 => r = Ok(res), Ok(_) => {} diff --git a/crates/export/src/pipeline.rs b/crates/export/src/pipeline.rs index e1494fabb..d6e5bc46b 100644 --- a/crates/export/src/pipeline.rs +++ b/crates/export/src/pipeline.rs @@ -1078,18 +1078,29 @@ impl<'a> Cx<'a> { /// The render log's account of the encoder: every encoder here is built in and runs on the /// CPU (no hardware encoder is used), with the codec settings of the Output Module. pub(crate) fn describe_encoder(om: &OutputModule) -> String { + use effectcraft_project::render_queue::{Channels, ProResProfile, WebmVideoCodec}; let rate = |om: &OutputModule| match om.codec.rate_control { effectcraft_project::render_queue::RateControlMode::Bitrate => format!("{} kbps", om.bitrate_kbps), effectcraft_project::render_queue::RateControlMode::Quality => format!("constant quality {}", om.codec.quality), }; + let mut label = om.format.label().to_string(); let settings = match om.format { OutputFormat::H264 => format!(", {} kbps", om.bitrate_kbps), OutputFormat::Hevc | OutputFormat::Av1 => format!(", profile {}, {}", om.codec.profile.label(), rate(om)), - OutputFormat::ProRes => format!(", profile {}", om.prores_profile.label()), + // (alpha needs a 4444 flavour: the encoder promotes the profile, so the log names that one) + OutputFormat::ProRes => { + let profile = if om.channels == Channels::Rgba && !om.prores_profile.is_4444() { ProResProfile::P4444 } else { om.prores_profile }; + format!(", profile {}", profile.label()) + } + // (WebM carries VP9 or AV1: the log names the one that is written) + OutputFormat::WebM if om.webm_codec == WebmVideoCodec::Av1 => { + label = "WebM (AV1 + Opus)".to_string(); + format!(", profile {}, {}", om.codec.profile.label(), rate(om)) + } OutputFormat::WebM => format!(", {:?}{}", om.webm_codec, if om.webm_bitrate { format!(", {} kbps", om.bitrate_kbps) } else { String::new() }), _ => String::new(), }; - format!("{}{settings}, built-in software encoder (not a hardware encoder)", om.format.label()) + format!("{label}{settings}, built-in software encoder (not a hardware encoder)") } /// The render log's account of a job's compositor: which, why, and what was measured. @@ -1187,6 +1198,25 @@ mod tests { use rayon::prelude::*; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + /// #3724 review: the log names the profile and codec that are written: alpha promotes ProRes + /// to 4444, and WebM with AV1 says AV1 (not VP9). + #[test] + fn the_encoder_description_names_what_is_written() { + use effectcraft_project::render_queue::{Channels, ProResProfile, WebmVideoCodec}; + let mut om = OutputModule { format: OutputFormat::ProRes, prores_profile: ProResProfile::Hq, channels: Channels::Rgb, ..OutputModule::default() }; + let hq = describe_encoder(&om); + assert!(hq.contains(ProResProfile::Hq.label()) && !hq.contains("4444"), "{hq}"); + om.channels = Channels::Rgba; + let alpha = describe_encoder(&om); + assert!(alpha.contains(ProResProfile::P4444.label()) && !alpha.contains(ProResProfile::Hq.label()), "{alpha}"); + let mut web = OutputModule { format: OutputFormat::WebM, webm_codec: WebmVideoCodec::Av1, ..OutputModule::default() }; + let av1 = describe_encoder(&web); + assert!(av1.starts_with("WebM (AV1 + Opus)") && !av1.contains("VP9") && av1.contains("profile"), "{av1}"); + web.webm_codec = WebmVideoCodec::Vp9; + let vp9 = describe_encoder(&web); + assert!(vp9.starts_with("WebM (VP9 + Opus)") && !vp9.contains("AV1"), "{vp9}"); + } + /// Dither may round a colour up while alpha rounds down; premultiplied colour stays at or /// below the written alpha at every pixel. #[test] From 49b6be954cfd5d6be2763f79e545abf05fdaef47 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 00:54:48 +0100 Subject: [PATCH 22/38] Export log: a failed job's render log carries its timing line; docs say when the line is written (#3724 review) --- crates/export/src/lib.rs | 8 ++++++-- crates/export/src/pipeline.rs | 11 +++++------ crates/export/tests/it/export_timing.rs | 19 +++++++++++++++++++ docs/preferences.md | 6 ++++-- 4 files changed, 34 insertions(+), 10 deletions(-) diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs index d3ffc1c57..87673c218 100644 --- a/crates/export/src/lib.rs +++ b/crates/export/src/lib.rs @@ -225,10 +225,14 @@ pub async fn export_async(job: &Job<'_>, progress: &mut dyn FnMut(&Progress) -> let mut r = export_with(&cx, progress, t0).await; drop(render); let wall = t0.elapsed().as_secs_f64(); + // (what a failed export got done: its render log carries the line too, with the compositor) + let mut unfinished = None; if let Err(e) = &r { // A stopped or failed export gets its line too: slow ones are the ones people stop. let how = if matches!(e, ExportError::Cancelled) { "stopped" } else { "failed" }; - log::info!(target: "effectcraft_export", "{}: {}", cx.job.options.label, cx.timing(wall, 0).summary_of_unfinished(how)); + let t = cx.timing(wall, 0); + log::info!(target: "effectcraft_export", "{}: {}", cx.job.options.label, t.summary_of_unfinished(how)); + unfinished = Some(t); } if matches!(r, Err(ExportError::Cancelled)) { cx.remove_cancelled_outputs()?; @@ -238,7 +242,7 @@ pub async fn export_async(job: &Job<'_>, progress: &mut dyn FnMut(&Progress) -> if let Some(t) = &timing { log::info!(target: "effectcraft_export", "{}: {}", cx.job.options.label, t.summary()); } - let log = cx.write_log(&r, wall, timing.as_ref()); + let log = cx.write_log(&r, wall, timing.as_ref().or(unfinished.as_ref())); if let Ok(rep) = &mut r { rep.timing = timing.unwrap_or_default(); rep.log = log; diff --git a/crates/export/src/pipeline.rs b/crates/export/src/pipeline.rs index d6e5bc46b..027493dc2 100644 --- a/crates/export/src/pipeline.rs +++ b/crates/export/src/pipeline.rs @@ -1033,11 +1033,10 @@ impl<'a> Cx<'a> { s.push_str(&format!("Renderer: {}\n", describe_choice(&c))); } if let Some(t) = timing { - s.push_str(&format!( - "Timing: {} -", - t.summary() - )); + // (a failed job has no frame count: the line says what ran before it stopped) + let line = if result.is_err() { t.summary_of_unfinished("failed") } else { t.summary() }; + s.push_str(&format!("Timing: {line} +")); } if self.backend() == crate::JobRenderer::Gpu && let Some((n, why)) = &*self.gpu_frames.lock().unwrap_or_else(std::sync::PoisonError::into_inner) @@ -1078,7 +1077,7 @@ impl<'a> Cx<'a> { /// The render log's account of the encoder: every encoder here is built in and runs on the /// CPU (no hardware encoder is used), with the codec settings of the Output Module. pub(crate) fn describe_encoder(om: &OutputModule) -> String { - use effectcraft_project::render_queue::{Channels, ProResProfile, WebmVideoCodec}; + use effectcraft_project::render_queue::{ProResProfile, WebmVideoCodec}; let rate = |om: &OutputModule| match om.codec.rate_control { effectcraft_project::render_queue::RateControlMode::Bitrate => format!("{} kbps", om.bitrate_kbps), effectcraft_project::render_queue::RateControlMode::Quality => format!("constant quality {}", om.codec.quality), diff --git a/crates/export/tests/it/export_timing.rs b/crates/export/tests/it/export_timing.rs index 621988bce..da93847b6 100644 --- a/crates/export/tests/it/export_timing.rs +++ b/crates/export/tests/it/export_timing.rs @@ -115,6 +115,25 @@ fn gif_and_webm_time_the_stages_they_have() { assert!(e <= t.wall_seconds && w <= t.wall_seconds && t.render_seconds <= t.wall_seconds, "{t:?}"); } +/// #3724 review: a failed export's render log carries the timing line too (with the compositor +/// that ran), not only a finished one's. +#[test] +fn a_failed_export_logs_its_timing_line_too() { + let (p, _) = project(); + let settings = RenderSettings { time_span: TimeSpan::LengthOfComp, ..Default::default() }; + let om = OutputModule::for_format(OutputFormat::H264); + let files: Arc)>>> = Arc::default(); + let sink_files = files.clone(); + let sink: &Sink = &move |path: &str, data: Vec| sink_files.lock().unwrap().push((path.to_string(), data)); + // A composition that is not there: the export fails before it renders anything. + let job = job_of(&p, ItemId(9999), &settings, &om, "/out/failed.mp4", sink); + assert!(export(&job, &mut |_| true).is_err(), "no such composition"); + let files = files.lock().unwrap(); + let log = files.iter().find(|(path, _)| path.ends_with(".txt")).map(|(_, d)| String::from_utf8_lossy(d).into_owned()).expect("a failed job writes its log"); + assert!(log.contains("Result: Failed"), "{log}"); + assert!(log.contains("Timing: export failed after"), "{log}"); +} + #[test] fn a_stopped_export_has_a_summary_without_a_frame_count() { let t = effectcraft_export::render_queue::RenderTiming { diff --git a/docs/preferences.md b/docs/preferences.md index def2f7dcc..3f49467ae 100644 --- a/docs/preferences.md +++ b/docs/preferences.md @@ -114,8 +114,10 @@ Commands (CLI, MCP, control channel): names it and why). `EFFECTCRAFT_RQ_RENDERER` set to `gpu` or `cpu` skips it and renders on that compositor; `auto` (the default) measures. A queue item's later output modules reuse its first one's choice, and Software Rendering projects always render on the CPU. - When a job ends, the render log gets one `Timing:` line (and the log target `effectcraft_export` - the same line): the wall time, the busy time of rendering, the encoder and writing the file + When a job ends, the log target `effectcraft_export` gets one timing line, and the render log + gets it as a `Timing:` line when its Log setting writes a log for that outcome (under the + default Errors Only, failed jobs only; a failed job's line says how long it ran and what ran + before it stopped): the wall time, the busy time of rendering, the encoder and writing the file (the stages overlap, so they are not a sum), the compositor and why, the encoder and its settings, and frames per second ([#3713](https://github.com/storytold/effectcraft/issues/3713)). `effectcraft-cli render --json` returns it as `timing` and `timingSummary`. From fb8b302909bcc6a04b69328d1fe5023b544015e9 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 01:02:46 +0100 Subject: [PATCH 23/38] Export log: formatting (#3724) --- crates/export/src/pipeline.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/export/src/pipeline.rs b/crates/export/src/pipeline.rs index 027493dc2..0bffaca98 100644 --- a/crates/export/src/pipeline.rs +++ b/crates/export/src/pipeline.rs @@ -1035,8 +1035,10 @@ impl<'a> Cx<'a> { if let Some(t) = timing { // (a failed job has no frame count: the line says what ran before it stopped) let line = if result.is_err() { t.summary_of_unfinished("failed") } else { t.summary() }; - s.push_str(&format!("Timing: {line} -")); + s.push_str(&format!( + "Timing: {line} +" + )); } if self.backend() == crate::JobRenderer::Gpu && let Some((n, why)) = &*self.gpu_frames.lock().unwrap_or_else(std::sync::PoisonError::into_inner) From f76ae41f05a13d017afaa862c239174ecd9ebcbd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 09:06:32 -0800 Subject: [PATCH 24/38] Cargo.lock: list constant_time_eq where cargo sorts it The gate's lockfile check failed because cargo moves the entry ahead of core-foundation 0.9.4. --- Cargo.lock | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bf70392a0..932d79115 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -997,6 +997,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + [[package]] name = "core-foundation" version = "0.9.4" @@ -1007,12 +1013,6 @@ dependencies = [ "libc", ] -[[package]] -name = "constant_time_eq" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" - [[package]] name = "core-foundation" version = "0.10.1" From 5af43b67b5001e7796a667f3dc638524262d3051 Mon Sep 17 00:00:00 2001 From: Christopher Linnett Date: Tue, 17 Nov 2026 22:36:17 +0800 Subject: [PATCH 25/38] #3808: Interpret Footage: the dialog shows the footage the command will change Opened with `item`/`items` (an agent's `ui.menu.invoke`), the Interpret Footage dialog filled its fields from the Project selection while OK ran the command on the named item, so that item took another footage's interpretation. The dialog and the commands now share one target resolution, `commands::interpretation_targets`: `items`, else `item`, else the selection, keeping footage (for Proxy, items with a proxy). The dialog shows its first item. A named item that is missing, not footage or (Proxy) without a proxy opens no dialog: the command runs and reports that there is nothing to interpret, as Proxy already did. Interpret Footage used to accept such ids and change nothing. Use Proxy and the proxy commands' enablement share the "has a proxy" filter. --- crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/file_more.rs | 20 ++++- crates/engine/src/cmd/proxy.rs | 15 ++-- crates/engine/src/tests/proxy.rs | 71 +++++++++++++++++ crates/ui-egui/src/menus/tests.rs | 41 ++++++++++ crates/ui-egui/src/panels/forms.rs | 119 ++++++++++++++++++++++++++++- 6 files changed, 255 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index fefe01950..270e36ca7 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -165,6 +165,7 @@ use super::commands; pub use aep::is_aep_path; pub use enabled::always; pub(crate) use enabled::{has_comp, has_keys, has_layers, has_project_selection, not_yet, not_yet_run}; +pub use file_more::interpretation_targets; pub use params::match_path_of; pub(crate) use params::{ b_p, bad, comp_id, f_p, frontend, layer_mut, layer_p, layers_or, layers_p, merge_p, popup_options, resolve_effect_path, resolve_layer, selectable, diff --git a/crates/engine/src/cmd/file_more.rs b/crates/engine/src/cmd/file_more.rs index df9b0f076..d39cdeb52 100644 --- a/crates/engine/src/cmd/file_more.rs +++ b/crates/engine/src/cmd/file_more.rs @@ -30,10 +30,13 @@ fn has_comp_selection(s: &Session) -> std::result::Result<(), String> { if s.state.project_selection.iter().any(|i| s.project.comp(*i).is_some()) { Ok(()) } else { Err("select compositions in the Project panel".into()) } } +fn is_footage(s: &Session, i: ItemId) -> bool { + matches!(s.project.item(i).map(|x| &x.kind), Some(ItemKind::Footage(_))) +} + /// Selected project items that are footage (or the source of the selected layer). fn selected_footage(s: &Session) -> Vec { - let mut v: Vec = - s.state.project_selection.iter().copied().filter(|i| matches!(s.project.item(*i).map(|x| &x.kind), Some(ItemKind::Footage(_)))).collect(); + let mut v: Vec = s.state.project_selection.iter().copied().filter(|i| is_footage(s, *i)).collect(); if v.is_empty() && let Some(c) = s.active_comp() { @@ -56,6 +59,17 @@ fn items_p(s: &Session, p: &Value) -> Vec { } } +/// The items `file.interpretFootage` changes for parameters `p` (with `proxy`, the items whose +/// proxy `file.interpretProxy` changes): `items`/`item`, else the selection, keeping only +/// footage (items with a proxy). The Interpret Footage dialog shows the first one, so OK +/// writes its settings back to the footage they came from. +pub fn interpretation_targets(s: &Session, p: &Value, proxy: bool) -> Vec { + if proxy { + return super::proxy::proxied(s, p); + } + items_p(s, p).into_iter().filter(|i| is_footage(s, *i)).collect() +} + /// `project.newFolder {name?, parent?, items?}`. With `items` (ids or names), they move into the /// new folder in the same undo step: Project items dropped on the panel's New Folder button, as /// in After Effects (#3196). A folder can't end up inside itself. @@ -1006,7 +1020,7 @@ pub(crate) fn guess_alpha(s: &Session, item: ItemId, f: &Footage) -> Option<(Alp } fn interpret(s: &mut Session, p: &Value) -> Result { - let items = items_p(s, p); + let items = interpretation_targets(s, p, false); if items.is_empty() { return Err(bad("file.interpretFootage", "select footage")); } diff --git a/crates/engine/src/cmd/proxy.rs b/crates/engine/src/cmd/proxy.rs index 42633b913..5e8cea337 100644 --- a/crates/engine/src/cmd/proxy.rs +++ b/crates/engine/src/cmd/proxy.rs @@ -29,13 +29,14 @@ fn has_targets(s: &Session) -> std::result::Result<(), String> { if targets(s, &Value::Null).is_empty() { Err("select footage or a composition in the Project panel".into()) } else { Ok(()) } } +/// The targets that have a proxy: what Use Proxy and Interpret Footage ▸ Proxy change. +pub(crate) fn proxied(s: &Session, p: &Value) -> Vec { + targets(s, p).into_iter().filter(|i| s.project.item(*i).is_some_and(|x| x.proxy.is_some())).collect() +} + fn has_proxy(s: &Session) -> std::result::Result<(), String> { has_targets(s)?; - if targets(s, &Value::Null).iter().any(|i| s.project.item(*i).is_some_and(|x| x.proxy.is_some())) { - Ok(()) - } else { - Err("the selected items have no proxy".into()) - } + if proxied(s, &Value::Null).is_empty() { Err("the selected items have no proxy".into()) } else { Ok(()) } } /// Probe a proxy file through the importer. @@ -93,7 +94,7 @@ fn set_proxy_none(s: &mut Session, p: &Value) -> Result { /// The Project panel's proxy switch: use the proxy (filled box) or the full-resolution source. fn use_proxy(s: &mut Session, p: &Value) -> Result { const C: &str = "file.useProxy"; - let items: Vec = targets(s, p).into_iter().filter(|i| s.project.item(*i).is_some_and(|x| x.proxy.is_some())).collect(); + let items = proxied(s, p); if items.is_empty() { return Err(bad(C, "the selected items have no proxy")); } @@ -113,7 +114,7 @@ fn use_proxy(s: &mut Session, p: &Value) -> Result { /// File ▸ Interpret Footage ▸ Proxy: Interpret Footage settings for the proxy file. fn interpret_proxy(s: &mut Session, p: &Value) -> Result { const C: &str = "file.interpretProxy"; - let items: Vec = targets(s, p).into_iter().filter(|i| s.project.item(*i).is_some_and(|x| x.proxy.is_some())).collect(); + let items = super::file_more::interpretation_targets(s, p, true); if items.is_empty() { return Err(bad(C, "the selected items have no proxy")); } diff --git a/crates/engine/src/tests/proxy.rs b/crates/engine/src/tests/proxy.rs index 40927b8b8..e411c6979 100644 --- a/crates/engine/src/tests/proxy.rs +++ b/crates/engine/src/tests/proxy.rs @@ -316,6 +316,77 @@ fn interpret_proxy_settings_apply_to_the_proxy() { assert_eq!(f.alpha, AlphaMode::Straight, "the main footage keeps its interpretation"); } +/// What both Interpret Footage commands change, and what their dialog shows first: `items` in +/// order, else `item`, else the Project selection (for Main, the selected layers' footage when no +/// footage is selected), keeping footage only, or for Proxy only items with a proxy. A missing or +/// other item is no target, so the command reports that there is nothing to interpret. +#[test] +fn interpretation_targets_follow_the_parameters_then_the_selection() { + let mut s = session(); + let a = import(&mut s, "/m/red16.png"); + let b = import(&mut s, "/m/blue8.png"); + let c = import(&mut s, "/m/wide.png"); + s.execute("comp.new", json!({"name": "C", "width": 16, "height": 16, "frameRate": 10, "duration": 1})).unwrap(); + let comp = s.active_comp_id().unwrap(); + s.execute("file.setProxy", json!({"item": b.0, "path": "/m/half.png"})).unwrap(); + s.execute("file.setProxy", json!({"item": comp.0, "path": "/m/half.png"})).unwrap(); + let t = |s: &Session, p: serde_json::Value, proxy: bool| crate::commands::interpretation_targets(s, &p, proxy); + s.state.project_selection = vec![a]; + // Footage. + assert_eq!(t(&s, json!({"item": b.0}), false), [b]); + assert_eq!(t(&s, json!({"items": [c.0, b.0]}), false), [c, b]); + assert_eq!(t(&s, json!({"items": [b.0], "item": c.0}), false), [b], "`items` comes first"); + assert_eq!(t(&s, json!({}), false), [a]); + assert_eq!(t(&s, serde_json::Value::Null, false), [a]); + assert_eq!(t(&s, json!({"items": [999, comp.0, b.0]}), false), [b]); + for none in [json!({"item": 999}), json!({"item": comp.0}), json!({"items": []})] { + assert!(t(&s, none.clone(), false).is_empty(), "{none}"); + } + // Proxies: footage and compositions that have one. + assert_eq!(t(&s, json!({"item": b.0}), true), [b]); + assert_eq!(t(&s, json!({"items": [a.0, comp.0, b.0]}), true), [comp, b]); + for none in [json!({}), json!({"item": 999}), json!({"item": a.0}), json!({"item": c.0})] { + assert!(t(&s, none.clone(), true).is_empty(), "{none}"); + } + s.state.project_selection = vec![comp, a, b]; + assert_eq!(t(&s, json!({}), false), [a, b]); + assert_eq!(t(&s, json!({}), true), [comp, b]); + // No footage selected: the selected layer's footage. + s.execute("layer.addItem", json!({"item": c.0})).unwrap(); + s.state.project_selection.clear(); + assert!(!s.state.selected_layers.is_empty()); + assert_eq!(t(&s, json!({}), false), [c]); + s.state.project_selection = vec![comp]; + assert_eq!(t(&s, json!({}), false), [c], "a selected composition is no footage"); + // The commands change nothing when nothing is a target. + let before = s.project.clone(); + for (command, params) in [ + ("file.interpretFootage", json!({"item": 999, "loop": 2})), + ("file.interpretFootage", json!({"item": comp.0, "loop": 2})), + ("file.interpretProxy", json!({"item": 999, "loop": 2})), + ("file.interpretProxy", json!({"item": a.0, "loop": 2})), + ] { + let e = s.execute(command, params.clone()).unwrap_err().to_string(); + let usual = if command == "file.interpretProxy" { "no proxy" } else { "select footage" }; + assert!(e.contains(usual), "{command} {params}: {e}"); + } + assert_eq!(*s.project, *before); +} + +/// Use Proxy switches only the targets that have a proxy, and the first of those decides which +/// way: an item without one, named first, is skipped. +#[test] +fn use_proxy_skips_targets_without_a_proxy() { + let mut s = session(); + let plain = import(&mut s, "/m/red16.png"); + let full = import(&mut s, "/m/blue8.png"); + s.execute("file.setProxy", json!({"item": full.0, "path": "/m/half.png"})).unwrap(); + let r = s.execute("file.useProxy", json!({"items": [plain.0, full.0]})).unwrap(); + assert_eq!(r, json!({"items": [full.0], "on": false})); + assert!(!s.project.item(full).unwrap().proxy.as_ref().unwrap().enabled); + assert!(s.project.item(plain).unwrap().proxy.is_none()); +} + /// Agents and the control channel run commands through `execute_checked`, which refuses keys a /// params doc does not list. The Interpret Footage commands list every key they read. #[test] diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 68c8d3f43..71af77420 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -955,6 +955,47 @@ fn the_unlabeled_alpha_question_does_not_replace_an_open_dialog() { assert_eq!(app.dialog, Some(crate::Dialog::Form), "with no dialog open it asks"); } +/// The unlabeled alpha question opens Interpret Footage on the imported footage, not on the +/// footage selected before, and OK interprets the imported footage only. +#[test] +fn the_unlabeled_alpha_question_opens_on_the_imported_footage() { + use effectcraft_engine::project::{AlphaMode, Footage, FootageKind, ItemKind}; + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + let ctx = egui::Context::default(); + let still = |path: &str, loop_count: u32, alpha: AlphaMode| { + ItemKind::Footage(Footage { + path: path.into(), + kind: FootageKind::Still, + width: 4, + height: 4, + has_video: true, + loop_count, + alpha, + ..Default::default() + }) + }; + let project = std::sync::Arc::make_mut(&mut app.session.project); + let before = project.add_item("before.png", Default::default(), None, still("/m/before.png", 1, AlphaMode::Straight)); + let matte = project.add_item("matte.tga", Default::default(), None, still("/m/matte.tga", 4, AlphaMode::Premultiplied)); + app.session.state.project_selection = vec![before]; + super::frontend(&mut app, &ctx, "file.interpretFootage", json!({"item": matte.0, "reason": "unlabeledAlpha"})).unwrap(); + assert_eq!(app.dialog, Some(crate::Dialog::Form)); + let params = app.dialog_state.form.params(); + assert_eq!((params["loop"].clone(), params["alpha"].clone()), (json!(4.0), json!("premultiplied")), "{params}"); + // OK with Alpha ▸ Ignore. + let alpha = app.dialog_state.form.fields.iter_mut().find(|f| f.key == "alpha").map(|f| &mut f.kind); + let Some(crate::panels::forms::FieldKind::Choice { options, sel }) = alpha else { panic!("no Alpha choice") }; + *sel = options.iter().position(|(_, v)| v == "ignore").unwrap(); + let form = app.dialog_state.form.clone(); + app.session.execute(&form.command, form.params()).unwrap(); + let alpha_of = |app: &EffectcraftApp, id| match app.session.project.item(id).map(|i| &i.kind) { + Some(ItemKind::Footage(f)) => (f.alpha, f.loop_count), + _ => panic!("not footage"), + }; + assert_eq!(alpha_of(&app, matte), (AlphaMode::Ignore, 4)); + assert_eq!(alpha_of(&app, before), (AlphaMode::Straight, 1)); +} + /// File ▸ Import ▸ File… and Multiple Files… offer projects next to footage; File ▸ Replace /// Footage offers footage only. #[test] diff --git a/crates/ui-egui/src/panels/forms.rs b/crates/ui-egui/src/panels/forms.rs index 08aa9337b..5b350b6f7 100644 --- a/crates/ui-egui/src/panels/forms.rs +++ b/crates/ui-egui/src/panels/forms.rs @@ -233,9 +233,11 @@ fn new_comp_from_selection_form(s: &effectcraft_engine::Session) -> (String, Vec ) } -/// The Interpret Footage dialog for the selected footage (or its proxy), if there is one. +/// The Interpret Footage dialog for the footage the command changes (or its proxy), if there is +/// one: the first item the engine resolves from `items`/`item` in `base`, else from the selection. fn interpret_footage_form(s: &effectcraft_engine::Session, proxy: bool, base: &mut Value) -> Option<(String, Vec)> { - let f = s.state.project_selection.first().and_then(|i| s.project.item(*i)).and_then(|it| match (&it.kind, &it.proxy) { + let targets = effectcraft_engine::commands::interpretation_targets(s, base, proxy); + let f = targets.first().and_then(|i| s.project.item(*i)).and_then(|it| match (&it.kind, &it.proxy) { (_, Some(px)) if proxy => Some(px.footage.clone()), (effectcraft_engine::project::ItemKind::Footage(f), _) if !proxy => Some(f.clone()), _ => None, @@ -1255,6 +1257,119 @@ mod tests { } } + /// Footage items A, B and C with different interpretations (with `proxy`, each also has a + /// proxy interpreted differently again), A selected: (app, [A, B, C]). + fn three_clips(proxy: bool) -> (EffectcraftApp, [effectcraft_engine::project::ItemId; 3]) { + use effectcraft_engine::project::{AlphaMode, ColorSpace, Footage, FootageKind, ItemKind, Proxy}; + use effectcraft_engine::time::{FrameRate, Tick}; + let clip = |fps: f64, loop_count: u32, alpha: AlphaMode, color_profile: Option, invert_alpha: bool| Footage { + path: format!("/m/clip{fps}.mov"), + kind: FootageKind::Video, + width: 4, + height: 4, + has_video: true, + duration: Tick::from_seconds_f64(1.0), + frame_rate: FrameRate::from_f64(fps), + native_rate: Some(FrameRate::from_f64(fps)), + loop_count, + alpha, + color_profile, + invert_alpha, + ..Default::default() + }; + let looks = [ + (24.0, 1, AlphaMode::Straight, None, false), + (30.0, 3, AlphaMode::Premultiplied, Some(ColorSpace::Rec709), true), + (50.0, 2, AlphaMode::Ignore, Some(ColorSpace::DisplayP3), false), + ]; + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + let project = std::sync::Arc::make_mut(&mut app.session.project); + let ids = looks.map(|(fps, loops, alpha, profile, invert)| { + if !proxy { + return project.add_item("clip.mov", Default::default(), None, ItemKind::Footage(clip(fps, loops, alpha, profile, invert))); + } + let main = clip(fps + 1.0, 5, AlphaMode::Straight, Some(ColorSpace::Rec2020), false); + let id = project.add_item("clip.mov", Default::default(), None, ItemKind::Footage(main)); + let footage = clip(fps, loops, alpha, profile, invert); + if let Some(it) = project.item_mut(id) { + it.proxy = Some(Box::new(Proxy { footage, enabled: true })); + } + id + }); + app.session.state.project_selection = vec![ids[0]]; + (app, ids) + } + + /// Interpret Footage opened on named footage (`item`, or the first of `items`) through + /// `ui.menu.invoke` shows that footage's settings, not the selected footage's, so OK without + /// edits leaves it as it was (and gives the other named items its settings); with neither, it + /// shows the selection. Interpret Footage ▸ Proxy does the same with the items' proxies. + #[test] + fn interpret_footage_opens_on_the_named_footage() { + for command in ["file.interpretFootage", "file.interpretProxy"] { + let proxy = command == "file.interpretProxy"; + let (mut app, [a, b, c]) = three_clips(proxy); + let ctx = egui::Context::default(); + let shown = |app: &EffectcraftApp| { + let p = app.dialog_state.form.params(); + (p["frameRate"].clone(), p["loop"].clone(), p["alpha"].clone(), p["colorProfile"].clone(), p["invertAlpha"].clone()) + }; + let b_shows = (json!(30.0), json!(3.0), json!("premultiplied"), json!("rec709"), json!(true)); + let (a_was, b_was) = (app.session.project.item(a).cloned(), app.session.project.item(b).cloned()); + for params in [json!({"item": b.0}), json!({"items": [b.0, c.0]})] { + app.dialog = None; + crate::menus::invoke(&mut app, &ctx, command, params.clone()).unwrap(); + assert!(matches!(app.dialog, Some(Dialog::Form)), "{command}: {params}"); + assert_eq!(app.dialog_state.form.command, command); + assert_eq!(shown(&app), b_shows, "{command}: {params}"); + // OK. + let form = app.dialog_state.form.clone(); + app.session.execute(&form.command, form.params()).unwrap(); + assert_eq!(app.session.project.item(b).cloned(), b_was, "{command}: {params} leaves B as it was"); + assert_eq!(app.session.project.item(a).cloned(), a_was, "{command}: {params} leaves the selected A alone"); + } + // C took B's settings. + app.dialog = None; + crate::menus::invoke(&mut app, &ctx, command, json!({"item": c.0})).unwrap(); + assert_eq!(shown(&app), b_shows, "{command}: C"); + // Neither: the selection. + app.dialog = None; + crate::menus::invoke(&mut app, &ctx, command, json!({})).unwrap(); + assert!(matches!(app.dialog, Some(Dialog::Form)), "{command}"); + assert_eq!(shown(&app), (json!(24.0), json!(1.0), json!("straight"), json!("auto"), json!(false)), "{command}: {{}}"); + } + } + + /// Interpret Footage named at an item it can't change (missing, not footage, or for Proxy + /// without a proxy) doesn't open on the selected footage: as with nothing selected, the + /// command runs and reports that there is nothing to interpret, and nothing changes. + #[test] + fn interpret_footage_named_at_no_footage_opens_no_dialog() { + for command in ["file.interpretFootage", "file.interpretProxy"] { + let proxy = command == "file.interpretProxy"; + let (mut app, [a, ..]) = three_clips(true); + let ctx = egui::Context::default(); + app.session.execute("comp.new", json!({"name": "Comp", "width": 4, "height": 4, "frameRate": 24, "duration": 1})).unwrap(); + let comp = app.session.active_comp_id().unwrap(); + // Footage without a proxy. + let kind = app.session.project.item(a).unwrap().kind.clone(); + let plain = std::sync::Arc::make_mut(&mut app.session.project).add_item("plain.mov", Default::default(), None, kind); + app.session.state.project_selection = vec![a]; + let mut invalid = vec![json!({"item": 999}), json!({"items": [999]}), json!({"item": comp.0})]; + if proxy { + invalid.push(json!({"item": plain.0})); + } + let before = app.session.project.clone(); + for params in invalid { + let e = crate::menus::invoke(&mut app, &ctx, command, params.clone()).unwrap_err(); + assert!(app.dialog.is_none(), "{command}: {params}"); + assert!(e.contains(if proxy { "no proxy" } else { "select footage" }), "{command}: {params}: {e}"); + assert_eq!(app.ui.status, e, "the status line says why"); + } + assert_eq!(*app.session.project, *before); + } + } + /// Interpret Footage on an image sequence with a gap says the previous frame is held there /// (what the media pool shows), not colour bars. #[test] From 337a6ba677d344a3d347b1da971f55fed5e5e7f5 Mon Sep 17 00:00:00 2001 From: Christopher Linnett Date: Wed, 18 Nov 2026 00:07:03 +0800 Subject: [PATCH 26/38] #3808: Interpret Footage keeps main's results for targets that aren't footage `file.interpretFootage` resolves its items as before and skips what isn't footage, so an explicit missing id, composition or solid succeeds and changes nothing again, and a script setting a solid's mainSource.conformFrameRate doesn't throw. The dialog still opens on the first item `interpretation_targets` gives, which is the first footage the command changes, and opens no dialog when that is none. Tests pin Main's result for those targets, Proxy's existing error, and the script setter on a solid. --- crates/engine/src/cmd/file_more.rs | 6 +++--- crates/engine/src/tests/proxy.rs | 28 +++++++++++++++++----------- crates/script/src/tests.rs | 14 ++++++++++++++ crates/ui-egui/src/panels/forms.rs | 18 +++++++++++++----- 4 files changed, 47 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/file_more.rs b/crates/engine/src/cmd/file_more.rs index d39cdeb52..22df9054e 100644 --- a/crates/engine/src/cmd/file_more.rs +++ b/crates/engine/src/cmd/file_more.rs @@ -61,8 +61,8 @@ fn items_p(s: &Session, p: &Value) -> Vec { /// The items `file.interpretFootage` changes for parameters `p` (with `proxy`, the items whose /// proxy `file.interpretProxy` changes): `items`/`item`, else the selection, keeping only -/// footage (items with a proxy). The Interpret Footage dialog shows the first one, so OK -/// writes its settings back to the footage they came from. +/// footage (items with a proxy), as the commands skip the rest. The Interpret Footage dialog +/// shows the first one, so OK writes its settings back to the footage they came from. pub fn interpretation_targets(s: &Session, p: &Value, proxy: bool) -> Vec { if proxy { return super::proxy::proxied(s, p); @@ -1020,7 +1020,7 @@ pub(crate) fn guess_alpha(s: &Session, item: ItemId, f: &Footage) -> Option<(Alp } fn interpret(s: &mut Session, p: &Value) -> Result { - let items = interpretation_targets(s, p, false); + let items = items_p(s, p); if items.is_empty() { return Err(bad("file.interpretFootage", "select footage")); } diff --git a/crates/engine/src/tests/proxy.rs b/crates/engine/src/tests/proxy.rs index e411c6979..23e67118d 100644 --- a/crates/engine/src/tests/proxy.rs +++ b/crates/engine/src/tests/proxy.rs @@ -319,7 +319,8 @@ fn interpret_proxy_settings_apply_to_the_proxy() { /// What both Interpret Footage commands change, and what their dialog shows first: `items` in /// order, else `item`, else the Project selection (for Main, the selected layers' footage when no /// footage is selected), keeping footage only, or for Proxy only items with a proxy. A missing or -/// other item is no target, so the command reports that there is nothing to interpret. +/// other item is no target: Main skips it and changes nothing, Proxy reports that nothing named +/// has a proxy. #[test] fn interpretation_targets_follow_the_parameters_then_the_selection() { let mut s = session(); @@ -358,19 +359,24 @@ fn interpretation_targets_follow_the_parameters_then_the_selection() { assert_eq!(t(&s, json!({}), false), [c]); s.state.project_selection = vec![comp]; assert_eq!(t(&s, json!({}), false), [c], "a selected composition is no footage"); - // The commands change nothing when nothing is a target. + // Nothing named is a target: Main succeeds and changes nothing (scripts set a solid's + // mainSource.conformFrameRate through it), Proxy refuses. Named with footage, only the + // footage changes. + s.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap(); + let solid = s.project.items.values().find(|i| matches!(i.kind, ItemKind::Solid(_))).unwrap().id; let before = s.project.clone(); - for (command, params) in [ - ("file.interpretFootage", json!({"item": 999, "loop": 2})), - ("file.interpretFootage", json!({"item": comp.0, "loop": 2})), - ("file.interpretProxy", json!({"item": 999, "loop": 2})), - ("file.interpretProxy", json!({"item": a.0, "loop": 2})), - ] { - let e = s.execute(command, params.clone()).unwrap_err().to_string(); - let usual = if command == "file.interpretProxy" { "no proxy" } else { "select footage" }; - assert!(e.contains(usual), "{command} {params}: {e}"); + for params in [json!({"item": 999, "loop": 2}), json!({"item": comp.0, "loop": 2}), json!({"items": [solid.0, 999], "loop": 2})] { + assert_eq!(s.execute("file.interpretFootage", params.clone()).unwrap(), json!({"items": []}), "{params}"); + } + for params in [json!({"item": 999, "loop": 2}), json!({"item": a.0, "loop": 2}), json!({"item": solid.0, "loop": 2})] { + let e = s.execute("file.interpretProxy", params.clone()).unwrap_err().to_string(); + assert!(e.contains("no proxy"), "{params}: {e}"); } assert_eq!(*s.project, *before); + let r = s.execute("file.interpretFootage", json!({"items": [solid.0, b.0], "loop": 2})).unwrap(); + assert_eq!(r["items"].as_array().map(|a| a.iter().map(|i| i["item"].clone()).collect::>()), Some(vec![json!(b.0)]), "{r}"); + let ItemKind::Footage(f) = &s.project.item(b).unwrap().kind else { panic!("not footage") }; + assert_eq!(f.loop_count, 2); } /// Use Proxy switches only the targets that have a proxy, and the first of those decides which diff --git a/crates/script/src/tests.rs b/crates/script/src/tests.rs index 52b338e31..60f0ad206 100644 --- a/crates/script/src/tests.rs +++ b/crates/script/src/tests.rs @@ -1197,6 +1197,20 @@ fn import_options_sequence_picks_one_still_or_the_run() { let _ = std::fs::remove_dir_all(&dir); } +/// A solid's mainSource has no frame rate to conform: setting conformFrameRate leaves the solid +/// as it was, without an error. +#[test] +fn conform_rate_of_a_solid_changes_nothing() { + let mut s = session(); + let o = ok( + &mut s, + r#"var c = app.project.items.addComp("C", 64, 36, 1, 1, 24); var l = c.layers.addSolid([1, 0, 0], "Red", 64, 36, 1); + var before = JSON.stringify(l.source.mainSource.__info()); l.source.mainSource.conformFrameRate = 12; + [String(l.source.mainSource), l.source.mainSource.conformFrameRate, JSON.stringify(l.source.mainSource.__info()) === before]"#, + ); + assert_eq!(o.result, json!(["[object SolidSource]", 0, true])); +} + /// #813: FootageItem proxies, replaceWithSequence and mainSource.conformFrameRate. #[test] fn footage_proxies_sequences_and_conform_rate() { diff --git a/crates/ui-egui/src/panels/forms.rs b/crates/ui-egui/src/panels/forms.rs index 5b350b6f7..0dd7064b7 100644 --- a/crates/ui-egui/src/panels/forms.rs +++ b/crates/ui-egui/src/panels/forms.rs @@ -1342,7 +1342,8 @@ mod tests { /// Interpret Footage named at an item it can't change (missing, not footage, or for Proxy /// without a proxy) doesn't open on the selected footage: as with nothing selected, the - /// command runs and reports that there is nothing to interpret, and nothing changes. + /// command runs with the parameters given, and nothing changes. Main skips what isn't + /// footage and succeeds; Proxy reports that nothing named has a proxy. #[test] fn interpret_footage_named_at_no_footage_opens_no_dialog() { for command in ["file.interpretFootage", "file.interpretProxy"] { @@ -1351,20 +1352,27 @@ mod tests { let ctx = egui::Context::default(); app.session.execute("comp.new", json!({"name": "Comp", "width": 4, "height": 4, "frameRate": 24, "duration": 1})).unwrap(); let comp = app.session.active_comp_id().unwrap(); + app.session.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap(); + let solid = app.session.project.items.values().find(|i| matches!(i.kind, effectcraft_engine::project::ItemKind::Solid(_))).unwrap().id; // Footage without a proxy. let kind = app.session.project.item(a).unwrap().kind.clone(); let plain = std::sync::Arc::make_mut(&mut app.session.project).add_item("plain.mov", Default::default(), None, kind); app.session.state.project_selection = vec![a]; - let mut invalid = vec![json!({"item": 999}), json!({"items": [999]}), json!({"item": comp.0})]; + let mut invalid = vec![json!({"item": 999}), json!({"items": [999]}), json!({"item": comp.0}), json!({"item": solid.0})]; if proxy { invalid.push(json!({"item": plain.0})); } let before = app.session.project.clone(); for params in invalid { - let e = crate::menus::invoke(&mut app, &ctx, command, params.clone()).unwrap_err(); + let r = crate::menus::invoke(&mut app, &ctx, command, params.clone()); assert!(app.dialog.is_none(), "{command}: {params}"); - assert!(e.contains(if proxy { "no proxy" } else { "select footage" }), "{command}: {params}: {e}"); - assert_eq!(app.ui.status, e, "the status line says why"); + if proxy { + let e = r.unwrap_err(); + assert!(e.contains("no proxy"), "{command}: {params}: {e}"); + assert_eq!(app.ui.status, e, "the status line says why"); + } else { + assert_eq!(r, Ok(json!({"items": []})), "{command}: {params}"); + } } assert_eq!(*app.session.project, *before); } From b06ba083ab75f8fed79d699f4f8845faef1afc08 Mon Sep 17 00:00:00 2001 From: Christopher Linnett Date: Wed, 18 Nov 2026 00:12:18 +0800 Subject: [PATCH 27/38] #2286: a failing test behind each Classic 3D depth-of-field bounding guard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Removing any of three guards from the depth-of-field bounding work failed no test: dof_blur's refusal of a padded buffer past the largest layer size, dof_radii_at's zeroing of a NaN radius, and the GPU bokeh's saturating padded sizes with the refusal they feed. - dof_blur_refuses_a_padded_buffer_longer_than_a_layer: a defocused strip as long as a layer may be, lying across the frame and standing up it, is drawn sharp and opaque; half as long, it blurs. - dof_radii_are_zero_where_the_radius_is_nan: a NaN depth (camera and plane at z = ∓1e308) and a NaN circle of confusion at a finite depth (Aperture 1e308 at Blur Level 0 %) give a zero radius, not the cap. - bokeh_refuses_a_padding_the_device_cannot_hold: paddings that would wrap the u32 size, or pass the device's largest texture in width (with the row-sum column) or height, are refused; a padding the device holds blurs. The four existing tests that built the same depth-of-field scene now share dof_scene and plane_dof_radii with the new ones. --- crates/gpu/src/tests/three_d.rs | 28 +++++++ crates/render/src/three_d/tests.rs | 116 ++++++++++++++++++++--------- 2 files changed, 109 insertions(+), 35 deletions(-) diff --git a/crates/gpu/src/tests/three_d.rs b/crates/gpu/src/tests/three_d.rs index acdbea7b1..4332f74c4 100644 --- a/crates/gpu/src/tests/three_d.rs +++ b/crates/gpu/src/tests/three_d.rs @@ -4,10 +4,13 @@ //! intersection line of two planes may sort differently (f32 vs f64 depths), so intersecting //! scenes allow 0.5 % of pixels over. +use std::sync::Arc; + use effectcraft_color::{BlendMode, Label}; use effectcraft_keyframe::{Keyframe, Value}; use effectcraft_project::build; use effectcraft_project::{BitDepth, Comp, ItemKind, Layer, LayerSource, LightKind, MatteKind, TrackMatte}; +use effectcraft_render::three_d::PlaneDof; use effectcraft_render::{Backend, RenderOpts, Renderer}; use effectcraft_time::{FrameRate, Tick}; @@ -281,6 +284,31 @@ fn bokeh_depth_of_field_runs_on_the_gpu() { } } +/// Bokeh pads a plane in `u32` sizes and refuses a padded plane the device can't hold. Each +/// radius map here is sized as wrapping arithmetic would pad its plane: its length matches a +/// padded size that wraps, or one that outgrows the device, so only the refusal stops them. A +/// padding of 2³¹ doubles to 2³², which would wrap the padded size around to the plane's own: only +/// the saturating size stops it. A plane padded to the device's largest texture width is refused +/// too, as its row sums need a column more, and so is one padded a row taller than that texture. A +/// padding the device holds is blurred. +#[test] +fn bokeh_refuses_a_padding_the_device_cannot_hold() { + let Some(g) = gpu() else { return }; + let mut e = crate::context::Enc::new(g.context()); + let mut blurred = |(w, h): (u32, u32), pad: u32| { + let grow = |n: u32| n.wrapping_add(pad.wrapping_mul(2)) as usize; + let radius = Arc::new(vec![1.0; grow(w) * grow(h)]); + let d = PlaneDof { pad, iris: Default::default(), highlight: Default::default(), radius, levels: vec![1.0] }; + let src = e.image(w, h); + crate::bokeh::apply(&mut e, &src, &d).is_some() + }; + let max = g.context().max_dim; + assert!(blurred((4, 4), 1), "a padding the device holds is blurred"); + assert!(!blurred((4, 4), 1 << 31), "a padding of 2³¹ is refused"); + assert!(!blurred((max - 2, 1), 1), "a padded width of {max} is refused: its row sums need {} columns", max + 1); + assert!(!blurred((1, max - 1), 1), "a padded height of {} is refused", max + 1); +} + /// A 2D layer whose track matte is a 3D layer: the matte is drawn through the camera on the /// GPU walk as on the CPU. #[test] diff --git a/crates/render/src/three_d/tests.rs b/crates/render/src/three_d/tests.rs index 026929623..699f7d79d 100644 --- a/crates/render/src/three_d/tests.rs +++ b/crates/render/src/three_d/tests.rs @@ -435,16 +435,36 @@ fn orientation_for_round_trips() { } } -#[test] -fn depth_of_field_blurs_out_of_focus_layers() { +/// A comp whose camera (layer 0) has depth of field, Aperture 60 and Focus Distance `focus`, over +/// a white `w`×`h` 3D solid (layer 1) centred in the frame at z = 0, scaled `scale` %. +fn dof_scene(focus: f64, (w, h): (u32, u32), scale: f64) -> (Project, ItemId) { let (mut p, cid, comp) = setup(); let mut cam = camera(&mut p, &comp); set(&mut cam, "cameraOptions/dof", Value::Bool(true)); set(&mut cam, "cameraOptions/aperture", Value::Scalar(60.0)); - let s = solid3(&mut p, &comp, [1.0, 1.0, 1.0], 60, 60, [100.0, 50.0, 0.0]); + set(&mut cam, "cameraOptions/focusDistance", Value::Scalar(focus)); + let mut s = solid3(&mut p, &comp, [1.0, 1.0, 1.0], w, h, [100.0, 50.0, 0.0]); + set(&mut s, "transform/scale", Value::Vec3([scale, scale, 100.0])); push(&mut p, cid, cam); push(&mut p, cid, s); + (p, cid) +} + +/// The blur radius map of a [`dof_scene`]'s `w`×`h` plane as its camera sees it, and the cap it +/// is held to. +fn plane_dof_radii(p: &Project, cid: ItemId, (w, h): (u32, u32)) -> (Vec, f64) { + let cp = p.comp(cid).unwrap(); + let ctx = crate::EvalCtx::new(p, cid, cp, Tick::ZERO); + let cs = super::camera::layer_camera(&ctx, &cp.layers[0]); + let dof = cs.dof.unwrap(); + let cap = super::compose::dof_radius_cap(&dof, w, h); + (super::compose::dof_radii_at(&cs, &dof, ctx.world_matrix(&cp.layers[1]), (w as usize, h as usize), [0.0; 2], 1.0, cap), cap) +} + +#[test] +fn depth_of_field_blurs_out_of_focus_layers() { // In focus (focus distance = zoom = distance to z=0): hard edge at x = 70. + let (mut p, cid) = dof_scene(zoom(), (60, 60), 100.0); let a = render(&p, cid); assert!(a.get(71, 50)[3] > 0.99 && a.get(69, 50)[3] < 0.01); let c = p.comp_mut(cid).unwrap(); @@ -460,14 +480,7 @@ fn depth_of_field_blurs_out_of_focus_layers() { #[test] fn dof_falls_back_when_focus_distance_is_not_finite() { for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { - let (mut p, cid, comp) = setup(); - let mut cam = camera(&mut p, &comp); - set(&mut cam, "cameraOptions/dof", Value::Bool(true)); - set(&mut cam, "cameraOptions/aperture", Value::Scalar(60.0)); - set(&mut cam, "cameraOptions/focusDistance", Value::Scalar(bad)); - let s = solid3(&mut p, &comp, [1.0, 1.0, 1.0], 60, 60, [100.0, 50.0, 0.0]); - push(&mut p, cid, cam); - push(&mut p, cid, s); + let (p, cid) = dof_scene(bad, (60, 60), 100.0); let cp = p.comp(cid).unwrap(); let ctx = crate::EvalCtx::new(&p, cid, cp, Tick::ZERO); let cs = crate::three_d::camera::layer_camera(&ctx, &cp.layers[0]); @@ -486,15 +499,7 @@ fn dof_falls_back_when_focus_distance_is_not_finite() { #[test] fn dof_blur_radius_is_bounded_for_degenerate_inputs() { let scene = |focus: f64, scale: f64| { - let (mut p, cid, comp) = setup(); - let mut cam = camera(&mut p, &comp); - set(&mut cam, "cameraOptions/dof", Value::Bool(true)); - set(&mut cam, "cameraOptions/aperture", Value::Scalar(60.0)); - set(&mut cam, "cameraOptions/focusDistance", Value::Scalar(focus)); - let mut s = solid3(&mut p, &comp, [1.0, 1.0, 1.0], 60, 60, [100.0, 50.0, 0.0]); - set(&mut s, "transform/scale", Value::Vec3([scale, scale, 100.0])); - push(&mut p, cid, cam); - push(&mut p, cid, s); + let (p, cid) = dof_scene(focus, (60, 60), scale); render(&p, cid) }; let finite = |img: &effectcraft_raster::Image| img.data.iter().all(|px| px.iter().all(|c| c.is_finite())); @@ -515,21 +520,8 @@ fn dof_blur_radius_is_bounded_for_degenerate_inputs() { #[test] fn dof_radii_skip_degenerate_planes_and_respect_the_cap() { let radii = |focus: f64, scale: f64| { - let (mut p, cid, comp) = setup(); - let mut cam = camera(&mut p, &comp); - set(&mut cam, "cameraOptions/dof", Value::Bool(true)); - set(&mut cam, "cameraOptions/aperture", Value::Scalar(60.0)); - set(&mut cam, "cameraOptions/focusDistance", Value::Scalar(focus)); - let mut s = solid3(&mut p, &comp, [1.0, 1.0, 1.0], 60, 60, [100.0, 50.0, 0.0]); - set(&mut s, "transform/scale", Value::Vec3([scale, scale, 100.0])); - push(&mut p, cid, cam); - push(&mut p, cid, s); - let cp = p.comp(cid).unwrap(); - let ctx = crate::EvalCtx::new(&p, cid, cp, Tick::ZERO); - let cs = super::camera::layer_camera(&ctx, &cp.layers[0]); - let dof = cs.dof.unwrap(); - let cap = super::compose::dof_radius_cap(&dof, 60, 60); - (super::compose::dof_radii_at(&cs, &dof, ctx.world_matrix(&cp.layers[1]), (60, 60), [0.0; 2], 1.0, cap), cap) + let (p, cid) = dof_scene(focus, (60, 60), scale); + plane_dof_radii(&p, cid, (60, 60)) }; let (r, _) = radii(zoom() + 10.0, 0.0); assert!(r.iter().all(|&r| r == 0.0), "a 0%-scaled plane is not blurred"); @@ -538,6 +530,60 @@ fn dof_radii_skip_degenerate_planes_and_respect_the_cap() { assert!(r.iter().all(|&r| r as f64 <= cap && r as f64 > cap - 1.0), "huge focus: every radius at the cap {cap}"); } +/// A NaN blur radius has no defocus, so the plane isn't blurred, where `min` would make NaN the +/// cap, the largest blur there is. Values from an expression or a script can produce one in two +/// ways: a plane and a camera at finite but opposite extreme depths (z = ±1e308), whose depth +/// overflows to infinity, so its slope across the buffer is ∞ − ∞ and every pixel's depth is NaN; +/// and Aperture 1e308 at Blur Level 0 %, whose circle of confusion overflows to infinity before +/// the blur level scales it to ∞ × 0, at a finite depth that a check on the depth alone would let +/// through. +#[test] +fn dof_radii_are_zero_where_the_radius_is_nan() { + let radii = |edit: &dyn Fn(&mut effectcraft_project::Layers)| { + let (mut p, cid) = dof_scene(zoom() + 10.0, (60, 60), 100.0); + edit(&mut p.comp_mut(cid).unwrap().layers); + plane_dof_radii(&p, cid, (60, 60)) + }; + let nan_depth = radii(&|l| { + set(&mut l[0], "transform/position", Value::Vec3([100.0, 50.0, -1.0e308])); + set(&mut l[1], "transform/position", Value::Vec3([100.0, 50.0, 1.0e308])); + }); + let nan_coc = radii(&|l| { + set(&mut l[0], "cameraOptions/aperture", Value::Scalar(1.0e308)); + set(&mut l[0], "cameraOptions/blurLevel", Value::Scalar(0.0)); + }); + for (case, (r, cap)) in [("NaN depth", nan_depth), ("∞ × 0 circle of confusion", nan_coc)] { + assert!(r.iter().all(|&r| r == 0.0), "{case}: not blurred (cap {cap}): {:?}", &r[..4]); + } +} + +/// A plane as long as a layer may be ([`effectcraft_project::limits::MAX_SIZE`]) can't be +/// padded for its blur: the padded copy is well within the area budget, but longer on a side +/// than a layer may be. It is drawn sharp instead, whichever side is the long one. Half as long, +/// the same defocused plane blurs. +#[test] +fn dof_blur_refuses_a_padded_buffer_longer_than_a_layer() { + // A 20 px strip `len` px long through the centre of the frame, lying across it or up it, with + // a ~15 px blur radius: its soft and opaque pixels on the frame's centre line at right angles + // to it. + let strip = |len: u32, across: bool| { + let (p, cid) = dof_scene(zoom() * 0.5, if across { (len, 20) } else { (20, len) }, 100.0); + let img = render(&p, cid); + let line: Vec<(i64, i64)> = if across { (0..H as i64).map(|y| (100, y)).collect() } else { (0..W as i64).map(|x| (x, 50)).collect() }; + (soft_count(&img, line.iter().copied()), line.iter().filter(|&&(x, y)| img.get(x, y)[3] > 0.99).count()) + }; + let max = effectcraft_project::limits::MAX_SIZE; + for across in [true, false] { + let (soft, _) = strip(max / 2, across); + assert!(soft > 10, "a {}-px-long plane out of focus blurs (across {across}): {soft} soft px", max / 2); + let (soft, opaque) = strip(max, across); + assert!( + soft == 0 && opaque == 20, + "a {max}-px-long plane is drawn sharp, not padded past the largest layer size (across {across}): {soft} soft px, {opaque} opaque" + ); + } +} + /// Two layers that look the same on screen (400×100 at 100%, 1600×400 at 25%) at the same depth /// blur by the same amount on screen: the radius bound must not depend on the layer's scale. #[test] From 28d859ba3b5186e4f722825e45ba55ddf7998899 Mon Sep 17 00:00:00 2001 From: Christopher Linnett Date: Wed, 18 Nov 2026 00:25:15 +0800 Subject: [PATCH 28/38] Viewer: a test draws the motion path of separated X/Y Position (#2285) --- crates/ui-egui/tests/it/ui_viewer.rs | 91 ++++++++++++++++++++++------ 1 file changed, 71 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/tests/it/ui_viewer.rs b/crates/ui-egui/tests/it/ui_viewer.rs index 6dee87535..703679f7b 100644 --- a/crates/ui-egui/tests/it/ui_viewer.rs +++ b/crates/ui-egui/tests/it/ui_viewer.rs @@ -1234,16 +1234,24 @@ fn pen_draws_on_a_layer_fitted_to_the_work_area_past_the_playhead() { assert!(sp.closed, "the click on the first vertex closes the path"); } -#[test] -fn motion_path_key_drag_edits_that_key() { +/// The harness with the Box layer selected and its Position keyed from (100, 100) at 0 s to `end` +/// at 2 s, so its motion path shows, and the playhead at `at` s. Snapping is off so a keyframe drag +/// ends where the pointer does, not on a nearby edge or centre. +fn box_with_motion_path(end: [f64; 2], at: f64) -> (Harness<'static, EffectcraftApp>, LayerId) { let mut h = harness(); let box_id: LayerId = h.state().session.active_comp().unwrap().layers[0].id; let s = &mut h.state_mut().session; s.execute("layer.select", json!({"layers": [box_id.0]})).unwrap(); s.execute("prop.addKey", json!({"layer": box_id.0, "path": "transform/position", "time": 0.0, "value": [100, 100, 0]})).unwrap(); - s.execute("prop.addKey", json!({"layer": box_id.0, "path": "transform/position", "time": 2.0, "value": [500, 100, 0]})).unwrap(); + s.execute("prop.addKey", json!({"layer": box_id.0, "path": "transform/position", "time": 2.0, "value": [end[0], end[1], 0.0]})).unwrap(); s.execute("view.snapping", json!({"value": false})).unwrap(); - s.set_time(effectcraft_engine::time::Tick::from_seconds_f64(1.0)); + s.set_time(effectcraft_engine::time::Tick::from_seconds_f64(at)); + (h, box_id) +} + +#[test] +fn motion_path_key_drag_edits_that_key() { + let (mut h, box_id) = box_with_motion_path([500.0, 100.0], 1.0); h.run_steps(3); assert!(h.state().auto.find(&format!("viewer.motionPath.{}.1", box_id.0)).is_some()); let from = screen(&h, [500.0, 100.0]); @@ -1385,14 +1393,7 @@ fn clicking_off_a_mask_deselects_its_points() { /// path into a curve (#290). #[test] fn a_straight_motion_path_has_handles_to_curve_it() { - let mut h = harness(); - let box_id: LayerId = h.state().session.active_comp().unwrap().layers[0].id; - let s = &mut h.state_mut().session; - s.execute("layer.select", json!({"layers": [box_id.0]})).unwrap(); - s.execute("prop.addKey", json!({"layer": box_id.0, "path": "transform/position", "time": 0.0, "value": [100, 100, 0]})).unwrap(); - s.execute("prop.addKey", json!({"layer": box_id.0, "path": "transform/position", "time": 2.0, "value": [400, 100, 0]})).unwrap(); - s.execute("view.snapping", json!({"value": false})).unwrap(); - s.set_time(effectcraft_engine::time::Tick::from_seconds_f64(1.0)); + let (mut h, box_id) = box_with_motion_path([400.0, 100.0], 1.0); h.run_steps(3); let (out0, in1) = (format!("viewer.motionPath.{}.0.out", box_id.0), format!("viewer.motionPath.{}.1.in", box_id.0)); assert!(h.state().auto.find(&in1).is_some(), "the second key has a handle"); @@ -3066,14 +3067,7 @@ fn roto_brush_ctrl_drag_resizes_the_brush() { /// Linear and Auto Bezier, Delete Vertex removes it; the pointer is the tool's pen. #[test] fn vertex_tools_edit_motion_path_keyframes() { - let mut h = harness(); - let box_id: LayerId = h.state().session.active_comp().unwrap().layers[0].id; - let s = &mut h.state_mut().session; - s.execute("layer.select", json!({"layers": [box_id.0]})).unwrap(); - s.execute("prop.addKey", json!({"layer": box_id.0, "path": "transform/position", "time": 0.0, "value": [100, 100, 0]})).unwrap(); - s.execute("prop.addKey", json!({"layer": box_id.0, "path": "transform/position", "time": 2.0, "value": [500, 100, 0]})).unwrap(); - s.execute("view.snapping", json!({"value": false})).unwrap(); - s.set_time(effectcraft_engine::time::Tick::from_seconds_f64(3.0)); + let (mut h, box_id) = box_with_motion_path([500.0, 100.0], 3.0); let keys = |h: &Harness<'_, EffectcraftApp>| { h.state().session.active_comp().unwrap().layer(box_id).unwrap().props.prop("transform/position").unwrap().keys.clone() }; @@ -3108,6 +3102,63 @@ fn vertex_tools_edit_motion_path_keyframes() { assert_eq!(keys(&h).len(), 3); } +/// With Separate Dimensions on, X and Y Position move the layer, while the combined Position keeps +/// the keys it had before separating, so the motion path has to follow X and Y. Each gets a key the +/// other lacks, and X's lies past the combined Position's last key: a square shows on the X/Y route +/// at every key time of either axis only when the path spans and samples both. A frame dot between +/// keys lies on that route too, and Add Vertex there keys both X and Y. A layer separated before it +/// is animated has a path too. +#[test] +fn separated_motion_path_follows_x_and_y_position() { + use effectcraft_engine::time::Tick; + // The playhead past the last key keeps the layer itself away from the dot Add Vertex clicks. + let (mut h, box_id) = box_with_motion_path([500.0, 100.0], 3.0); + let s = &mut h.state_mut().session; + s.execute("prop.separateDimensions", json!({"layer": box_id.0, "value": true})).unwrap(); + s.execute("prop.addKey", json!({"layer": box_id.0, "path": "transform/positionY", "time": 1.0, "value": 250})).unwrap(); + s.execute("prop.addKey", json!({"layer": box_id.0, "path": "transform/positionX", "time": 2.5, "value": 450})).unwrap(); + h.run_steps(3); + let comp = h.state().session.active_comp().unwrap().clone(); + let props = &comp.layer(box_id).unwrap().props; + let prop = |path: &str| props.prop(path).unwrap_or_else(|| panic!("no {path}")).clone(); + let (x, y, combined) = (prop("transform/positionX"), prop("transform/positionY"), prop("transform/position")); + let route = |t: Tick| [x.value_at(t).as_f64() as f32, y.value_at(t).as_f64() as f32]; + // Keys land on the nearest frame (2 s is 2.002 s at 29.97 fps): compare at the keys' own times. + let key_times = [0.0, 1.0, 2.0, 2.5].map(|s| comp.frame_rate.snap_nearest(Tick::from_seconds_f64(s))); + for (i, t) in key_times.into_iter().enumerate() { + let at = rect(&h, &format!("viewer.motionPath.{}.{i}", box_id.0)).center(); + assert!(at.distance(screen(&h, route(t))) < 1.0, "key square {i} at {at:?} is off the X/Y route at {}s", t.seconds()); + } + assert!(h.state().auto.find(&format!("viewer.motionPath.{}.4", box_id.0)).is_none(), "one square per X or Y key time"); + // The viewer puts a frame dot every comp frame from the first key; this one is 15 frames in. + // The combined Position runs straight along y 100 there, well away from the X/Y route. + let t = Tick(comp.frame_duration().0 * 15); + let on_route = route(t); + let stale = combined.value_at(t).as_vec3(); + assert!((stale[1] - f64::from(on_route[1])).abs() > 50.0, "the routes must differ here: {stale:?} vs {on_route:?}"); + h.state_mut().ui.tool = Tool::PenAdd; + h.run_steps(2); + let at = screen(&h, on_route); + click(&mut h, at); + let props = &h.state().session.active_comp().unwrap().layer(box_id).unwrap().props; + for path in ["transform/positionX", "transform/positionY"] { + let times: Vec = props.prop(path).unwrap().keys.iter().map(|k| k.time.seconds()).collect(); + assert!(times.iter().any(|s| (s - t.seconds()).abs() < 1e-6), "Add Vertex on the X/Y route keys {path} at {}s: {times:?}", t.seconds()); + } + assert_eq!(props.prop("transform/position").unwrap().keys.len(), 2, "the unused combined Position gets no key"); + // Separated before it is animated, the Plate's combined Position has no keys at all: whether it + // has a motion path has to depend on X and Y Position's keys alone. + let plate = layer_id(&h, "Plate"); + let s = &mut h.state_mut().session; + s.execute("layer.select", json!({"layers": [plate]})).unwrap(); + s.execute("prop.separateDimensions", json!({"layer": plate, "value": true})).unwrap(); + for (time, value) in [(0.0, 100), (2.0, 500)] { + s.execute("prop.addKey", json!({"layer": plate, "path": "transform/positionX", "time": time, "value": value})).unwrap(); + } + h.run_steps(3); + assert!(h.state().auto.find(&format!("viewer.motionPath.{plate}.1")).is_some(), "X Position's second key has its square"); +} + /// #882: at 100 % (and 200 %) on a scaled display the frame's corner sits on a physical pixel, so /// every comp pixel covers whole screen pixels instead of being blended with its neighbour. #[test] From 8e648b3e6fdc8a80eda71e8d01386117113a7a89 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:07:13 -0800 Subject: [PATCH 29/38] Import: one PhotoCraft input limit for the engine and media readers The 512 MiB limit is effectcraft_project::PCRAFT_MAX_INPUT. The engine re-exports it and the media reader's limit is defined from it, so the two reads cannot drift apart. Both reads compute their take() limit with saturating_add. --- crates/engine/src/services.rs | 4 ++-- crates/media/src/lib.rs | 2 +- crates/media/src/pcraft.rs | 2 +- crates/project/src/footage.rs | 4 ++++ crates/project/src/lib.rs | 4 +++- 5 files changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/services.rs b/crates/engine/src/services.rs index 4bc42baf0..2a641cf41 100644 --- a/crates/engine/src/services.rs +++ b/crates/engine/src/services.rs @@ -1,7 +1,7 @@ use super::config; /// The largest PhotoCraft bundle [`Services::read_pcraft`] reads. -pub const PCRAFT_MAX_INPUT: u64 = 512 << 20; +pub use effectcraft_project::PCRAFT_MAX_INPUT; /// The error for a PhotoCraft bundle over [`PCRAFT_MAX_INPUT`]. pub fn pcraft_too_large() -> std::io::Error { @@ -130,7 +130,7 @@ fn read_regular_file(path: &str, limit: Option) -> std::io::Result> let mut bytes = Vec::new(); // A sparse file can claim far more than memory: an error, not an abort. bytes.try_reserve_exact(usize::try_from(meta.len()).unwrap_or(usize::MAX)).map_err(|e| std::io::Error::new(std::io::ErrorKind::OutOfMemory, e))?; - file.take(limit.map_or(u64::MAX, |max| max + 1)).read_to_end(&mut bytes)?; + file.take(limit.map_or(u64::MAX, |max| max.saturating_add(1))).read_to_end(&mut bytes)?; if limit.is_some_and(|max| bytes.len() as u64 > max) { return Err(pcraft_too_large()); } diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index a6e9e0fb5..02ade4f9b 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -112,7 +112,7 @@ pub(crate) fn read_regular_file_stamped(path: &std::path::Path) -> std::io::Resu // A sparse file can claim far more than memory: an error, not an abort. bytes.try_reserve_exact(usize::try_from(meta.len()).unwrap_or(usize::MAX)).map_err(|e| std::io::Error::new(std::io::ErrorKind::OutOfMemory, e))?; if pcraft { - file.take(pcraft::MAX_INPUT_BYTES + 1).read_to_end(&mut bytes)?; + file.take(pcraft::MAX_INPUT_BYTES.saturating_add(1)).read_to_end(&mut bytes)?; if bytes.len() as u64 > pcraft::MAX_INPUT_BYTES { return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "PhotoCraft bundle grew beyond the 512 MiB input limit")); } diff --git a/crates/media/src/pcraft.rs b/crates/media/src/pcraft.rs index 220fcd381..ab8b0b74f 100644 --- a/crates/media/src/pcraft.rs +++ b/crates/media/src/pcraft.rs @@ -13,7 +13,7 @@ const MAX_PIXELS: u64 = 16 << 20; // (16 B), two blur images (32 B) and output (16 B), even where lifetimes do not // overlap. Twelve Mi pixels fit within a 1 GiB working-buffer budget (84 B/pixel). const MAX_LAYER_PIXELS: u64 = 12 << 20; -pub(crate) const MAX_INPUT_BYTES: u64 = 512 << 20; +pub(crate) const MAX_INPUT_BYTES: u64 = effectcraft_project::PCRAFT_MAX_INPUT; pub(crate) fn sniff(path: &str, bytes: &[u8]) -> bool { path.to_ascii_lowercase().ends_with(".pcraft") || craft_doc::sniff(bytes) == Some(craft_doc::Kind::PhotoCraft) diff --git a/crates/project/src/footage.rs b/crates/project/src/footage.rs index 462772dc4..107e5effc 100644 --- a/crates/project/src/footage.rs +++ b/crates/project/src/footage.rs @@ -49,6 +49,10 @@ impl FieldOrder { /// by this list. pub const VIDEO_EXTENSIONS: &[&str] = &["mp4", "m4v", "mov", "mkv", "webm", "mxf", "avi"]; +/// The largest PhotoCraft bundle that is read for import, in bytes. The engine's +/// `Services::read_pcraft` and `effectcraft_media`'s file reader both use it. +pub const PCRAFT_MAX_INPUT: u64 = 512 << 20; + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum AlphaMode { #[default] diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs index 9f5f399e0..fe8146b9b 100644 --- a/crates/project/src/lib.rs +++ b/crates/project/src/lib.rs @@ -40,7 +40,9 @@ mod reach; mod settings; pub use comp::{Comp, Guide, Renderer, Resolution}; -pub use footage::{AlphaMode, CineonSettings, CineonUnits, FieldOrder, Footage, FootageKind, Proxy, Solid, SourceLayer, VIDEO_EXTENSIONS, cineon_log_to_lin}; +pub use footage::{ + AlphaMode, CineonSettings, CineonUnits, FieldOrder, Footage, FootageKind, PCRAFT_MAX_INPUT, Proxy, Solid, SourceLayer, VIDEO_EXTENSIONS, cineon_log_to_lin, +}; pub use item::NO_LAYER; pub use item::{Heard, Item, ItemId, ItemKind, LayerId}; pub use layer::{ From b84130ad63a290897743af7165c27fa070a37268 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:25:04 -0800 Subject: [PATCH 30/38] Import: refuse pass-through groups deeper than the renderer collapses them A pass-through group becomes a precomposition with Collapse Transformations on, and the renderer collapses one only 12 comps deep. A deeper one was flattened, so its layers no longer blended with the layers below the group. Composition import now refuses pass-through groups more than 13 levels deep and suggests Footage, as it does for groups more than 16 levels deep. The renderer's limit is effectcraft_render::MAX_COLLAPSE_DEPTH. --- .../engine/src/interchange/pcraft_import.rs | 14 +++++++++-- crates/engine/src/tests/import_photocraft.rs | 23 +++++++++++++------ crates/render/src/lib.rs | 4 ++++ crates/render/src/pipeline.rs | 2 +- 4 files changed, 33 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/interchange/pcraft_import.rs b/crates/engine/src/interchange/pcraft_import.rs index ae3b4e4e0..0f86d2557 100644 --- a/crates/engine/src/interchange/pcraft_import.rs +++ b/crates/engine/src/interchange/pcraft_import.rs @@ -11,6 +11,12 @@ use effectcraft_time::{FrameRate, Tick}; // Each source group becomes a precomposition; match the renderer's nesting limit. const MAX_GROUP_DEPTH: usize = 16; +/// A group whose blend mode is Pass Through: it becomes a precomposition with Collapse +/// Transformations on, so its layers blend with the layers below the group. +fn passes_through(layer: &InputLayer) -> bool { + layer.kind == "group" && layer.blend.as_deref().is_some_and(|b| b.eq_ignore_ascii_case("PassThrough") || b.eq_ignore_ascii_case("Pass Through")) +} + pub(crate) struct Document { outline: Outline, width: u32, @@ -20,7 +26,7 @@ pub(crate) struct Document { /// Metadata only: source pixels remain media and are decoded when a frame needs them, as PSD /// footage is. Bound the number of project items before creating their property groups. pub(crate) fn read(bytes: &[u8]) -> Result { - if bytes.len() as u64 > 512 << 20 { + if bytes.len() as u64 > effectcraft_project::PCRAFT_MAX_INPUT { return Err("PhotoCraft bundle exceeds the 512 MiB input limit".into()); } fn count(layers: &[InputLayer], depth: usize, nodes: &mut usize, pixels: &mut usize) -> Result<(), String> { @@ -31,6 +37,10 @@ pub(crate) fn read(bytes: &[u8]) -> Result { if depth == MAX_GROUP_DEPTH && layer.kind == "group" { return Err("PhotoCraft groups exceed 16 levels; import as Footage for the saved composite".into()); } + // A pass-through group collapses into its parent only this deep in the renderer. + if depth > effectcraft_render::MAX_COLLAPSE_DEPTH && passes_through(layer) { + return Err("PhotoCraft pass-through groups exceed 13 levels; import as Footage for the saved composite".into()); + } *nodes += 1; if *nodes > 4096 { return Err("PhotoCraft composition import exceeds 4096 layers; import as Footage for the saved composite".into()); @@ -147,7 +157,7 @@ fn build_comp(project: &mut Project, ctx: &mut Context, name: &str, layers: &[In opacity.value = Value::Scalar(f64::from(input.opacity.filter(|v| v.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0)) * 100.0); } if let Some(blend) = input.blend.as_deref() { - if input.kind == "group" && (blend.eq_ignore_ascii_case("PassThrough") || blend.eq_ignore_ascii_case("Pass Through")) { + if passes_through(input) { layer.switches.collapse = true; } else if let Some(mode) = BlendMode::from_name(blend) { layer.blend_mode = mode; diff --git a/crates/engine/src/tests/import_photocraft.rs b/crates/engine/src/tests/import_photocraft.rs index 1a198d75c..b5926aa83 100644 --- a/crates/engine/src/tests/import_photocraft.rs +++ b/crates/engine/src/tests/import_photocraft.rs @@ -290,7 +290,16 @@ fn photocraft_layer_buffers_are_bounded_before_decoding_pixels() { #[test] fn photocraft_group_nesting_stays_within_the_composition_renderer_limit() { - for (depth, blend) in [(16, "Normal"), (16, "PassThrough"), (17, "Normal"), (17, "PassThrough")] { + // Pass-through groups collapse into their parents only 13 levels deep in the renderer, so a + // deeper one is refused instead of blending as a flattened group. + let cases = [ + (16, "Normal", None), + (13, "PassThrough", None), + (14, "PassThrough", Some("13 levels")), + (17, "Normal", Some("16 levels")), + (17, "PassThrough", Some("13 levels")), + ]; + for (depth, blend, refused) in cases { let mut layers = json!([layer("Deep pixels", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("0000ffff")}))]); for index in 0..depth { layers = json!([layer(&format!("Group {index}"), true, 1.0, blend, json!({"kind":"group","children":layers}))]); @@ -299,15 +308,15 @@ fn photocraft_group_nesting_stays_within_the_composition_renderer_limit() { let mut s = Session { footage: std::sync::Arc::new(effectcraft_media::MediaPool::new()), ..Default::default() }; let before = s.project.items.len(); let result = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); - if depth == 16 { - let comp = ItemId(result["comps"][0].as_u64().unwrap()); - assert_eq!(s.render(comp, effectcraft_time::Tick::ZERO, Default::default()).data[0], [0.0, 0.0, 1.0, 1.0]); - } else { + if let Some(levels) = refused { assert_eq!(s.project.items.len(), before, "unsupported nesting must not create a composition with disappearing artwork"); assert!( - result["errors"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains("16 levels") && e.contains("Footage"))), - "{result}" + result["errors"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains(levels) && e.contains("Footage"))), + "{depth} {blend}: {result}" ); + } else { + let comp = ItemId(result["comps"][0].as_u64().unwrap()); + assert_eq!(s.render(comp, effectcraft_time::Tick::ZERO, Default::default()).data[0], [0.0, 0.0, 1.0, 1.0], "{depth} {blend}"); } std::fs::remove_file(path).unwrap(); } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 1a3822f48..1b81a7e5c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -63,6 +63,10 @@ pub use opts::{LayerTiming, RenderOpts}; use opts::{MAX_THROUGH, Through}; pub use pipeline::{Collapsed, FootagePicture, MediaOverride, PropertyOverride}; +/// The deepest nested comp whose precomp layers still collapse their transformations: a layer +/// with Collapse Transformations in a comp nested deeper than this is rendered flattened. +pub const MAX_COLLAPSE_DEPTH: usize = 12; + pub struct Renderer<'a> { pub project: &'a Project, pub footage: &'a dyn FootageSource, diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 042dc198c..a57771363 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -357,7 +357,7 @@ impl<'a> Renderer<'a> { /// Properties overrides travel with it and are applied as the nested layers are evaluated, /// so the nested comp is not rasterised at its frame. pub fn collapsed(&self, ctx: &EvalCtx, layer: &Layer) -> Option { - if !layer.switches.collapse || layer.switches.adjustment || self.depth > 12 { + if !layer.switches.collapse || layer.switches.adjustment || self.depth > super::MAX_COLLAPSE_DEPTH { return None; } let LayerSource::Comp { item } = &layer.source else { return None }; From 8e1defea9365f081ad8e0482a907bb2feca599ad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 19:20:23 -0800 Subject: [PATCH 31/38] Import: test the PhotoCraft input limit without reading 512 MiB The two tests of the 512 MiB limit read a sparse file one byte over it into memory to show that other ZIP-based files are read whole. They now check the limit from the file's length alone and read a 4-byte file: the engine test reads it with and without a smaller limit, and the media reader's limit comes from input_limit, which gives the limit for .pcraft files only. --- crates/engine/src/services.rs | 15 ++++++++------ crates/media/src/lib.rs | 39 +++++++++++++++++++++++------------ 2 files changed, 35 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/services.rs b/crates/engine/src/services.rs index 2a641cf41..ebbe4c3d4 100644 --- a/crates/engine/src/services.rs +++ b/crates/engine/src/services.rs @@ -173,19 +173,22 @@ mod tests { } /// Templates and dotLottie files are ZIP archives too: only PhotoCraft reads have the - /// 512 MiB input limit. The length is set without writing the data. + /// 512 MiB input limit. A file over it is refused from its length, which is set without + /// writing the data, so nothing is read; the same read with a smaller limit, and with none, + /// shows where the limit applies. #[test] fn only_photocraft_reads_have_the_input_limit() { let f = std::env::temp_dir().join(format!("ec-services-large-{}.zip", std::process::id())); std::fs::write(&f, b"PK\x03\x04").unwrap(); std::fs::OpenOptions::new().write(true).open(&f).unwrap().set_len(super::PCRAFT_MAX_INPUT + 1).unwrap(); - let path = f.to_string_lossy(); + let path = f.to_string_lossy().to_string(); let error = FsServices.read_pcraft(&path).unwrap_err(); assert!(error.to_string().contains("512 MiB input limit"), "{error}"); - let bytes = FsServices.read_file(&path).unwrap(); - assert_eq!(bytes.len() as u64, super::PCRAFT_MAX_INPUT + 1); - assert!(bytes.starts_with(b"PK\x03\x04")); - drop(bytes); + std::fs::OpenOptions::new().write(true).open(&f).unwrap().set_len(4).unwrap(); + assert_eq!(FsServices.read_file(&path).unwrap(), b"PK\x03\x04"); + assert_eq!(FsServices.read_pcraft(&path).unwrap(), b"PK\x03\x04"); + assert!(super::read_regular_file(&path, Some(3)).is_err(), "one byte over a limit"); + assert_eq!(super::read_regular_file(&path, None).unwrap(), b"PK\x03\x04"); let _ = std::fs::remove_file(f); } diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index 02ade4f9b..7eff0e9cf 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -102,18 +102,17 @@ pub(crate) fn read_regular_file_stamped(path: &std::path::Path) -> std::io::Resu if !meta.is_file() { return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{} is not a file", path.display()))); } - // Only `.pcraft` files are limited before the read; other ZIP-based files are not. // A renamed bundle is checked after its read, before it is parsed. - let pcraft = ext_of(path) == "pcraft"; - if pcraft && meta.len() > pcraft::MAX_INPUT_BYTES { + let limit = input_limit(path); + if limit.is_some_and(|max| meta.len() > max) { return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "PhotoCraft bundle exceeds the 512 MiB input limit")); } let mut bytes = Vec::new(); // A sparse file can claim far more than memory: an error, not an abort. bytes.try_reserve_exact(usize::try_from(meta.len()).unwrap_or(usize::MAX)).map_err(|e| std::io::Error::new(std::io::ErrorKind::OutOfMemory, e))?; - if pcraft { - file.take(pcraft::MAX_INPUT_BYTES.saturating_add(1)).read_to_end(&mut bytes)?; - if bytes.len() as u64 > pcraft::MAX_INPUT_BYTES { + if let Some(max) = limit { + file.take(max.saturating_add(1)).read_to_end(&mut bytes)?; + if bytes.len() as u64 > max { return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "PhotoCraft bundle grew beyond the 512 MiB input limit")); } } else { @@ -122,6 +121,12 @@ pub(crate) fn read_regular_file_stamped(path: &std::path::Path) -> std::io::Resu Ok((bytes, effectcraft_render::reads::FileStamp::of_metadata(&meta))) } +/// The most bytes a read of `path` takes before it fails: `.pcraft` files have the PhotoCraft +/// input limit; other files, ZIP-based templates and dotLottie files included, have none. +fn input_limit(path: &std::path::Path) -> Option { + (ext_of(path) == "pcraft").then_some(pcraft::MAX_INPUT_BYTES) +} + #[cfg(test)] static OPENS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); @@ -175,16 +180,24 @@ mod read_tests { } /// Templates and dotLottie files are ZIP archives too: only `.pcraft` files have the - /// 512 MiB input limit. The length is set without writing the data. + /// 512 MiB input limit. A `.pcraft` file over it is refused from its length, which is set + /// without writing the data, so nothing is read. #[test] fn large_zip_files_other_than_photocraft_are_read_whole() { - let f = std::env::temp_dir().join(format!("ec-read-large-{}.zip", std::process::id())); + let max = crate::pcraft::MAX_INPUT_BYTES; + for name in ["a.zip", "a.lottie", "a.json", "a"] { + assert_eq!(super::input_limit(std::path::Path::new(name)), None, "{name}"); + } + for name in ["a.pcraft", "a.PCraft"] { + assert_eq!(super::input_limit(std::path::Path::new(name)), Some(max), "{name}"); + } + let f = std::env::temp_dir().join(format!("ec-read-large-{}.pcraft", std::process::id())); std::fs::write(&f, b"PK\x03\x04").unwrap(); - std::fs::OpenOptions::new().write(true).open(&f).unwrap().set_len(crate::pcraft::MAX_INPUT_BYTES + 1).unwrap(); - let bytes = super::read_regular_file(&f).unwrap(); - assert_eq!(bytes.len() as u64, crate::pcraft::MAX_INPUT_BYTES + 1); - assert!(bytes.starts_with(b"PK\x03\x04")); - drop(bytes); + std::fs::OpenOptions::new().write(true).open(&f).unwrap().set_len(max + 1).unwrap(); + let error = super::read_regular_file(&f).unwrap_err(); + assert!(error.to_string().contains("512 MiB input limit"), "{error}"); + std::fs::OpenOptions::new().write(true).open(&f).unwrap().set_len(4).unwrap(); + assert_eq!(super::read_regular_file(&f).unwrap(), b"PK\x03\x04"); let _ = std::fs::remove_file(f); } } From 5d27d1377cb2ad6ebcc6c8719f1ac9127b0983ef Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 18 Nov 2026 16:21:47 +0100 Subject: [PATCH 32/38] #3901: pasted Source Text keyframes keep their style Pasting a copied Source Text keyframe (keys.paste, Paste Reversed) or a copied unanimated Source Text value (Edit > Copy / Paste) went through the value's JSON form, which is the characters only, so the pasted key took the font, size and colours of the property's current value. A copied text value now pastes as the whole document; every other kind is pasted as before. --- crates/engine/src/cmd/anim.rs | 13 ++++- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/tests/timeline.rs | 81 +++++++++++++++++++++++++++++ 3 files changed, 94 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/anim.rs b/crates/engine/src/cmd/anim.rs index e23fc736f..c11aefeb4 100644 --- a/crates/engine/src/cmd/anim.rs +++ b/crates/engine/src/cmd/anim.rs @@ -56,6 +56,17 @@ fn compatible(a: &Property, b: &effectcraft_keyframe::Value) -> bool { a.value.kind_name() == b.kind_name() && a.value.components().len() == b.components().len() } +/// A copied value (keyframe or unanimated property) shaped for the property `target` it is pasted +/// into. A copied Source Text keeps its whole document, characters and style, as in After Effects +/// (#3901): its JSON form is the characters only, so going through it would take the font, size +/// and colours from the target's current value. Every other kind goes through the JSON form. +pub(super) fn pasted_value(target: &KValue, copied: &KValue) -> Option { + match (target, copied) { + (KValue::Text(_), KValue::Text(_)) => Some(copied.clone()), + _ => target.coerce_json(&copied.to_json()), + } +} + pub(crate) fn locked_selection(comp: &effectcraft_project::Comp, selected: &[KeyRef]) -> Vec { selected.iter().filter(|k| comp.layer(k.layer).is_some_and(|l| l.switches.locked)).copied().collect() } @@ -131,7 +142,7 @@ fn paste(s: &mut Session, p: &Value) -> Result { for (k, lt) in clip[*ci].keys.iter().zip(times) { let mut k = k.clone(); k.time = lt; - if let Some(v) = pr.value.coerce_json(&k.value.to_json()) { + if let Some(v) = pasted_value(&pr.value, &k.value) { k.value = v; } if pr.hold_only { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index c2ecb838d..8cba6a2ce 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -423,7 +423,7 @@ fn paste_properties(s: &mut Session, p: &Value) -> Result { for (path, v) in &values { let path = super::resolve_effect_path(l, path); if let Some(pr) = l.props.prop_mut(&path) - && let Some(v) = pr.value.coerce_json(&v.to_json()) + && let Some(v) = super::anim::pasted_value(&pr.value, v) { pr.set_value_at(lt, v); n += 1; diff --git a/crates/engine/src/tests/timeline.rs b/crates/engine/src/tests/timeline.rs index f0996f4af..89fc598b4 100644 --- a/crates/engine/src/tests/timeline.rs +++ b/crates/engine/src/tests/timeline.rs @@ -1664,3 +1664,84 @@ fn convert_expression_to_keyframes_refuses_a_zero_frame_duration() { assert!(e.contains("frame duration"), "{e}"); assert!(prop(&s, l, "transform/rotation").keys.is_empty()); } + +/// Source Text of text layer `t`, its static value set to `doc` (no keyframes touched). +fn set_static_text(s: &mut Session, t: u64, doc: &effectcraft_keyframe::TextDoc) { + let cid = s.active_comp_id().unwrap(); + let comp = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap(); + comp.layer_mut(effectcraft_project::LayerId(t)).unwrap().props.prop_mut("text/sourceText").unwrap().value = KV::Text(Box::new(doc.clone())); +} + +/// A text layer's current Source Text document, restyled: `text` in fill `fill`, size `size`. +fn styled_text(s: &Session, t: u64, text: &str, fill: [f32; 4], size: f64) -> effectcraft_keyframe::TextDoc { + let mut doc = prop(s, t, "text/sourceText").value.as_text().unwrap().clone(); + doc.text = text.into(); + doc.fill = fill; + doc.size = size; + doc +} + +/// #3901: a pasted Source Text keyframe is the copied one, characters and style, not the copied +/// characters in the property's current style. +#[test] +fn pasted_source_text_key_keeps_its_style() { + let (mut s, _) = setup(); + let t = s.execute("layer.newText", json!({"text": "Start", "size": 40})).unwrap()["layer"].as_u64().unwrap(); + let red = styled_text(&s, t, "Red", [1.0, 0.0, 0.0, 1.0], 72.0); + let blue = styled_text(&s, t, "Blue", [0.0, 0.0, 1.0, 1.0], 30.0); + animate(&mut s, t, "text/sourceText", &[(0.0, serde_json::to_value(&red).unwrap()), (1.0, serde_json::to_value(&blue).unwrap())]); + set_static_text(&mut s, t, &blue); + let copied = prop(&s, t, "text/sourceText").keys[0].value.clone(); + assert_eq!(copied.as_text().map(|d| d.fill), Some(red.fill), "key A is red"); + assert_ne!(prop(&s, t, "text/sourceText").value.as_text().map(|d| d.fill), Some(red.fill), "the property's own value is not red"); + let uid = prop(&s, t, "text/sourceText").uid; + s.execute("keys.select", json!({"keys": [{"layer": t, "prop": uid, "time": 0.0}]})).unwrap(); + assert_eq!(s.execute("keys.copy", json!({})).unwrap(), json!(1)); + assert_eq!(s.execute("keys.paste", json!({"layers": [t], "time": 2.0})).unwrap(), json!(1)); + let p = prop(&s, t, "text/sourceText"); + assert_eq!(p.keys.len(), 3); + let pasted = p.keys[2].value.as_text().unwrap(); + assert_eq!((pasted.text.as_str(), pasted.fill, pasted.size), ("Red", red.fill, 72.0), "text, fill and size travel with the key"); + assert_eq!(p.keys[2].value, copied, "the whole document travels with the key"); + // Edit ▸ Paste Reversed goes the same way. + s.execute("keys.select", json!({"keys": [{"layer": t, "prop": uid, "time": 0.0}]})).unwrap(); + s.execute("keys.copy", json!({})).unwrap(); + s.execute("time.set", json!({"time": 3.0})).unwrap(); + s.execute("edit.pasteReversedKeyframes", json!({"layers": [t]})).unwrap(); + let p = prop(&s, t, "text/sourceText"); + assert_eq!(p.keys.last().map(|k| &k.value), Some(&copied)); +} + +/// #3901: Edit ▸ Copy of an unanimated Source Text and Edit ▸ Paste onto another text layer +/// gives that layer the copied document, style included. +#[test] +fn pasted_source_text_value_keeps_its_style() { + let (mut s, _) = setup(); + let a = s.execute("layer.newText", json!({"text": "Red", "size": 40})).unwrap()["layer"].as_u64().unwrap(); + let b = s.execute("layer.newText", json!({"text": "Blue", "size": 40})).unwrap()["layer"].as_u64().unwrap(); + let red = styled_text(&s, a, "Red", [1.0, 0.0, 0.0, 1.0], 72.0); + let blue = styled_text(&s, b, "Blue", [0.0, 0.0, 1.0, 1.0], 30.0); + set_static_text(&mut s, a, &red); + set_static_text(&mut s, b, &blue); + s.execute("layer.select", json!({"layers": [a]})).unwrap(); + s.execute("prop.select", json!({"layer": a, "path": "text/sourceText", "selectKeys": false})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + assert_eq!(s.state.value_clipboard.len(), 1); + s.execute("layer.select", json!({"layers": [b]})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + assert_eq!(prop(&s, b, "text/sourceText").value, KV::Text(Box::new(red)), "layer B gets the copied text and style"); +} + +/// Typing plain characters into Source Text (control channel / scripts) still keeps the +/// property's style: the JSON form of a text value stays its characters (not changed by #3901). +#[test] +fn plain_string_source_text_keeps_the_current_style() { + let (mut s, _) = setup(); + let t = s.execute("layer.newText", json!({"text": "Start", "size": 40})).unwrap()["layer"].as_u64().unwrap(); + let blue = styled_text(&s, t, "Start", [0.0, 0.0, 1.0, 1.0], 30.0); + set_static_text(&mut s, t, &blue); + s.execute("prop.addKey", json!({"layer": t, "path": "text/sourceText", "time": 0.0, "value": "Hello"})).unwrap(); + let k = prop(&s, t, "text/sourceText").keys[0].value.as_text().unwrap().clone(); + assert_eq!((k.text.as_str(), k.fill, k.size), ("Hello", blue.fill, 30.0)); + assert_eq!(s.execute("prop.get", json!({"layer": t, "path": "text/sourceText"})).unwrap()["value"], json!("Hello")); +} From 6619dbe1d49b48d0278e6268f908ab9b3015240c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 18 Nov 2026 17:40:33 +0100 Subject: [PATCH 33/38] #3901: the Paste Reversed check counts the keys and checks the reversed key's time and value --- crates/engine/src/tests/timeline.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/timeline.rs b/crates/engine/src/tests/timeline.rs index 89fc598b4..281438771 100644 --- a/crates/engine/src/tests/timeline.rs +++ b/crates/engine/src/tests/timeline.rs @@ -1709,7 +1709,9 @@ fn pasted_source_text_key_keeps_its_style() { s.execute("time.set", json!({"time": 3.0})).unwrap(); s.execute("edit.pasteReversedKeyframes", json!({"layers": [t]})).unwrap(); let p = prop(&s, t, "text/sourceText"); - assert_eq!(p.keys.last().map(|k| &k.value), Some(&copied)); + assert_eq!(p.keys.len(), 4, "Paste Reversed adds one key"); + assert!((p.keys[3].time.seconds() - 3.0).abs() < 1e-6, "the reversed key is at 3 s: {}", p.keys[3].time.seconds()); + assert_eq!(p.keys[3].value, copied, "the reversed key keeps the whole document"); } /// #3901: Edit ▸ Copy of an unanimated Source Text and Edit ▸ Paste onto another text layer From e005d480108c56e6d4a3d3b4443bb2ba8051a5a8 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 18 Nov 2026 17:42:12 +0100 Subject: [PATCH 34/38] Export timing: count a write that fails, and the header and finish writes Each timed write now records its time before its error is passed on, so a failed export's log line keeps it (GIF frames and finish, VP9 clusters, WAV/AIFF, the movie's AAC flush and finish). Opening the file, the header and the segment patch with the final flush now count as writing for WebM (VP9 and AV1), the movies and GIF. New test: a_failed_write_keeps_its_time_in_the_log. --- crates/export/src/encode.rs | 25 +++++++----- crates/export/src/lib.rs | 22 +++++++---- crates/export/src/webm.rs | 51 +++++++++++++++---------- crates/export/src/webm_av1.rs | 19 +++++---- crates/export/tests/it/export_timing.rs | 50 ++++++++++++++++++++++++ 5 files changed, 120 insertions(+), 47 deletions(-) diff --git a/crates/export/src/encode.rs b/crates/export/src/encode.rs index e229d40b5..68f7849f0 100644 --- a/crates/export/src/encode.rs +++ b/crates/export/src/encode.rs @@ -393,10 +393,13 @@ pub(crate) async fn movie(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut St st.advance(first_end)?; let path = job.place(job.path, 1); - let mut file = job.create(&path)?; + let mut file = job.timed(Stage::Write, || job.create(&path))?; let opts = WriterOptions::new(brand); let movie_ts = opts.movie_timescale.max(1) as i128; - let mut mux: Writer = Mp4Writer::new(&mut file, opts).map_err(mux_err)?; + let t = Instant::now(); + let mux = Mp4Writer::new(&mut file, opts).map_err(mux_err); + job.add_time(Stage::Write, t); + let mut mux: Writer = mux?; let mut vcfg = TrackConfig::new(venc.sample_entry(), rate.num as u32); if let Some(start) = venc.media_start() { // An explicit edit: the convenience `media_start` edit would subtract the B-frame delay @@ -491,18 +494,20 @@ pub(crate) async fn movie(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut St let tail = job.timed(Stage::Encode, || venc.flush())?; job.timed(Stage::Write, || write_video(&mut mux, tail))?; job.timed_if(with_audio, Stage::Audio, || write_audio_until(&mut mux, span_end, &mut cursor))?; + // Each write is timed before its error is passed on: a failed export's line keeps the time. if let Some((Audio::Aac(e), at)) = audio.as_mut() { - let t = Instant::now(); - for au in e.flush() { - mux.write_sample(*at, WriteSample { data: &au, duration: 1024, composition_offset: 0, is_sync: true }).map_err(mux_err)?; - } - job.add_time(Stage::Audio, t); + job.timed(Stage::Audio, || -> Result<()> { + for au in e.flush() { + mux.write_sample(*at, WriteSample { data: &au, duration: 1024, composition_offset: 0, is_sync: true }).map_err(mux_err)?; + } + Ok(()) + })?; } let t = Instant::now(); - let out = mux.finish().map_err(mux_err)?; - out.flush().map_err(mux_err)?; - let bytes = file.finish()?; + let finished = mux.finish().map_err(mux_err).and_then(|out| out.flush().map_err(mux_err)); job.add_time(Stage::Write, t); + finished?; + let bytes = job.timed(Stage::Write, || file.finish())?; Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio, log: None, overflow: vec![], timing: Default::default() }) } diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs index 02bdbedc9..2e5327c21 100644 --- a/crates/export/src/lib.rs +++ b/crates/export/src/lib.rs @@ -455,8 +455,10 @@ async fn gif_export(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_ validate_gif_dimensions(w, h)?; let path = job.place(job.path, 1); - let mut file = job.create(&path)?; - let mut enc = AnimationWriter::new( + // Each write is timed before its error is passed on: a failed export's line keeps the time. + let mut file = job.timed(pipeline::Stage::EncodeWrite, || job.create(&path))?; + let t = Instant::now(); + let enc = AnimationWriter::new( &mut file, w, h, @@ -466,7 +468,9 @@ async fn gif_export(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_ speed: 10, }, ) - .map_err(|e| ExportError::Encode(e.to_string()))?; + .map_err(|e| ExportError::Encode(e.to_string())); + job.add_time(pipeline::Stage::EncodeWrite, t); + let mut enc = enc?; let rate = job.settings.rate(comp); // GIF delays are in 1/100 s: carry the rounding error so long animations keep their timing. let cs_per_frame = 100.0 * rate.den as f64 / rate.num as f64; @@ -480,22 +484,24 @@ async fn gif_export(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_ .frames(comp, (i..end).collect(), |_, img| craft_gif::write::prepare_frame(w, h, job.pixels_with(&img, comp, job.output.channels, w, h, false), 10)) .await; let t = Instant::now(); - for frame in frames { + let wrote = frames.into_iter().try_for_each(|frame| { clock += cs_per_frame; let d = (clock.round() as u64).saturating_sub(emitted).max(1); emitted += d; let frame = frame.map_err(|e| ExportError::Encode(e.to_string()))?; - enc.write_prepared_frame(frame, d.min(u16::MAX as u64) as u16).map_err(|e| ExportError::Encode(e.to_string()))?; - } + enc.write_prepared_frame(frame, d.min(u16::MAX as u64) as u16).map_err(|e| ExportError::Encode(e.to_string())) + }); // The GIF writer compresses as it writes: the two are not measured apart. job.add_time(pipeline::Stage::EncodeWrite, t); + wrote?; st.advance(end - i)?; i = end; } let t = Instant::now(); - let _ = enc.finish().map_err(|e| ExportError::Encode(e.to_string()))?; - let bytes = file.finish()?; + let finished = enc.finish().map(drop).map_err(|e| ExportError::Encode(e.to_string())); job.add_time(pipeline::Stage::EncodeWrite, t); + finished?; + let bytes = job.timed(pipeline::Stage::EncodeWrite, || file.finish())?; Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: false, log: None, overflow: vec![], timing: Default::default() }) } diff --git a/crates/export/src/webm.rs b/crates/export/src/webm.rs index 5db721bc7..b116ec198 100644 --- a/crates/export/src/webm.rs +++ b/crates/export/src/webm.rs @@ -170,7 +170,8 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta let duration_ms = frame_ms(total) as f64; let path = job.place(job.path, 1); - let mut file = job.create(&path)?; + // Each write is timed before its error is passed on: a failed export's line keeps the time. + let mut file = job.timed(Stage::Write, || job.create(&path))?; // EBML header. let mut head = vec![]; let mut eb = vec![]; @@ -229,7 +230,7 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta el(&mut tracks, TRACK_ENTRY, &a); } el(&mut head, TRACKS, &tracks); - file.write_all(&head).map_err(io)?; + job.timed(Stage::Write, || file.write_all(&head).map_err(io))?; let mut seg_len = head.len() as u64 - seg_start; // Audio: mixed in blocks, encoded in 20 ms packets. @@ -293,31 +294,37 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta job.add_time(Stage::Encode, t); let t_end = if end >= total { span_end } else { job.settings.frame_time(comp, end) }; job.timed_if(with_audio, Stage::Audio, || audio_until(t_end, &mut frames, end >= total))?; - let t = Instant::now(); - let c = cluster(&mut frames); - file.write_all(&c).map_err(io)?; - seg_len += c.len() as u64; - job.add_time(Stage::Write, t); + job.timed(Stage::Write, || -> Result<()> { + let c = cluster(&mut frames); + file.write_all(&c).map_err(io)?; + seg_len += c.len() as u64; + Ok(()) + })?; st.advance(end - i)?; i = end; } if total == 0 { let mut frames = vec![]; - audio_until(span_end, &mut frames, true)?; + job.timed_if(with_audio, Stage::Audio, || audio_until(span_end, &mut frames, true))?; if !frames.is_empty() { - let c = cluster(&mut frames); - file.write_all(&c).map_err(io)?; - seg_len += c.len() as u64; + job.timed(Stage::Write, || -> Result<()> { + let c = cluster(&mut frames); + file.write_all(&c).map_err(io)?; + seg_len += c.len() as u64; + Ok(()) + })?; } } // Patch the Segment size. let mut size = [0u8; 8]; size[0] = 0x01; size[1..].copy_from_slice(&seg_len.to_be_bytes()[1..]); - file.seek(SeekFrom::Start(size_pos)).map_err(io)?; - file.write_all(&size).map_err(io)?; - file.seek(SeekFrom::End(0)).map_err(io)?; - let bytes = file.finish()?; + let bytes = job.timed(Stage::Write, || -> Result { + file.seek(SeekFrom::Start(size_pos)).map_err(io)?; + file.write_all(&size).map_err(io)?; + file.seek(SeekFrom::End(0)).map_err(io)?; + file.finish() + })?; Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio, log: None, overflow: vec![], timing: Default::default() }) } @@ -434,12 +441,14 @@ pub(crate) fn audio_file(job: &Cx, comp: &Comp, aiff: bool, st: &mut State) -> R out.push(0); } } - let t = Instant::now(); - let path = job.place(job.path, out.len() as u64); - let mut file = job.create(&path)?; - file.write_all(&out).map_err(io)?; - let bytes = file.finish()?; - job.add_time(Stage::Write, t); + // Timed before the error is passed on: a failed export's line keeps the time. + let (path, bytes) = job.timed(Stage::Write, || -> Result<(String, u64)> { + let path = job.place(job.path, out.len() as u64); + let mut file = job.create(&path)?; + file.write_all(&out).map_err(io)?; + let bytes = file.finish()?; + Ok((path, bytes)) + })?; Ok(Report { path, frames: 0, width: 0, height: 0, seconds: 0.0, bytes, audio: true, log: None, overflow: vec![], timing: Default::default() }) } diff --git a/crates/export/src/webm_av1.rs b/crates/export/src/webm_av1.rs index a05115a8a..eb78af777 100644 --- a/crates/export/src/webm_av1.rs +++ b/crates/export/src/webm_av1.rs @@ -53,7 +53,8 @@ pub(crate) async fn webm_av1(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut let duration_ms = frame_ms(total) as f64; let path = job.place(job.path, 1); - let mut file = job.create(&path)?; + // Each write is timed before its error is passed on: a failed export's line keeps the time. + let mut file = job.timed(Stage::Write, || job.create(&path))?; let mut head = vec![]; let mut eb = vec![]; el_uint(&mut eb, 0x4286, 1); @@ -105,7 +106,7 @@ pub(crate) async fn webm_av1(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut el(&mut tracks, TRACK_ENTRY, &a); } el(&mut head, TRACKS, &tracks); - file.write_all(&head).map_err(io)?; + job.timed(Stage::Write, || file.write_all(&head).map_err(io))?; let mut seg_len = head.len() as u64 - seg_start; let (span_start, span_end) = job.settings.span(comp); @@ -167,15 +168,17 @@ pub(crate) async fn webm_av1(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut i = end; } if total == 0 { - audio_until(span_end, &mut blocks, true)?; - flush_blocks(&mut blocks, &mut file, &mut seg_len)?; + job.timed_if(with_audio, Stage::Audio, || audio_until(span_end, &mut blocks, true))?; + job.timed(Stage::Write, || flush_blocks(&mut blocks, &mut file, &mut seg_len))?; } let mut size = [0u8; 8]; size[0] = 0x01; size[1..].copy_from_slice(&seg_len.to_be_bytes()[1..]); - file.seek(SeekFrom::Start(size_pos)).map_err(io)?; - file.write_all(&size).map_err(io)?; - file.seek(SeekFrom::End(0)).map_err(io)?; - let bytes = file.finish()?; + let bytes = job.timed(Stage::Write, || -> Result { + file.seek(SeekFrom::Start(size_pos)).map_err(io)?; + file.write_all(&size).map_err(io)?; + file.seek(SeekFrom::End(0)).map_err(io)?; + file.finish() + })?; Ok(Report { path, frames: 0, width: w, height: h, seconds: 0.0, bytes, audio: with_audio, log: None, overflow: vec![], timing: Default::default() }) } diff --git a/crates/export/tests/it/export_timing.rs b/crates/export/tests/it/export_timing.rs index da93847b6..7315e18c1 100644 --- a/crates/export/tests/it/export_timing.rs +++ b/crates/export/tests/it/export_timing.rs @@ -134,6 +134,56 @@ fn a_failed_export_logs_its_timing_line_too() { assert!(log.contains("Timing: export failed after"), "{log}"); } +/// #3724 review: a write that fails still counts in the failed job's line. The output path is a +/// folder, so opening the output file fails; the log next to it names the writing stage. +#[test] +fn a_failed_write_keeps_its_time_in_the_log() { + use effectcraft_export::render_queue::WebmVideoCodec; + let (p, cid) = project(); + let settings = RenderSettings { time_span: TimeSpan::LengthOfComp, ..Default::default() }; + let dir = tempfile::tempdir().expect("temp dir"); + let vp9 = OutputModule::for_format(OutputFormat::WebM); + let av1 = OutputModule { webm_codec: WebmVideoCodec::Av1, ..OutputModule::for_format(OutputFormat::WebM) }; + let cases = [ + ("h264.mp4", OutputModule::for_format(OutputFormat::H264), "writing output"), + ("anim.gif", OutputModule::for_format(OutputFormat::Gif), "encoding and writing output measured together"), + ("vp9.webm", vp9, "writing output"), + ("av1.webm", av1, "writing output"), + ("wave.wav", OutputModule::for_format(OutputFormat::Wav), "writing output"), + ("aiff.aiff", OutputModule::for_format(OutputFormat::Aiff), "writing output"), + ]; + let mut misses = vec![]; + for (name, om, stage) in cases { + let out = dir.path().join(name); + std::fs::create_dir(&out).expect("a folder where the output should go"); + let path = out.to_string_lossy().into_owned(); + let job = Job { + project: &p, + footage: &NoFootage, + expr: None, + accel: None, + comp: cid, + settings: &settings, + output: &om, + path: &path, + sink: None, + options: Default::default(), + nested_switches: true, + }; + if export(&job, &mut |_| true).is_ok() { + misses.push(format!("{name}: the export did not fail")); + continue; + } + let stem = name.split('.').next().unwrap_or(name); + let log = std::fs::read_to_string(dir.path().join(format!("{stem}_RenderLog.txt"))).unwrap_or_default(); + let line = log.lines().find(|l| l.starts_with("Timing: export failed after")).unwrap_or_default(); + if !line.contains(stage) || line.contains("rendering, encoding and writing measured together") { + misses.push(format!("{name}: {stage:?} missing from {line:?}")); + } + } + assert!(misses.is_empty(), "{misses:#?}"); +} + #[test] fn a_stopped_export_has_a_summary_without_a_frame_count() { let t = effectcraft_export::render_queue::RenderTiming { From b83fced573bdc7615a61443e47eb53d176c219dc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 23:57:37 -0800 Subject: [PATCH 35/38] Import: keep the PhotoCraft note when a Photoshop file is picked with it When a selection holds a .pcraft file together with a .psd or .psb file, the Import Photoshop File dialog now shows the PhotoCraft compatibility note under its Import Kind choices. The note text moves into one helper that both Import dialogs use. --- crates/ui-egui/src/panels/forms.rs | 36 +++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/forms.rs b/crates/ui-egui/src/panels/forms.rs index fc0dc8f26..c50ac1fef 100644 --- a/crates/ui-egui/src/panels/forms.rs +++ b/crates/ui-egui/src/panels/forms.rs @@ -505,6 +505,11 @@ fn transform_form(p: &Value, layer: Option<&effectcraft_engine::project::Layer>, (title.into(), fields) } +/// The Import dialog's note on how a PhotoCraft file imports as a composition. +fn pcraft_note() -> Field { + Field::note("pcraftNote", "Composition uses canvas-sized saved pixels. Masks, effects and profiles may differ; use Footage for the saved appearance.") +} + /// If `id` is a dialog command invoked without its parameters, open its form and return true. pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool { let s = &app.session; @@ -517,13 +522,8 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool { "file.import" if !has(p, &["importAs"]) && imports_ext(p, &["pcraft"]) && !is_layered(p) => { let drag = p.get("drag").and_then(Value::as_bool).unwrap_or(false); let sel = usize::from(drag && s.prefs.drag_import_as() != "footage"); - let mut fields = vec![ - Field::choice("importAs", "Import Kind", &[("Footage", json!("footage")), ("Composition", json!("composition"))], sel), - Field::note( - "pcraftNote", - "Composition uses canvas-sized saved pixels. Masks, effects and profiles may differ; use Footage for the saved appearance.", - ), - ]; + let mut fields = + vec![Field::choice("importAs", "Import Kind", &[("Footage", json!("footage")), ("Composition", json!("composition"))], sel), pcraft_note()]; // A PDF or Illustrator file picked with it keeps its Page field. if is_pdf(p) && !has(p, &["page"]) { fields.push(Field::num("page", "Page", 1.0)); @@ -537,7 +537,10 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool { [("Footage", json!("footage")), ("Composition", json!("composition")), ("Composition - Retain Layer Sizes", json!("compositionLayerSizes"))]; let drag = p.get("drag").and_then(Value::as_bool).unwrap_or(false); let sel = if drag { kinds.iter().position(|(_, v)| v.as_str() == Some(s.prefs.drag_import_as())).unwrap_or(0) } else { 1 }; - ("Import Photoshop File".into(), vec![Field::choice("importAs", "Import Kind", &kinds, sel)]) + let mut fields = vec![Field::choice("importAs", "Import Kind", &kinds, sel)]; + // A PhotoCraft file picked with it keeps its compatibility note. + fields.extend(imports_ext(p, &["pcraft"]).then(pcraft_note)); + ("Import Photoshop File".into(), fields) } // PDF / Illustrator files: Import Kind and the page. "file.import" if !has(p, &["importAs", "page"]) && is_pdf(p) => ( @@ -1098,6 +1101,23 @@ mod tests { } } + #[test] + fn photocraft_import_with_a_photoshop_file_keeps_the_note() { + let has_note = |paths: Value| { + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + let reply = crate::menus::invoke(&mut app, &egui::Context::default(), "file.import", json!({"paths": paths, "drag": true})).unwrap(); + assert_eq!(reply["dialog"], "file.import"); + assert_eq!(app.dialog_state.form.title, "Import Photoshop File"); + let FieldKind::Choice { options, .. } = &app.dialog_state.form.fields[0].kind else { panic!("no import choices") }; + assert_eq!(options.len(), 3); + app.dialog_state.form.fields.iter().any(|f| f.key == "pcraftNote") + }; + for psd in ["/picked.psd", "/picked.psb"] { + assert!(has_note(json!(["/picked.pcraft", psd])), "{psd}"); + assert!(!has_note(json!([psd])), "{psd}"); + } + } + #[test] fn renderer_form_keeps_descriptive_labels_and_stable_option_values() { crate::i18n::set_current("en"); From 681b2c7468ecc5fea096280111d8c2974fdc4bd8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 00:29:17 -0800 Subject: [PATCH 36/38] Import: report PhotoCraft composition notes as warnings A PhotoCraft document that imports as a composition now returns its notes in the result's `warnings` instead of `errors`, so a successful import no longer reports a failure. With `background`, the notes are shown and returned when the job starts, since the composition stays in the project when the footage job is canceled. --- crates/engine/src/cmd/file.rs | 23 +++++++++++++++----- crates/engine/src/tests/import_photocraft.rs | 22 ++++++++++++++++++- 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 9feafe25f..f1f542135 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -144,6 +144,13 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result { }; let p = p.clone(); let immediate_errors = pending.errors.clone(); + // Compositions made during preparation stay when the job is canceled, so their notes are + // shown now and returned in both results. + let immediate_warnings = std::mem::take(&mut pending.warnings); + for w in &immediate_warnings { + s.events.push(crate::Event::Toast { message: w.clone(), error: true }); + } + let job_warnings = immediate_warnings.clone(); let mut result = s.spawn_task("import", label, false, move |ctl| { let mut probed = Vec::with_capacity(total); for (k, src) in sources.iter().enumerate() { @@ -157,6 +164,9 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result { let apply: crate::jobs::Apply = Box::new(move |s: &mut Session| { let made = pending.comps.len() + probed.iter().filter(|r| r.is_ok()).count(); let mut r = add_footage(s, pending, probed)?; + if let Some(w) = r.get_mut("warnings").and_then(Value::as_array_mut) { + w.splice(0..0, job_warnings.into_iter().map(Value::from)); + } finish_import(s, &mut r, target, &p); let mut toast = format!("Imported {made} item{}", if made == 1 { "" } else { "s" }); let errors: Vec<&str> = r["errors"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); @@ -174,6 +184,7 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result { // Report those failures now as well as in the eventual job result. if result["started"] == true { result["errors"] = json!(immediate_errors); + result["warnings"] = json!(immediate_warnings); } return Ok(result); } @@ -281,6 +292,8 @@ struct PendingImport { comps: Vec, items: Vec, errors: Vec, + /// Notes about compositions that imported, such as what a PhotoCraft composition leaves out. + warnings: Vec, /// EffectCraft projects merged in (`file.importProject` results); never added to a comp. projects: Vec, } @@ -427,6 +440,7 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result { let mut comps = vec![]; let mut items = vec![]; let mut errors = vec![]; + let mut warnings = vec![]; // EffectCraft projects import as projects, as After Effects imports an .aep; so do After // Effects projects, refused when parts of them cannot come over. The app asks about those // before it gets here (`panels::aep_losses`); a script or agent gets the refusal. @@ -460,10 +474,10 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result { let bytes = match read { Ok(b) if pcraft || craft_doc::sniff(&b) == Some(craft_doc::Kind::PhotoCraft) => { match import_pcraft_comp(s, &path, &b, retain) { - Ok((comp, made, warnings)) => { + Ok((comp, made, notes)) => { comps.push(comp); items.extend(made); - errors.extend(warnings); + warnings.extend(notes); } Err(e) => errors.push(format!("{path}: {e}")), } @@ -526,15 +540,14 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result { page, psd_layer: p.get("layer").cloned(), }; - Ok(PendingImport { sources, prober, comps, items, errors, projects }) + Ok(PendingImport { sources, prober, comps, items, errors, warnings, projects }) } /// The last part of an import: add the probed files to the project (one undo step) and select /// everything the import made, so the Project panel shows it. fn add_footage(s: &mut Session, pending: PendingImport, probed: Vec>) -> Result { - let PendingImport { comps, mut items, mut errors, projects, .. } = pending; + let PendingImport { comps, mut items, mut errors, mut warnings, projects, .. } = pending; let mut found = vec![]; - let mut warnings = vec![]; for r in probed { match r { Ok(f) => { diff --git a/crates/engine/src/tests/import_photocraft.rs b/crates/engine/src/tests/import_photocraft.rs index b5926aa83..4359b4b98 100644 --- a/crates/engine/src/tests/import_photocraft.rs +++ b/crates/engine/src/tests/import_photocraft.rs @@ -86,7 +86,11 @@ fn photocraft_composition_keeps_layer_names_visibility_opacity_and_blend() { let before = s.project.items.len(); let r = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); assert_eq!(r["comps"].as_array().unwrap().len(), 1, "{r}"); - assert!(r["errors"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains("Some masks, effects and profiles are unsupported"))), "{r}"); + assert!(r["errors"].as_array().unwrap().is_empty(), "{r}"); + assert!( + r["warnings"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains("Some masks, effects and profiles are unsupported"))), + "{r}" + ); let cid = ItemId(r["comps"][0].as_u64().unwrap()); let c = s.project.comp(cid).unwrap(); assert_eq!((c.width, c.height), (8, 6)); @@ -119,6 +123,22 @@ fn photocraft_composition_keeps_layer_names_visibility_opacity_and_blend() { std::fs::remove_file(path).unwrap(); } +#[test] +fn photocraft_composition_notes_arrive_before_a_background_footage_job() { + let layered = fixture("background-layered.pcraft", json!([layer("Bottom", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("ff0000ff")}))])); + let mut png = std::io::Cursor::new(Vec::new()); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(2, 2, image::Rgba([1, 2, 3, 255]))).write_to(&mut png, image::ImageFormat::Png).unwrap(); + let still = fixture_bytes("background-still.png", png.into_inner()); + let mut s = Session { importer: Some(std::sync::Arc::new(Import)), ..Default::default() }; + let r = s.execute("file.import", json!({"paths":[layered, still],"importAs":"composition","background":true})).unwrap(); + assert!(r["errors"].as_array().unwrap().is_empty(), "{r}"); + let notes = |r: &Value| r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains("Some masks, effects and profiles"))); + assert!(notes(&r), "the composition already exists, so a canceled job must not hide its notes: {r}"); + s.execute("jobs.wait", json!({})).unwrap(); + std::fs::remove_file(layered).unwrap(); + std::fs::remove_file(still).unwrap(); +} + #[test] fn photocraft_optional_canvas_metadata_does_not_block_probed_footage() { struct Metadata(bool); From 99c7e172b08f1c8f929763aeb50d6cce6e6bbdd9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 09:12:14 -0800 Subject: [PATCH 37/38] Import: show PhotoCraft composition notes as a notice, not an error The notes about a PhotoCraft composition that was already added now go to the window as one non-error notice. With several compositions the notice leads with the first note and a count of the rest, and the finished import's toast repeats the notes. Both command results keep the warnings as before. --- crates/engine/src/cmd/file.rs | 16 ++++++-- crates/engine/src/tests/import_photocraft.rs | 43 ++++++++++++++++++++ 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index f1f542135..72a2510a6 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -145,10 +145,17 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result { let p = p.clone(); let immediate_errors = pending.errors.clone(); // Compositions made during preparation stay when the job is canceled, so their notes are - // shown now and returned in both results. + // shown now and returned in both results. The window keeps one notice at a time and shows + // its first line, so they go in one notice led by a summary, and the finished job's toast + // repeats them. let immediate_warnings = std::mem::take(&mut pending.warnings); - for w in &immediate_warnings { - s.events.push(crate::Event::Toast { message: w.clone(), error: true }); + let notes = match immediate_warnings.as_slice() { + [] => String::new(), + [one] => one.clone(), + [first, rest @ ..] => format!("{first} (and {} more)\n{}", rest.len(), immediate_warnings.join("\n")), + }; + if !notes.is_empty() { + s.events.push(crate::Event::Toast { message: notes.clone(), error: false }); } let job_warnings = immediate_warnings.clone(); let mut result = s.spawn_task("import", label, false, move |ctl| { @@ -175,6 +182,9 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result { [one] => toast = format!("{toast}. {one}"), [first, rest @ ..] => toast = format!("{toast}. {first} (and {} more)\n{}", rest.len(), errors.join("\n")), } + if !notes.is_empty() { + toast = if errors.is_empty() { format!("{toast}. {notes}") } else { format!("{toast}\n{notes}") }; + } r["toast"] = json!(toast); Ok(r) }); diff --git a/crates/engine/src/tests/import_photocraft.rs b/crates/engine/src/tests/import_photocraft.rs index 4359b4b98..b135774c5 100644 --- a/crates/engine/src/tests/import_photocraft.rs +++ b/crates/engine/src/tests/import_photocraft.rs @@ -134,11 +134,54 @@ fn photocraft_composition_notes_arrive_before_a_background_footage_job() { assert!(r["errors"].as_array().unwrap().is_empty(), "{r}"); let notes = |r: &Value| r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains("Some masks, effects and profiles"))); assert!(notes(&r), "the composition already exists, so a canceled job must not hide its notes: {r}"); + let toast = s.drain_events().into_iter().find_map(|e| match e { + crate::Event::Toast { message, error } if message.contains("Some masks, effects and profiles") => Some(error), + _ => None, + }); + assert_eq!(toast, Some(false), "the composition was imported, so its notes are shown as a notice, not an error"); s.execute("jobs.wait", json!({})).unwrap(); + let done = s.drain_events().into_iter().find_map(|e| match e { + crate::Event::Toast { message, error } if message.starts_with("Imported") => Some((message, error)), + _ => None, + }); + let (done, error) = done.expect("the finished job shows its own toast"); + assert!(!error, "{done}"); + let shown = done.lines().next().unwrap_or_default(); + assert!( + shown.contains("Some masks, effects and profiles"), + "the job's toast replaces the notice in the window, so its first line repeats the notes: {done}" + ); std::fs::remove_file(layered).unwrap(); std::fs::remove_file(still).unwrap(); } +#[test] +fn photocraft_composition_notes_from_several_files_share_one_notice() { + let first = fixture("background-first.pcraft", json!([layer("Bottom", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("ff0000ff")}))])); + let second = fixture("background-second.pcraft", json!([layer("Bottom", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("00ff00ff")}))])); + let mut png = std::io::Cursor::new(Vec::new()); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(2, 2, image::Rgba([1, 2, 3, 255]))).write_to(&mut png, image::ImageFormat::Png).unwrap(); + let still = fixture_bytes("background-third.png", png.into_inner()); + let mut s = Session { importer: Some(std::sync::Arc::new(Import)), ..Default::default() }; + let r = s.execute("file.import", json!({"paths":[first, second, still],"importAs":"composition","background":true})).unwrap(); + assert_eq!(r["warnings"].as_array().unwrap().len(), 2, "{r}"); + let notices: Vec = s + .drain_events() + .into_iter() + .filter_map(|e| match e { + crate::Event::Toast { message, error: false } => Some(message), + _ => None, + }) + .collect(); + let [notice] = notices.as_slice() else { panic!("one notice for both compositions: {notices:?}") }; + assert!(notice.lines().next().unwrap_or_default().ends_with("(and 1 more)"), "the shown line says another note is on hover: {notice}"); + assert_eq!(notice.lines().count(), 3, "{notice}"); + s.execute("jobs.wait", json!({})).unwrap(); + for path in [first, second, still] { + std::fs::remove_file(path).unwrap(); + } +} + #[test] fn photocraft_optional_canvas_metadata_does_not_block_probed_footage() { struct Metadata(bool); From 6dbdefa987cfa7c0673963d6d0a45b23fa282582 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 16:36:19 +0100 Subject: [PATCH 38/38] Export timing: audio mux writes count as writing; a finish without timing clears the last one The movie's audio step now times mixing and encoding as audio and muxing the encoded AAC/PCM samples (and the AAC drain) as writing, as the timing contract says. A Finished update without timing clears the item's earlier timing. New test: an_audio_mux_write_counts_as_writing. --- crates/engine/src/background/offload/tests.rs | 3 + crates/engine/src/render_queue.rs | 12 +- crates/export/src/encode.rs | 134 ++++++++++++++---- 3 files changed, 115 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/background/offload/tests.rs b/crates/engine/src/background/offload/tests.rs index 495012ed8..f30d1d384 100644 --- a/crates/engine/src/background/offload/tests.rs +++ b/crates/engine/src/background/offload/tests.rs @@ -287,6 +287,8 @@ fn cancelling_offloaded_jobs() { assert!(s.revision > rev); // Render: the queued items become User Stopped. s.execute("renderQueue.add", serde_json::json!({"output": "/a.gif"})).unwrap(); + // An earlier run's timing does not stay beside the stopped status (#3724) + Arc::make_mut(&mut s.project).render_queue.last_mut().unwrap().last_timing = Some(Default::default()); let ids = s.start_render(false).unwrap(); assert!(s.is_rendering()); assert!(s.stop_render()); @@ -295,6 +297,7 @@ fn cancelling_offloaded_jobs() { assert_eq!(off.0.lock().unwrap().len(), 2); let it = s.project.render_queue.iter().find(|i| i.id == ids[0]).unwrap(); assert_eq!(it.status, RenderStatus::UserStopped); + assert_eq!(it.last_timing, None); } #[test] diff --git a/crates/engine/src/render_queue.rs b/crates/engine/src/render_queue.rs index b45932217..43c0b374b 100644 --- a/crates/engine/src/render_queue.rs +++ b/crates/engine/src/render_queue.rs @@ -213,9 +213,11 @@ impl JobShared { item.remove("last_timing"); } ItemUpdate::Finished { status, seconds, output, timing, .. } => { - if let Some(timing) = timing { - item.insert("last_timing".into(), json!(timing)); - } + // Each finish reports its own run: an item stopped before it started has no timing + match timing { + Some(timing) => item.insert("last_timing".into(), json!(timing)), + None => item.remove("last_timing"), + }; item.insert("status".into(), json!(status)); item.insert("statusLabel".into(), json!(status.label())); item.insert("render_time".into(), json!(seconds)); @@ -783,9 +785,7 @@ impl Session { if output.is_some() { i.last_output = output.clone(); } - if timing.is_some() { - i.last_timing = timing.clone(); - } + i.last_timing = timing.clone(); if let (RenderStatus::Done, Some(o)) = (status, output) && !i.post_render.is_none() { diff --git a/crates/export/src/encode.rs b/crates/export/src/encode.rs index 68f7849f0..1203c7ac6 100644 --- a/crates/export/src/encode.rs +++ b/crates/export/src/encode.rs @@ -297,6 +297,21 @@ enum Audio { Pcm, } +/// One encoded sample of a movie's audio track: its bytes and its duration in audio samples. +type AudioSample = (Vec, u32); + +/// One audio step of a movie: mixing and encoding count as audio, muxing the encoded samples as +/// writing, so a slow destination shows up as writing. Each part keeps its time on an error. +fn audio_step(job: &Cx, mux: &mut Mp4Writer, track: usize, encode: impl FnOnce() -> Result>) -> Result<()> { + let samples = job.timed(Stage::Audio, encode)?; + job.timed(Stage::Write, || -> Result<()> { + for (data, duration) in &samples { + mux.write_sample(track, WriteSample { data, duration: *duration, composition_offset: 0, is_sync: true }).map_err(mux_err)?; + } + Ok(()) + }) +} + fn deinterleave(buf: &[f32], channels: usize) -> Vec> { (0..channels).map(|c| buf.chunks_exact(channels).map(|p| p[c]).collect()).collect() } @@ -443,35 +458,31 @@ pub(crate) async fn movie(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut St } Ok(()) }; - let mut write_audio_until = |mux: &mut Writer, until: Tick, cursor: &mut i64| -> Result<()> { + let mut audio_until = |mux: &mut Writer, until: Tick, cursor: &mut i64| -> Result<()> { let Some((a, at)) = audio.as_mut() else { return Ok(()) }; let end = until.to_units_floor(sr as i64); if end <= *cursor { return Ok(()); } - let n = (end - *cursor) as usize; - let start = Tick::from_units(*cursor, i64::from(sr)); - let start = if start.to_units_floor(i64::from(sr)) < *cursor { Tick(start.0.saturating_add(1)) } else { start }; - let buf = mix(job, start, n, sr); - *cursor = end; - match a { - Audio::Aac(e) => { - let planar = deinterleave(&buf, chans as usize); - let refs: Vec<&[f32]> = planar.iter().map(Vec::as_slice).collect(); - for au in e.encode(&refs) { - mux.write_sample(*at, WriteSample { data: &au, duration: 1024, composition_offset: 0, is_sync: true }).map_err(mux_err)?; + audio_step(job, mux, *at, || { + let n = (end - *cursor) as usize; + let start = Tick::from_units(*cursor, i64::from(sr)); + let start = if start.to_units_floor(i64::from(sr)) < *cursor { Tick(start.0.saturating_add(1)) } else { start }; + let buf = mix(job, start, n, sr); + *cursor = end; + Ok(match a { + Audio::Aac(e) => { + let planar = deinterleave(&buf, chans as usize); + let refs: Vec<&[f32]> = planar.iter().map(Vec::as_slice).collect(); + e.encode(&refs).into_iter().map(|au| (au, 1024)).collect() } - } - Audio::Pcm => { - let pcm = pcm_bytes(&buf, afmt, false); - mux.write_sample(*at, WriteSample { data: &pcm, duration: n as u32, composition_offset: 0, is_sync: true }).map_err(mux_err)?; - } - } - Ok(()) + Audio::Pcm => vec![(pcm_bytes(&buf, afmt, false), n as u32)], + }) + }) }; let frame_end_time = |k: u64| -> Tick { if k >= total { span_end } else { job.settings.frame_time(comp, k) } }; job.timed(Stage::Write, || write_video(&mut mux, pending))?; - job.timed_if(with_audio, Stage::Audio, || write_audio_until(&mut mux, frame_end_time(first_end), &mut cursor))?; + audio_until(&mut mux, frame_end_time(first_end), &mut cursor)?; let mut i = first_end; while i < total { let end = (i + batch).min(total); @@ -483,7 +494,7 @@ pub(crate) async fn movie(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut St let ps = job.timed(Stage::Encode, || encode(&mut venc, px, i + k as u64))?; job.timed(Stage::Write, || write_video(&mut mux, ps))?; } - job.timed_if(with_audio, Stage::Audio, || write_audio_until(&mut mux, frame_end_time(end), &mut cursor)) + audio_until(&mut mux, frame_end_time(end), &mut cursor) }) .await?; done?; @@ -493,15 +504,10 @@ pub(crate) async fn movie(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut St } let tail = job.timed(Stage::Encode, || venc.flush())?; job.timed(Stage::Write, || write_video(&mut mux, tail))?; - job.timed_if(with_audio, Stage::Audio, || write_audio_until(&mut mux, span_end, &mut cursor))?; + audio_until(&mut mux, span_end, &mut cursor)?; // Each write is timed before its error is passed on: a failed export's line keeps the time. if let Some((Audio::Aac(e), at)) = audio.as_mut() { - job.timed(Stage::Audio, || -> Result<()> { - for au in e.flush() { - mux.write_sample(*at, WriteSample { data: &au, duration: 1024, composition_offset: 0, is_sync: true }).map_err(mux_err)?; - } - Ok(()) - })?; + audio_step(job, &mut mux, *at, || Ok(e.flush().into_iter().map(|au| (au, 1024)).collect()))?; } let t = Instant::now(); let finished = mux.finish().map_err(mux_err).and_then(|out| out.flush().map_err(mux_err)); @@ -596,4 +602,76 @@ mod tests { assert_eq!(cb[0], 512); assert!(cr[2] > 900, "red has high Cr: {}", cr[2]); } + + /// A destination that takes the movie's header, then is slow on every write once `slow` is + /// set, and refuses the write after the delay when `fails` is set too. + struct SlowDestination { + data: std::io::Cursor>, + slow: std::rc::Rc>, + fails: bool, + delay: std::time::Duration, + } + + impl Write for SlowDestination { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if self.slow.get() { + std::thread::sleep(self.delay); + if self.fails { + return Err(std::io::Error::other("destination refused the write")); + } + } + self.data.write(buf) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + impl std::io::Seek for SlowDestination { + fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result { + self.data.seek(pos) + } + } + + /// #3724 review: muxing an audio sample counts as writing, not as audio (mixing and + /// encoding), also when the destination refuses it. + #[test] + fn an_audio_mux_write_counts_as_writing() { + use effectcraft_project::render_queue::{OutputModule, RenderSettings}; + let (project, settings, output) = (effectcraft_project::Project::default(), RenderSettings::default(), OutputModule::for_format(OutputFormat::ProRes)); + let job = crate::Job { + project: &project, + footage: &effectcraft_render::NoFootage, + expr: None, + accel: None, + comp: effectcraft_project::ItemId(0), + settings: &settings, + output: &output, + path: "/a/movie.mov", + sink: None, + nested_switches: true, + options: Default::default(), + }; + let delay = std::time::Duration::from_millis(50); + let pcm = PcmConfig { bits: 16, float: false, big_endian: false, signed: true, channels: 2, sample_rate: 48_000.0 }; + + for fails in [false, true] { + let cx = Cx::new(&job); + let slow = std::rc::Rc::new(std::cell::Cell::new(false)); + let destination = SlowDestination { data: Default::default(), slow: slow.clone(), fails, delay }; + let mut mux = Mp4Writer::new(destination, WriterOptions::new(Brand::Mov)).expect("movie header"); + let track = mux.add_track(TrackConfig::new(SampleEntry::pcm(pcm), 48_000)).expect("audio track"); + slow.set(true); + let started = Instant::now(); + let result = audio_step(&cx, &mut mux, track, || Ok(vec![(vec![0; 4], 1)])); + let wall = started.elapsed().as_secs_f64(); + + assert_eq!(result.is_err(), fails, "the refused write is passed on"); + let timing = cx.timing(wall, 0); + let write = timing.write_seconds.expect("the attempted mux write is timed as writing"); + let audio = timing.audio_seconds.expect("mixing and encoding are timed as audio"); + assert!(write >= delay.as_secs_f64(), "fails {fails}: the slow write is in writing: {timing:?}"); + assert!(audio + write <= wall, "fails {fails}: the write counts once, not in audio too: {timing:?}"); + } + } }