Skip to content

EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust

Merge main into #2410

Minher0db1f79845505
diff --cc crates/engine/src/tests.rs
index b3f0602b3,579d3d30d..38ff943e7
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@@ -1,735 -1,53 +1,54 @@@
- use serde_json::json;
-
- use crate::Session;
-
- fn demo() -> Session {
- let mut s = Session::default();
- s.execute("file.openDemoProject", json!({})).unwrap();
- s
- }
-
- #[test]
- fn demo_opens_and_renders() {
- let s = demo();
- let cid = s.active_comp_id().unwrap();
- let img = s.render(cid, s.time(), effectcraft_render::RenderOpts { scale: 0.25, ..Default::default() });
- assert_eq!((img.width, img.height), (480, 270));
- let lit = img.data.iter().filter(|p| p[3] > 0.99).count();
- assert!(lit > 100_000, "{lit}");
- }
-
- /// The session's layer cache never changes pixels: scrubbing the demo (including back and
- /// forth, and across an edit made through a command) matches cache-less renders exactly.
- #[test]
- fn demo_layer_cache_is_transparent() {
- let mut s = demo();
- let cid = s.active_comp_id().unwrap();
- let opts = effectcraft_render::RenderOpts { scale: 0.25, ..Default::default() };
- let uncached = |s: &Session, t: f64| {
- let mut r = effectcraft_render::Renderer::new(&s.project, s.footage.as_ref(), opts);
- r.expr = s.expr.as_deref();
- r.comp_frame(cid, effectcraft_time::Tick::from_seconds_f64(t))
- };
- let check = |s: &Session, t: f64| {
- let a = s.render(cid, effectcraft_time::Tick::from_seconds_f64(t), opts);
- let b = uncached(s, t);
- assert!(a.data.iter().zip(&b.data).all(|(p, q)| (0..4).all(|c| (p[c] - q[c]).abs() < 1e-6)), "t={t}");
- };
- for t in [0.5, 1.0, 3.0, 3.0334, 6.0, 3.0, 0.5] {
- check(&s, t);
- }
- assert!(s.layer_cache.stats().hits > 0);
- // Edit the title's glow through the command layer, then scrub again.
- let title = s.project.comp(cid).unwrap().layers.iter().find(|l| l.name == "EFFECTCRAFT").map(|l| l.id.0).unwrap();
- s.execute("prop.set", json!({"layer": title, "path": "effects/#1/radius", "value": 5.0})).unwrap();
- for t in [3.0, 0.5] {
- check(&s, t);
- }
- }
-
- /// `layer.addItem` puts the layer at `index` (1-based) in the stack and starts it at `time`, as a
- /// drop in the Timeline does (#89).
- #[test]
- fn add_item_at_a_stack_index_and_time() {
- let mut s = Session::default();
- let clip = s.execute("comp.new", json!({"name": "Clip", "width": 16, "height": 16, "frameRate": 30, "duration": 1})).unwrap()["comp"].as_u64().unwrap();
- s.execute("comp.new", json!({"name": "Main", "width": 32, "height": 32, "frameRate": 30, "duration": 4})).unwrap();
- for name in ["C", "B", "A"] {
- s.execute("layer.newSolid", json!({"name": name})).unwrap();
- }
- let names = |s: &Session| s.active_comp().unwrap().layers.iter().map(|l| l.name.clone()).collect::<Vec<_>>();
- s.execute("layer.addItem", json!({"item": clip, "index": 2, "time": 1.01})).unwrap();
- assert_eq!(names(&s), ["A", "Clip", "B", "C"]);
- let l = &s.active_comp().unwrap().layers[1];
- assert_eq!(l.in_point, effectcraft_time::Tick::from_seconds_f64(1.0), "on the nearest frame");
- // Past the bottom: the bottom.
- s.execute("layer.addItem", json!({"item": clip, "index": 99})).unwrap();
- assert_eq!(names(&s).last().map(String::as_str), Some("Clip 2"));
- assert!(s.execute("layer.addItem", json!({"item": clip, "index": 0})).is_err(), "1-based");
- }
-
- /// Files dropped on the Timeline or the Composition viewer (`file.import {addToComp}`) become
- /// layers of the comp that was active, one under the other, where they were dropped (#85, #89).
- #[test]
- fn imported_files_go_into_the_comp_where_they_were_dropped() {
- use effectcraft_project::{Footage, FootageKind};
- struct Probe;
- impl crate::Importer for Probe {
- fn probe(&self, path: &str) -> Result<Footage, String> {
- Ok(Footage { path: path.into(), kind: FootageKind::Still, width: 64, height: 32, has_video: true, ..Default::default() })
- }
- }
- let mut s = Session { importer: Some(std::sync::Arc::new(Probe)), ..Default::default() };
- s.execute("comp.new", json!({"name": "Main", "width": 320, "height": 180, "frameRate": 30, "duration": 4})).unwrap();
- s.execute("layer.newSolid", json!({"name": "Bg"})).unwrap();
- let params = json!({"paths": ["/drop/a.png", "/drop/b.png"], "addToComp": true, "position": [40.0, 50.0], "index": 1, "time": 1.0});
- s.execute("file.import", params).unwrap();
- let comp = s.active_comp().unwrap();
- assert_eq!(comp.layers.iter().map(|l| l.name.as_str()).collect::<Vec<_>>(), ["a.png", "b.png", "Bg"]);
- for l in &comp.layers[..2] {
- assert_eq!(l.props.prop("transform/position").map(|p| p.value.clone()), Some(effectcraft_keyframe::Value::Vec3([40.0, 50.0, 0.0])));
- assert_eq!(l.in_point, effectcraft_time::Tick::from_seconds_f64(1.0));
- }
- // Without `addToComp` they only import.
- s.execute("file.import", json!({"paths": ["/drop/c.png"]})).unwrap();
- assert_eq!(s.active_comp().unwrap().layers.len(), 3);
- assert!(s.execute("layer.addItem", json!({"item": "a.png", "position": [1.0]})).is_err(), "position needs x and y");
- }
-
- /// #270: files dropped or picked in the Import dialog (`file.import {background}`) are probed in
- /// a background job that says which file it is reading and how many are left; then they arrive
- /// in one undo step, all selected, with a count. The same file imported again arrives again.
- #[test]
- fn background_imports_report_progress_and_select_what_arrived() {
- use effectcraft_project::{Footage, FootageKind, ItemId};
- use std::sync::Arc;
- use std::sync::atomic::{AtomicUsize, Ordering};
- /// Probes file k once `allow` > k (a slow video; 5 s at most, so an import that waits for it
- /// fails the test instead of hanging it); `.xyz` files fail.
- struct Gated {
- started: AtomicUsize,
- allow: Arc<AtomicUsize>,
- }
- impl crate::Importer for Gated {
- fn probe(&self, path: &str) -> Result<Footage, String> {
- let k = self.started.fetch_add(1, Ordering::SeqCst);
- let until = std::time::Instant::now() + std::time::Duration::from_secs(5);
- while self.allow.load(Ordering::SeqCst) <= k && std::time::Instant::now() < until {
- std::thread::sleep(std::time::Duration::from_millis(1));
- }
- if path.ends_with(".xyz") {
- return Err("unsupported file".into());
- }
- Ok(Footage { path: path.into(), kind: FootageKind::Still, width: 64, height: 32, has_video: true, ..Default::default() })
- }
- }
- let allow = Arc::new(AtomicUsize::new(1));
- let mut s = Session { importer: Some(Arc::new(Gated { started: AtomicUsize::new(0), allow: allow.clone() })), ..Default::default() };
- s.execute("comp.new", json!({"name": "Main", "width": 320, "height": 180, "frameRate": 30, "duration": 4})).unwrap();
- let undo = s.history.undo.len();
- let r = s.execute("file.import", json!({"paths": ["/drop/a.png", "/drop/b.png", "/drop/a.png"], "background": true})).unwrap();
- let job = r["job"].as_str().unwrap().to_string();
- // The first file is through; the second is being read.
- let running = |s: &mut Session| s.execute("jobs.list", json!({})).unwrap()["running"].as_array().unwrap().clone();
- let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
- while running(&mut s)[0]["done"] != json!(1) && std::time::Instant::now() < deadline {
- std::thread::sleep(std::time::Duration::from_millis(2));
- }
- let row = running(&mut s)[0].clone();
- assert_eq!(row["id"], json!(job));
- assert_eq!(row["label"], json!("Importing 3 files"));
- assert_eq!(row["message"], json!("b.png (2 of 3)"));
- assert_eq!((row["done"].as_u64(), row["total"].as_u64()), (Some(1), Some(3)));
- assert!(s.project.items.values().all(|i| i.name != "a.png"), "nothing is added before the import finishes");
- allow.store(usize::MAX, Ordering::SeqCst);
- s.execute("jobs.wait", json!({})).unwrap();
- let names = |s: &Session, ids: &[ItemId]| ids.iter().map(|i| s.project.item(*i).unwrap().name.clone()).collect::<Vec<_>>();
- assert_eq!(names(&s, &s.state.project_selection), ["a.png", "b.png", "a.png"], "everything imported is selected, the same file twice too");
- assert_eq!(s.history.undo.len(), undo + 1, "one undo step");
- let rec = s.job_log.last().unwrap();
- assert_eq!((rec.status.as_str(), rec.message.as_str()), ("done", "Imported 3 items"));
- assert!(s.drain_events().iter().any(|e| matches!(e, crate::Event::Toast { message, .. } if message == "Imported 3 items")));
- // Dropped on the viewer: they become layers too; a file that can't be read is reported.
- s.execute("file.import", json!({"paths": ["/drop/c.png", "/drop/d.xyz"], "background": true, "addToComp": true, "position": [10.0, 20.0]})).unwrap();
- s.execute("jobs.wait", json!({})).unwrap();
- assert_eq!(s.active_comp().unwrap().layers.iter().map(|l| l.name.as_str()).collect::<Vec<_>>(), ["c.png"]);
- assert_eq!(s.job_log.last().unwrap().message, "Imported 1 item. /drop/d.xyz: unsupported file");
- // Agents and scripts import at once by default.
- let r = s.execute("file.import", json!({"paths": ["/drop/e.png"]})).unwrap();
- assert_eq!(r["items"].as_array().map(Vec::len), Some(1));
- }
-
- /// Audio, Lock and Shy don't change pixels: toggling them keeps the cached layers (#103).
- #[test]
- fn audio_lock_and_shy_keep_cached_layers() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"name": "C", "width": 160, "height": 90, "frameRate": 30, "duration": 1})).unwrap();
- s.execute("layer.newSolid", json!({"color": "#3080ff", "width": 80, "height": 40})).unwrap();
- s.execute("effect.apply", json!({"layer": "#1", "effect": "Gaussian Blur"})).unwrap();
- s.execute("prop.set", json!({"layer": "#1", "path": "effects/#1/blurriness", "value": 12})).unwrap();
- let cid = s.active_comp_id().unwrap();
- let t = s.time();
- s.render(cid, t, Default::default());
- let before = s.layer_cache.stats();
- for sw in ["audio", "lock", "shy"] {
- s.execute("layer.setSwitch", json!({"layers": ["#1"], "switch": sw, "value": sw != "audio"})).unwrap();
- }
- s.render(cid, t, Default::default());
- let after = s.layer_cache.stats();
- assert_eq!(after.misses, before.misses, "no layer rendered again");
- assert!(after.hits > before.hits);
- }
-
- #[test]
- fn every_command_has_unique_id_and_runs_or_reports() {
- let mut ids = std::collections::HashSet::new();
- for c in crate::command_specs() {
- assert!(ids.insert(c.id), "duplicate {}", c.id);
- }
- assert!(ids.len() >= 90, "{}", ids.len());
- }
-
- #[test]
- fn layer_workflow_with_undo() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"name": "Test", "width": 640, "height": 360, "frameRate": 30, "duration": 4})).unwrap();
- let r = s.execute("layer.newSolid", json!({"color": "#336699"})).unwrap();
- let lid = r["layer"].as_u64().unwrap();
- s.execute("prop.set", json!({"layer": lid, "path": "transform/opacity", "value": 50})).unwrap();
- let tree = s.execute("layer.tree", json!({"layer": lid})).unwrap();
- assert!(tree.to_string().contains("\"value\":50.0"));
- s.execute("prop.toggleAnimation", json!({"layer": lid, "path": "transform/position"})).unwrap();
- s.execute("time.set", json!({"time": 2.0})).unwrap();
- s.execute("prop.set", json!({"layer": lid, "path": "transform/position", "value": [100, 100]})).unwrap();
- let comp = s.active_comp().unwrap();
- let pos = comp.layers[0].props.prop("transform/position").unwrap();
- assert_eq!(pos.keys.len(), 2);
- s.execute("prop.select", json!({"layer": lid, "path": "transform/position"})).unwrap();
- assert_eq!(s.state.selected_keys.len(), 2);
- s.execute("keys.easyEase", json!({})).unwrap();
- s.execute("keys.move", json!({"delta": 0.5})).unwrap();
- let pos = s.active_comp().unwrap().layers[0].props.prop("transform/position").unwrap().clone();
- assert!((pos.keys[0].time.seconds() - 0.5).abs() < 0.02);
- assert_eq!(pos.keys[0].out_interp, effectcraft_keyframe::Interp::Bezier);
- // undo back to before the move
- s.execute("edit.undo", json!({})).unwrap();
- let pos = s.active_comp().unwrap().layers[0].props.prop("transform/position").unwrap().clone();
- assert!(pos.keys[0].time.seconds().abs() < 0.02);
- s.execute("effect.apply", json!({"layer": lid, "effect": "Gaussian Blur"})).unwrap();
- s.execute("prop.set", json!({"layer": lid, "path": "effects/#1/blurriness", "value": 12})).unwrap();
- // Applying selects the new effect (Edit ▸ Duplicate would duplicate it); select the layer.
- s.execute("layer.select", json!({"layers": [lid]})).unwrap();
- s.execute("edit.duplicate", json!({})).unwrap();
- assert_eq!(s.active_comp().unwrap().layers.len(), 2);
- s.execute("layer.precompose", json!({"layers": [1, 2], "name": "Pre"})).unwrap();
- assert_eq!(s.active_comp().unwrap().layers.len(), 1);
- }
-
- #[test]
- fn text_shape_mask_matte_parent() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"width": 800, "height": 450, "duration": 3})).unwrap();
- let t = s.execute("layer.newText", json!({"text": "Hello", "size": 90})).unwrap()["layer"].as_u64().unwrap();
- s.execute("layer.addTextAnimator", json!({"layer": t, "properties": ["position", "opacity"]})).unwrap();
- let sh = s.execute("layer.newShape", json!({"kind": "star", "fill": "#ffcc00"})).unwrap()["layer"].as_u64().unwrap();
- s.execute("layer.addShapeItem", json!({"layer": sh, "kind": "trim"})).unwrap();
- s.execute("layer.addMask", json!({"layer": sh, "shape": "ellipse"})).unwrap();
- s.execute("layer.setMask", json!({"layer": sh, "mask": 1, "mode": "Subtract", "inverted": true})).unwrap();
- s.execute("layer.setTrackMatte", json!({"layer": sh, "matte": t, "kind": "luma"})).unwrap();
- s.execute("layer.setParent", json!({"layers": [sh], "parent": t})).unwrap();
- assert!(s.execute("layer.setParent", json!({"layers": [t], "parent": sh})).is_err());
- s.execute("layer.setBlendMode", json!({"layers": [sh], "mode": "Screen"})).unwrap();
- s.execute("layer.setSwitch", json!({"layers": [sh], "switch": "threeD"})).unwrap();
- let cid = s.active_comp_id().unwrap();
- let _ = s.render(cid, s.time(), Default::default());
- let info = s.execute("comp.info", json!({})).unwrap();
- assert_eq!(info["layers"].as_array().unwrap().len(), 2);
- }
-
- /// The toolbar's Fill / Stroke change a selected shape layer's paint (#205): a shape drawn
- /// without a stroke gets one, later edits change it, and the Contents "Add:" items (#206) include
- /// an empty Path and a Gradient Stroke that render.
- #[test]
- fn toolbar_fill_and_stroke_paint_selected_shape_layers() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"width": 400, "height": 300, "duration": 2})).unwrap();
- let sh = s.execute("layer.newShape", json!({"kind": "rect", "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
- let paint = |s: &mut Session| s.execute("shape.fillStroke", json!({})).unwrap();
- assert_eq!(paint(&mut s)["stroke"], serde_json::Value::Null, "drawn without a stroke");
- s.execute("shape.fillStroke", json!({"stroke": "#00ff00", "strokeWidth": 6})).unwrap();
- let p = paint(&mut s);
- assert_eq!((p["stroke"][1].as_f64(), p["strokeWidth"].as_f64()), (Some(1.0), Some(6.0)), "{p}");
- s.execute("shape.fillStroke", json!({"fill": "#0000ff", "strokeWidth": 3})).unwrap();
- let p = paint(&mut s);
- assert_eq!((p["fill"][2].as_f64(), p["strokeWidth"].as_f64()), (Some(1.0), Some(3.0)), "{p}");
- // One stroke, before the fill (paths, stroke, fill), and each change is one undo step.
- let l = s.active_comp().unwrap().layer(effectcraft_project::LayerId(sh)).unwrap().clone();
- let group = l.props.group("contents/group").unwrap();
- let order: Vec<&str> = group.sub("contents").unwrap().groups().map(|g| g.match_id.as_str()).collect();
- assert_eq!(order, ["rect", "stroke", "fill"]);
- s.execute("edit.undo", json!({})).unwrap();
- assert_eq!(paint(&mut s)["strokeWidth"].as_f64(), Some(6.0));
- // Only shape layers.
- s.execute("layer.newSolid", json!({"color": "#808080"})).unwrap();
- assert!(s.execute("shape.fillStroke", json!({"fill": "#ffffff"})).is_err());
- for kind in ["path", "gstroke"] {
- let r = s.execute("layer.addShapeItem", json!({"layer": sh, "kind": kind})).unwrap();
- assert!(r["path"].as_str().is_some_and(|p| p.starts_with("contents/")), "{r}");
- }
- let cid = s.active_comp_id().unwrap();
- let _ = s.render(cid, s.time(), Default::default());
- }
-
- /// The toolbar's Fill Options / Stroke Options change a selected shape layer's paint kind (#732):
- /// None switches the fill off, a gradient turns the Fill into a Gradient Fill that keeps its
- /// opacity, Solid Color turns it back, and a Stroke kind adds a stroke where there is none.
- #[test]
- fn toolbar_fill_and_stroke_kinds_change_selected_shape_layers() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"width": 400, "height": 300, "duration": 2})).unwrap();
- let sh = s.execute("layer.newShape", json!({"kind": "rect", "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
- let items = |s: &Session| -> Vec<(String, bool)> {
- let l = s.active_comp().unwrap().layer(effectcraft_project::LayerId(sh)).unwrap();
- l.props.group("contents/group/contents").unwrap().groups().map(|g| (g.match_id.clone(), g.enabled)).collect()
- };
- let kinds = |s: &mut Session| {
- let p = s.execute("shape.fillStroke", json!({})).unwrap();
- (p["fillType"].as_str().unwrap().to_string(), p["strokeType"].as_str().unwrap().to_string())
- };
- assert_eq!(kinds(&mut s), ("solid".into(), "none".into()));
- let cid = s.active_comp_id().unwrap();
- let centre = |s: &Session| s.render(cid, s.time(), Default::default()).get(200, 150);
- let red = centre(&s);
- // None switches the fill off: nothing is drawn, and the item stays.
- s.execute("shape.fillStroke", json!({"fillType": "none"})).unwrap();
- assert_eq!(items(&s), [("rect".into(), true), ("fill".into(), false)]);
- assert_eq!(kinds(&mut s).0, "none");
- assert_ne!(centre(&s), red, "the fill is off");
- // A radial gradient: the Fill becomes a Gradient Fill (switched on) that keeps its opacity.
- s.execute("shape.fillStroke", json!({"fillType": "solid", "fill": "#ff0000"})).unwrap();
- assert_eq!(centre(&s), red);
- let opacity = |s: &Session, m: &str| {
- let l = s.active_comp().unwrap().layer(effectcraft_project::LayerId(sh)).unwrap();
- l.props.group(&format!("contents/group/contents/{m}")).unwrap().get("opacity").unwrap().value.as_f64()
- };
- s.execute("prop.set", json!({"layer": sh, "path": "contents/group/contents/fill/opacity", "value": 40})).unwrap();
- s.execute("shape.fillStroke", json!({"fillType": "radial"})).unwrap();
- assert_eq!(items(&s), [("rect".into(), true), ("gfill".into(), true)]);
- assert_eq!((kinds(&mut s).0.as_str(), opacity(&s, "gfill")), ("radial", 40.0));
- s.execute("shape.fillStroke", json!({"fillType": "linear"})).unwrap();
- assert_eq!(kinds(&mut s).0, "linear");
- s.execute("shape.fillStroke", json!({"fillType": "solid", "fill": "#00ff00"})).unwrap();
- assert_eq!(items(&s), [("rect".into(), true), ("fill".into(), true)]);
- assert_eq!(opacity(&s, "fill"), 40.0);
- // A Stroke kind adds a stroke (before the fill); None switches it off again; undo is per step.
- s.execute("shape.fillStroke", json!({"strokeType": "linear"})).unwrap();
- assert_eq!(items(&s), [("rect".into(), true), ("gstroke".into(), true), ("fill".into(), true)]);
- s.execute("shape.fillStroke", json!({"strokeType": "none"})).unwrap();
- assert_eq!(kinds(&mut s), ("solid".into(), "none".into()));
- s.execute("edit.undo", json!({})).unwrap();
- assert_eq!(kinds(&mut s), ("solid".into(), "linear".into()));
- assert!(s.execute("shape.fillStroke", json!({"fillType": "plaid"})).is_err());
- }
-
- /// Selecting a mask in the Timeline (its row or its Mask Path) selects all of its points, so the
- /// viewer drags the whole mask (#203); a shape's Path item works the same way.
- #[test]
- fn selecting_a_mask_selects_its_points() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"width": 400, "height": 300, "duration": 2})).unwrap();
- let l = s.execute("layer.newSolid", json!({"color": "#808080"})).unwrap()["layer"].as_u64().unwrap();
- let m1 = s.execute("layer.addMask", json!({"layer": l, "shape": "rect"})).unwrap()["mask"].as_u64().unwrap();
- let m2 = s.execute("layer.addMask", json!({"layer": l, "shape": "ellipse"})).unwrap()["mask"].as_u64().unwrap();
- let points = |s: &Session, m: u64| s.state.selected_vertices.iter().filter(|v| v.mask == m).count();
- s.execute("prop.select", json!({"layer": l, "prop": m1, "selectKeys": false})).unwrap();
- assert_eq!((points(&s, m1), s.state.selected_vertices.len()), (4, 4));
- // Mask Path selects them too; Shift-adding another mask keeps the first.
- let path = s.active_comp().unwrap().layer(effectcraft_project::LayerId(l)).unwrap().props.find_group(m2).unwrap().get("path").unwrap().uid;
- s.execute("prop.select", json!({"layer": l, "prop": path, "add": true})).unwrap();
- assert_eq!((points(&s, m1), points(&s, m2)), (4, 4));
- // Another mask replaces them; another property deselects them.
- s.execute("prop.select", json!({"layer": l, "prop": m2})).unwrap();
- assert_eq!((points(&s, m1), points(&s, m2)), (0, 4));
- // Delete removes the selected mask (not only its points).
- s.execute("edit.clear", json!({})).unwrap();
- let masks = |s: &Session| s.active_comp().unwrap().layer(effectcraft_project::LayerId(l)).unwrap().masks().unwrap().children.len();
- assert_eq!(masks(&s), 1);
- s.execute("prop.select", json!({"layer": l, "path": "transform/opacity"})).unwrap();
- assert!(s.state.selected_vertices.is_empty());
- let sh = s.execute("layer.newShape", json!({"kind": "star"})).unwrap()["layer"].as_u64().unwrap();
- let star = s.execute("layer.addShapeItem", json!({"layer": sh, "kind": "path"})).unwrap()["uid"].as_u64().unwrap();
- s.execute("prop.select", json!({"layer": sh, "prop": star})).unwrap();
- assert_eq!(s.state.selected_vertices.len(), 0, "an empty Path has no points");
- }
-
- #[test]
- fn save_and_open_roundtrip() {
- let mut s = demo();
- let dir = std::env::temp_dir().join(format!("ec-test-{}", std::process::id()));
- std::fs::create_dir_all(&dir).unwrap();
- let path = dir.join("demo.ecproj").to_string_lossy().to_string();
- s.execute("file.saveAs", json!({"path": path})).unwrap();
- let before = s.project.clone();
- let mut s2 = Session::default();
- s2.execute("file.open", json!({"path": path})).unwrap();
- assert_eq!(*before, *s2.project);
- let _ = std::fs::remove_dir_all(dir);
- }
-
- #[test]
- fn help_links_emit_urls() {
- let mut s = Session::default();
- let r = s.execute("help.discord", json!({})).unwrap();
- assert_eq!(r["url"], "https://discord.gg/artcraft");
- assert!(s.drain_events().iter().any(|e| matches!(e, crate::Event::OpenUrl(u) if u.contains("discord"))));
- assert_eq!(s.execute("help.github", json!({})).unwrap()["url"], "https://github.com/storytold/effectcraft");
- }
-
- #[test]
- fn time_navigation() {
- let mut s = demo();
- s.execute("time.start", json!({})).unwrap();
- let r = s.execute("time.nextKey", json!({})).unwrap();
- assert!(r["time"].as_f64().unwrap() > 0.0);
- s.execute("time.set", json!({"frame": 45})).unwrap();
- assert_eq!(s.execute("time.step", json!({"frames": 5})).unwrap()["frame"], 50);
- }
-
- #[test]
- fn time_navigation_per_property() {
- let mut s = demo();
- // An animated property and the comp times of its keys.
- let comp = s.active_comp().unwrap().clone();
- let mut found = None;
- for l in &comp.layers {
- l.props.walk("", &mut |_, pr| {
- if found.is_none() && pr.keys.len() >= 2 {
- found = Some((pr.uid, pr.keys.iter().map(|k| l.comp_time(k.time)).collect::<Vec<_>>()));
- }
- });
- }
- let (uid, times) = found.expect("demo has an animated property");
- s.set_time(effectcraft_time::Tick::ZERO);
- let half = comp.frame_duration().0 / 2;
- let expect = times.iter().copied().filter(|t| t.0 > half).min().unwrap();
- s.execute("time.go", json!({"to": "nextKey", "prop": uid})).unwrap();
- let snap = |t| comp.frame_rate.snap(t);
- assert_eq!(s.time(), snap(expect));
- // Going back from past the last key lands on the last key.
- s.set_time(comp.duration);
- s.execute("time.go", json!({"to": "prevKey", "prop": uid})).unwrap();
- assert_eq!(s.time(), snap(*times.iter().max().unwrap()));
- }
-
- #[test]
- fn set_text_paragraph_fill_and_leading() {
- use effectcraft_keyframe::{Justify, Value as KValue};
- let mut s = demo();
- let t = s.execute("layer.newText", json!({"text": "Hi"})).unwrap()["layer"].as_u64().unwrap();
- let doc = |s: &Session| {
- let l = s.active_comp().unwrap().layer(crate::project::LayerId(t)).unwrap().clone();
- match &l.props.prop("text/sourceText").unwrap().value {
- KValue::Text(d) => (**d).clone(),
- v => panic!("{v:?}"),
- }
- };
- for (key, j) in [
- ("justifyLeft", Justify::JustifyLastLeft),
- ("justifyCenter", Justify::JustifyLastCenter),
- ("justifyRight", Justify::JustifyLastRight),
- ("justifyAll", Justify::JustifyAll),
- ("center", Justify::Center),
- ] {
- s.execute("layer.setText", json!({"layer": t, "justify": key})).unwrap();
- assert_eq!(doc(&s).justify, j, "{key}");
- }
- s.execute("layer.setText", json!({"layer": t, "leading": 50, "applyFill": false, "applyStroke": true})).unwrap();
- let d = doc(&s);
- assert_eq!((d.leading, d.apply_fill, d.apply_stroke), (Some(50.0), false, true));
- s.execute("layer.setText", json!({"layer": t, "leading": "auto"})).unwrap();
- assert_eq!(doc(&s).leading, None);
- s.execute("layer.setText", json!({"layer": t, "hScale": 120, "vScale": 80, "baselineShift": 4, "smallCaps": true, "strokeOverFill": true})).unwrap();
- let d = doc(&s);
- assert_eq!((d.h_scale, d.v_scale, d.baseline_shift, d.small_caps, d.stroke_over_fill), (120.0, 80.0, 4.0, true, true));
- }
-
- #[test]
- fn property_groups_report_actionable_errors() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"name": "T"})).unwrap();
- let l = s.execute("layer.newText", json!({"text": "Hi"})).unwrap()["layer"].as_u64().unwrap();
- let uid = s.active_comp().unwrap().layer(crate::project::LayerId(l)).unwrap().props.group("text/pathOptions").unwrap().uid;
- for selector in [json!({"path": "text"}), json!({"path": "text/pathOptions"}), json!({"path": format!("@{uid}")}), json!({"prop": uid})] {
- let mut params = selector;
- params["layer"] = json!(l);
- for cmd in ["prop.get", "prop.set"] {
- let err = s.execute(cmd, params.clone()).unwrap_err().to_string();
- assert!(err.contains("is a property group"), "{cmd}: {err}");
- assert!(err.contains("get_layer"), "{cmd}: {err}");
- }
- }
- assert!(s.execute("prop.get", json!({"layer": l, "path": "text/sourceText"})).is_ok());
- let err = s.execute("prop.get", json!({"layer": l, "path": "missing"})).unwrap_err().to_string();
- assert!(err.contains("no property `missing`"), "{err}");
- }
-
- #[test]
- fn prop_get_and_render_rgba8() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"name": "T", "width": 320, "height": 180, "duration": 2.0, "frameRate": 30})).unwrap();
- let l = s.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
- s.execute("prop.addKey", json!({"layer": l, "path": "transform/position", "time": 0.0, "value": [0, 0]})).unwrap();
- s.execute("prop.addKey", json!({"layer": l, "path": "transform/position", "time": 1.0, "value": [100, 50]})).unwrap();
- let v = s.execute("prop.get", json!({"layer": l, "path": "transform/position", "time": 1.0})).unwrap();
- assert_eq!(v["animated"], true);
- assert_eq!(v["keys"].as_array().unwrap().len(), 2);
- assert_eq!(v["value"][0].as_f64().unwrap(), 100.0);
- let cid = s.resolve_comp(Some(&json!("T"))).unwrap();
- let (w, h, rgba) = s.render_rgba8(cid, effectcraft_time::Tick::ZERO, 160).unwrap();
- assert_eq!((w, h), (160, 90));
- assert_eq!(rgba.len(), (w * h * 4) as usize);
- }
-
- #[test]
- fn params_docs_parse() {
- use crate::commands::accepted_params;
- let k = |d: &str| accepted_params(d).unwrap();
- assert_eq!(k("{layers: [id|name|#n], add?, toggle?}"), ["layers", "add", "toggle"]);
- assert_eq!(k("{time? (s) | frame? | timecode?}"), ["time", "frame", "timecode"]);
- assert_eq!(k("{interpolation?|in?|out?: linear|bezier|hold, autoBezier?}"), ["interpolation", "in", "out", "autoBezier"]);
- assert_eq!(k("{keys: [{layer, prop, time}], add?}"), ["keys", "add"]);
- assert_eq!(k("{label: Red|Yellow|Aqua|…, layers?}"), ["label", "layers"]);
- assert_eq!(k("{name?, background? [r,g,b]|#hex, open?}"), ["name", "background", "open"]);
- assert!(k("{}").is_empty());
- assert!(accepted_params("free text").is_none());
- // Every registered command documents its params as a parseable key list.
- for c in crate::command_specs() {
- assert!(accepted_params(c.params).is_some(), "{}: {}", c.id, c.params);
- }
- }
-
- #[test]
- fn execute_checked_rejects_unknown_params() {
- let mut s = demo();
- let e = s.execute_checked("layer.select", json!({"index": 2})).unwrap_err().to_string();
- assert!(e.contains("`index`") && e.contains("layers, add, toggle"), "{e}");
- s.execute_checked("layer.select", json!({"layers": ["#2"]})).unwrap();
- assert_eq!(s.state.selected_layers.len(), 1);
- // Aliases and always-accepted keys.
- s.execute_checked("layer.select", json!({"layer": "#1", "comp": s.active_comp_id().unwrap().0})).unwrap();
- s.execute_checked("time.set", json!({"frame": 3})).unwrap();
- assert!(s.execute_checked("edit.undo", json!({"steps": 2})).is_err());
- // Non-object params are not validated; the unchecked path stays lenient.
- s.execute("layer.select", json!({"layers": ["#1"], "index": 2})).unwrap();
- }
-
- #[test]
- fn layer_tree_paths_resolve() {
- let mut s = demo();
- s.execute("effect.apply", json!({"layer": 1, "effect": "Gaussian Blur"})).unwrap();
- let comp = s.execute("comp.info", json!({})).unwrap();
- let mut checked = 0;
- for l in comp["layers"].as_array().unwrap() {
- let tree = s.execute("layer.tree", json!({"layer": l["id"]})).unwrap();
- let mut stack = vec![tree["properties"].clone()];
- while let Some(n) = stack.pop() {
- if let Some(ch) = n["children"].as_array() {
- stack.extend(ch.iter().cloned());
- continue;
- }
- let path = n["path"].as_str().unwrap();
- let got = s.execute("prop.get", json!({"layer": l["id"], "path": path})).unwrap();
- assert_eq!(got["uid"], n["uid"], "path {path} on layer {}", l["name"]);
- checked += 1;
- }
- }
- assert!(checked > 20, "{checked}");
- }
-
- #[test]
- fn comp_settings_anchor_start_timecode_renderer() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"name": "A", "width": 100, "height": 100, "duration": 2.0})).unwrap();
- let l = s.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
- s.execute("prop.addKey", json!({"layer": l, "path": "transform/position", "time": 0.0, "value": [10, 20]})).unwrap();
- let pos = |s: &Session| {
- let pr = s.active_comp().unwrap().layer(crate::project::LayerId(l)).unwrap().props.prop("transform/position").unwrap().clone();
- pr.keys[0].value.components()
- };
- // Center anchor: grow by 100x50 → shift by half.
- s.execute("comp.settings", json!({"width": 200, "height": 150})).unwrap();
- assert_eq!(pos(&s)[..2], [60.0, 45.0]);
- // Top-left anchor: no shift. Bottom-right: full shift.
- s.execute("comp.settings", json!({"width": 300, "anchor": 0})).unwrap();
- assert_eq!(pos(&s)[..2], [60.0, 45.0]);
- s.execute("comp.settings", json!({"width": 200, "height": 100, "anchor": 8})).unwrap();
- assert_eq!(pos(&s)[..2], [-40.0, -5.0]);
- s.execute("comp.settings", json!({"startTimecode": "0:00:01:00", "renderer": "advanced3D"})).unwrap();
- let c = s.active_comp().unwrap();
- assert_eq!(c.display_start, c.frame_rate.tick_of(30));
- assert_eq!(c.renderer, crate::project::Renderer::Advanced3D);
- }
-
- /// `advanced3D` is a value of `renderer`, not a key: comp.new / comp.settings don't advertise it
- /// in their schemas and reject it as unknown instead of ignoring it (#177).
- #[test]
- fn renderer_values_are_not_parameter_keys() {
- let mut s = Session::default();
- for (id, p) in [("comp.new", json!({"name": "A"})), ("comp.settings", json!({}))] {
- let spec = crate::command_specs().iter().find(|c| c.id == id).unwrap();
- let keys = crate::commands::accepted_params(spec.params).unwrap();
- assert!(keys.contains(&"renderer".to_string()) && !keys.contains(&"advanced3D".to_string()), "{id}: {keys:?}");
- let mut bad = p.clone();
- bad["advanced3D"] = json!(true);
- let e = s.execute_checked(id, bad).unwrap_err().to_string();
- assert!(e.contains("unknown parameter(s) `advanced3D`"), "{id}: {e}");
- let mut good = p;
- good["renderer"] = json!("advanced3D");
- s.execute_checked(id, good).unwrap();
- assert_eq!(s.active_comp().unwrap().renderer, crate::project::Renderer::Advanced3D, "{id}");
- s.execute("comp.renderer", json!({"renderer": "classic3d"})).unwrap();
- }
- }
-
- #[test]
- fn comp_rejects_zero_and_negative_frame_rates() {
- let mut s = Session::default();
- for fps in [0.0, -30.0, 0.0001] {
- assert!(s.execute("comp.new", json!({"frameRate": fps})).is_err(), "{fps}");
- }
- s.execute("comp.new", json!({"frameRate": 30, "duration": 1})).unwrap();
- assert!(s.execute("comp.settings", json!({"frameRate": 0})).is_err());
- assert_eq!(s.active_comp().unwrap().frame_rate, crate::time::FrameRate::FPS_30);
- }
-
- #[test]
- fn render_queue_add_accepts_documented_settings_when_checked() {
- let mut s = demo();
- let r = s.execute_checked(
- "renderQueue.add",
- json!({"format": "gif", "output": "/tmp/x.gif", "resolution": "quarter", "timeSpan": "custom", "start": 0.0, "end": 0.5, "quality": "draft", "loop": true}),
- );
- // Without an exporter the add itself still succeeds (rendering is what needs one).
- assert!(r.is_ok(), "{r:?}");
- assert!(s.execute_checked("renderQueue.add", json!({"bogus": 1})).is_err());
- }
-
- #[test]
- fn new_text_rejects_malformed_positions_without_creating_a_layer() {
- let mut s = Session::default();
- s.execute("comp.new", json!({"name": "C", "width": 64, "height": 64, "duration": 1})).unwrap();
- for position in [json!([]), json!([10]), json!(["x", 20]), json!([null, 20])] {
- let err = s.execute("layer.newText", json!({"text": "Hello", "position": position})).unwrap_err();
- assert!(err.to_string().contains("position: [x, y]"), "{err}");
- assert!(s.active_comp().unwrap().layers.is_empty());
- }
- s.execute("layer.newText", json!({"name": "Valid", "text": "Hello", "position": [10, 20]})).unwrap();
- assert_eq!(s.active_comp().unwrap().layers[0].props.prop("transform/position").unwrap().value, effectcraft_keyframe::Value::Vec3([10.0, 20.0, 0.0]));
- s.execute("layer.newText", json!({"text": "No explicit position"})).unwrap();
- assert_eq!(s.active_comp().unwrap().layers.len(), 2);
- }
-
- /// The active comp and the open comp tabs are saved with the project and restored on open (#748).
- #[test]
- fn reopening_a_project_restores_its_active_comp() {
- use effectcraft_project::ItemId;
- let dir = std::env::temp_dir().join(format!("ec-test-748-{}", std::process::id()));
- std::fs::create_dir_all(&dir).unwrap();
- let path = dir.join("view.ecproj").to_string_lossy().to_string();
- let mut s = Session::default();
- let a = s.execute("comp.new", json!({"name": "CompA"})).unwrap()["comp"].as_u64().unwrap();
- let b = s.execute("comp.new", json!({"name": "CompB"})).unwrap()["comp"].as_u64().unwrap();
- let c = s.execute("comp.new", json!({"name": "CompC"})).unwrap()["comp"].as_u64().unwrap();
- s.execute("comp.open", json!({"comp": "CompB"})).unwrap();
- s.state.open_comps.retain(|id| id.0 != c);
- s.execute("file.saveAs", json!({"path": path})).unwrap();
- let mut s2 = Session::default();
- s2.execute("file.open", json!({"path": path})).unwrap();
- assert_eq!(s2.state.active_comp, Some(ItemId(b)));
- assert_eq!(s2.state.open_comps, vec![ItemId(a), ItemId(b)]);
- assert!(!s2.is_dirty());
-
- // A file from before the view was saved opens on its first comp, as it always did.
- let text = std::fs::read_to_string(&path).unwrap();
- let mut old: serde_json::Value = serde_json::from_str(&text).unwrap();
- let obj = old.as_object_mut().unwrap();
- obj.remove("activeComp");
- obj.remove("openComps");
- std::fs::write(&path, serde_json::to_string_pretty(&old).unwrap()).unwrap();
- let mut s3 = Session::default();
- s3.execute("file.open", json!({"path": path})).unwrap();
- assert_eq!((s3.state.active_comp, s3.state.open_comps.clone()), (Some(ItemId(a)), vec![ItemId(a)]));
-
- // Ids that no longer name a comp (edited by hand, or written by another tool) fall back.
- obj_set(&mut old, json!(999), json!([999, b, "x"]));
- std::fs::write(&path, serde_json::to_string_pretty(&old).unwrap()).unwrap();
- let mut s4 = Session::default();
- s4.execute("file.open", json!({"path": path})).unwrap();
- assert_eq!((s4.state.active_comp, s4.state.open_comps.clone()), (Some(ItemId(b)), vec![ItemId(b)]));
- obj_set(&mut old, json!(999), json!([]));
- std::fs::write(&path, serde_json::to_string_pretty(&old).unwrap()).unwrap();
- let mut s5 = Session::default();
- s5.execute("file.open", json!({"path": path})).unwrap();
- assert_eq!((s5.state.active_comp, s5.state.open_comps.clone()), (Some(ItemId(a)), vec![ItemId(a)]));
-
- // XML copies carry it too.
- let xml = dir.join("view.ecprojx").to_string_lossy().to_string();
- s.execute("file.saveAs", json!({"path": xml})).unwrap();
- let mut s6 = Session::default();
- s6.execute("file.open", json!({"path": xml})).unwrap();
- assert_eq!(s6.state.active_comp, Some(ItemId(b)));
- let _ = std::fs::remove_dir_all(dir);
-
- fn obj_set(v: &mut serde_json::Value, active: serde_json::Value, open: serde_json::Value) {
- let o = v.as_object_mut().unwrap();
- o.insert("activeComp".into(), active);
- o.insert("openComps".into(), open);
- }
- }
-
- /// Layer times are saved as exact ticks and read back unchanged, and each comp reopens at the
- /// current time it was saved at, not at 0, where a layer starting later shows nothing (#1714).
- #[test]
- fn reopening_a_project_restores_layer_times_and_current_time() {
- use effectcraft_project::ItemId;
- use effectcraft_time::{FrameRate, Tick};
- let dir = std::env::temp_dir().join(format!("ec-test-1714-{}", std::process::id()));
- std::fs::create_dir_all(&dir).unwrap();
- let path = dir.join("times.ecproj").to_string_lossy().to_string();
- let mut s = Session::default();
- s.execute("comp.new", json!({"name": "C", "width": 108, "height": 192, "duration": 60})).unwrap();
- s.execute("layer.newSolid", json!({"name": "crown"})).unwrap();
- let cid = s.active_comp_id().unwrap();
- let comp = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap();
- comp.frame_rate = FrameRate::FPS_59_94;
- // The layer from the issue: 34f, 315f and 3033f at 59.94 fps.
- let l = comp.layers.first_mut().unwrap();
- (l.start_time, l.in_point, l.out_point) = (Tick(144_086_342_400), Tick(1_334_917_584_000), Tick(12_853_349_308_800));
- s.execute("time.set", json!({"time": 6.0})).unwrap();
- let t = s.time();
- // A second comp keeps its own time.
- let b = ItemId(s.execute("comp.new", json!({"name": "B"})).unwrap()["comp"].as_u64().unwrap());
- s.execute("time.set", json!({"time": 2.0})).unwrap();
- let tb = s.time();
- s.execute("comp.open", json!({"comp": "C"})).unwrap();
- s.execute("file.saveAs", json!({"path": path})).unwrap();
-
- let mut s2 = Session::default();
- s2.execute("file.open", json!({"path": path})).unwrap();
- let l = s2.project.comp(cid).unwrap().layers.first().unwrap();
- assert_eq!((l.start_time, l.in_point, l.out_point), (Tick(144_086_342_400), Tick(1_334_917_584_000), Tick(12_853_349_308_800)));
- assert_eq!((s2.time(), s2.state.times.get(&b).copied()), (t, Some(tb)));
- assert!(l.in_point <= s2.time() && s2.time() < l.out_point, "the layer shows at the reopened time");
- assert!(!s2.is_dirty());
-
- // Hand-edited times past the end or before the start land on the last or first frame.
- let mut file: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
- file["compTimes"] = json!({cid.0.to_string(): i64::MAX, b.0.to_string(): -5});
- std::fs::write(&path, file.to_string()).unwrap();
- let mut s3 = Session::default();
- s3.execute("file.open", json!({"path": path})).unwrap();
- let c = s3.project.comp(cid).unwrap();
- assert_eq!(s3.time(), c.frame_rate.snap_nearest(c.duration - c.frame_duration()));
- assert_eq!(s3.time(), c.frame_rate.snap_nearest(c.duration - c.frame_duration()));
- assert_eq!(s3.state.times.get(&b).copied(), Some(Tick::ZERO));
- }
+ mod anim_presets;
+ mod anim_tools;
+ mod camera_track;
+ mod codec_options;
+ mod color_view;
+ mod crypto_pick;
+ mod delete_keys;
+ mod disk_cache;
+ mod effects;
+ mod essential;
+ mod essential_more;
+ mod face;
+ mod fidelity;
+ mod frame_export;
+ mod fuzz_open;
+ mod history;
+ mod import_project;
++mod instance3d;
+ mod key_metadata_order;
+ mod key_time;
+ mod keylight;
+ mod limits;
+ mod lottie;
+ mod m137;
+ mod m145;
+ mod markers;
+ mod mask_warp;
+ mod menu_cmds;
+ mod model3d;
+ mod models;
+ mod motion_blur_depth;
+ mod paint;
+ mod panels;
+ mod project_items;
+ mod proxy;
+ mod quick_offset;
+ mod replace_source;
+ mod rig3d;
+ pub(crate) mod roto;
+ mod sequence;
+ mod session;
+ mod settings;
+ mod shortcut_cmds;
+ pub(crate) mod stubs;
+ mod styles;
+ mod tail;
+ mod text;
+ mod text_edit;
+ mod three_d;
+ mod timeline;
+ mod timeline_interchange;
+ pub(crate) mod track;
+ mod vector_import;
+ mod viewer;
diff --cc crates/engine/src/tests/instance3d.rs
index aa31d3944,000000000..aa31d3944
mode 100644,000000..100644
--- a/crates/engine/src/tests/instance3d.rs
+++ b/crates/engine/src/tests/instance3d.rs
diff --cc crates/render/src/fx_host.rs
index 000000000,6275af5f0..b111daf64
mode 000000,100644..100644
--- a/crates/render/src/fx_host.rs
+++ b/crates/render/src/fx_host.rs
@@@ -1,0 -1,157 +1,165 @@@
+ use super::*;
+
+ /// Layer parameters and audio for effects (see [`effectcraft_effects::EffectHost`]). What it
+ /// hands out is in effect space (see [`effect_bounds`]): the other layer's for its pixels, the
+ /// running layer's for its own frames and the comp scene.
+ pub(crate) struct FxHost<'r, 'a, 'c> {
+ pub(crate) r: &'r Renderer<'a>,
+ pub(crate) ctx: &'c EvalCtx<'a>,
+ pub(crate) layer: &'c Layer,
+ /// Where the stack's effect space starts in layer coordinates (zero on adjustment layers,
+ /// whose effects run on the comp below).
+ pub(crate) origin: [f64; 2],
+ /// Index of the effect being rendered (bounds `self_at` to effects before it).
+ pub(crate) index: usize,
+ pub(crate) original: Option<&'c Buf>,
+ }
+
+ impl FxHost<'_, '_, '_> {
+ /// Another layer's pixels for a layer parameter, in its effect space; `layer_space`: `buf`
+ /// is still in layer space (its source or its content).
+ fn pixels(&self, other: &Layer, mut buf: Buf, layer_space: bool) -> LayerPixels {
+ let (size, origin) = self.ctx.effect_bounds(other);
+ if layer_space {
+ buf.rebase(origin);
+ }
+ LayerPixels { buf, size }
+ }
+ }
+
+ /// The comp's camera and first light relative to `layer`, in its layer pixels (see
+ /// [`EffectHost::comp_scene`]): the comp camera's view of the layer (as if 3D at its transform),
+ /// brought back into the layer's own pixel grid through the inverse of how the layer itself
+ /// composites.
+ pub(crate) fn comp_scene(ctx: &EvalCtx, layer: &Layer) -> Option<effectcraft_effects::CompScene> {
+ let world = ctx.world_matrix(layer);
+ let (cam, _, _) = ctx.camera();
+ let p = (cam * world).0;
+ let back = ctx.layer_to_comp(layer).0.inverse()?.0;
+ let rows = [p[0], p[1], p[3]];
+ let camera: [[f64; 4]; 3] = std::array::from_fn(|i| std::array::from_fn(|j| (0..3).map(|k| back[i][k] * rows[k][j]).sum()));
+ let inv = world.inverse();
+ let light = three_d::light::lights_at(ctx).first().and_then(|l| {
+ let inv = inv.as_ref()?;
+ let pos = inv.apply(l.pos);
+ let dir = inv.apply_vec(l.dir);
+ let len = (dir.x * dir.x + dir.y * dir.y + dir.z * dir.z).sqrt().max(1e-12);
+ let kind = match l.kind {
+ effectcraft_project::LightKind::Parallel => 0,
+ effectcraft_project::LightKind::Ambient => 2,
+ _ => 1,
+ };
+ Some(effectcraft_effects::CompLight { pos: [pos.x, pos.y, pos.z], dir: [dir.x / len, dir.y / len, dir.z / len], color: l.color, kind })
+ });
+ let camera_layer = ctx.comp.active_camera(ctx.time).is_some();
+ Some(effectcraft_effects::CompScene { camera: Some(camera), camera_layer, light })
+ }
+
+ /// Nesting limit for effects that render layers (other layers, other times).
+ pub(crate) const MAX_FX_DEPTH: usize = 8;
+
+ impl EffectHost for FxHost<'_, '_, '_> {
+ fn original(&self) -> Option<&Buf> {
+ self.original
+ }
+
+ fn particles(&self) -> Option<&dyn effectcraft_effects::psim::ParticleSim> {
+ self.r.active_accel().and_then(|a| a.particles())
+ }
+ fn layer(&self, id: u64, masks_and_effects: bool) -> Option<LayerPixels> {
+ let other = self.ctx.layer(effectcraft_project::LayerId(id))?;
+ if (other.id == self.layer.id && masks_and_effects) || self.r.depth > MAX_FX_DEPTH {
+ return None;
+ }
+ let sub = self.r.nested();
++ // A 3D model or primitive layer has no 2D source of its own: an effect referencing one
++ // reads it as After Effects does — the layer rendered on its own through the comp's
++ // camera (Create 3D Layer Instance's CC Composite), in the layer's effect space (the
++ // comp, centred on the layer's anchor).
++ if other.source.is_model() {
++ let buf = sub.solo_3d(self.ctx, other);
++ return Some(self.pixels(other, buf, false));
++ }
+ // The cached layer buffer is shared; effects get their own copy.
+ let buf = if masks_and_effects { (*sub.content_buf(self.ctx, other)?).clone() } else { sub.source(self.ctx, other)? };
+ Some(self.pixels(other, buf, true))
+ }
+
+ fn layer_masks(&self, id: u64) -> Option<LayerPixels> {
+ let other = self.ctx.layer(effectcraft_project::LayerId(id))?;
+ if self.r.depth > MAX_FX_DEPTH {
+ return None;
+ }
+ let sub = self.r.nested();
+ let buf = (*sub.layer_input(self.ctx, other, 0)?).clone();
+ Some(self.pixels(other, buf, false))
+ }
+
+ fn audio(&self, id: u64, start: f64, frames: usize, rate: u32) -> Option<Vec<f32>> {
+ let other = self.ctx.layer(effectcraft_project::LayerId(id))?;
+ let LayerSource::Footage { item } = &other.source else { return None };
+ let ItemKind::Footage(f) = &self.r.project.item(*item)?.kind else { return None };
+ if !f.has_audio {
+ return None;
+ }
+ let st = other.layer_time(Tick::from_seconds_f64(start));
+ self.r.footage.audio(*item, f, st, frames, rate)
+ }
+
+ fn self_at(&self, layer_time: f64, effects: usize) -> Option<Buf> {
+ if self.r.depth > MAX_FX_DEPTH || self.layer.switches.adjustment {
+ return None;
+ }
+ let n = effects.min(self.index);
+ let t = self.layer.comp_time(Tick::from_seconds_f64(layer_time));
+ let sub = self.r.nested();
+ sub.layer_input(&self.ctx.at(t), self.layer, n).map(|b| (*b).clone())
+ }
+
+ fn aux(&self) -> Option<Arc<effectcraft_raster::AuxChannels>> {
+ self.r.layer_aux(self.ctx, self.layer)
+ }
+
+ fn params_at(&self, layer_time: f64) -> Option<Params> {
+ let g = self.layer.effects()?.groups().nth(self.index)?;
+ let ctx = self.ctx.at(self.layer.comp_time(Tick::from_seconds_f64(layer_time)));
+ Some(effectcraft_effects::flatten_params(g, &mut |pr| ctx.value(self.layer, pr)))
+ }
+
+ fn comp_scene(&self) -> Option<effectcraft_effects::CompScene> {
+ Some(comp_scene(self.ctx, self.layer)?.rebased(self.origin))
+ }
+
+ fn layer_at(&self, id: u64, comp_time: f64, masks_and_effects: bool) -> Option<LayerPixels> {
+ let other = self.ctx.layer(effectcraft_project::LayerId(id))?;
+ if (other.id == self.layer.id && masks_and_effects) || !comp_time.is_finite() || self.r.depth > MAX_FX_DEPTH {
+ return None;
+ }
+ let ctx = self.ctx.at(Tick::from_seconds_f64(comp_time));
+ let sub = self.r.nested();
+ Some(if masks_and_effects {
+ self.pixels(other, (*sub.content_buf(&ctx, other)?).clone(), true)
+ } else if other.id == self.layer.id {
+ self.pixels(other, sub.source(&ctx, other)?, true)
+ } else {
+ // Preserve other-layer reads: time effects historically see source + masks.
+ self.pixels(other, (*sub.layer_input(&ctx, other, 0)?).clone(), false)
+ })
+ }
+ }
+
+ /// The Essential Properties overrides of a precomp layer, evaluated at the context time.
+ pub fn essential_overrides(ctx: &EvalCtx, layer: &Layer) -> Vec<effectcraft_project::essential::Override> {
+ use effectcraft_project::essential;
+ let over = essential::overridden(layer);
+ let Some(g) = essential::group(layer).filter(|_| !over.is_empty()) else { return vec![] };
+ let mut out = vec![];
+ g.walk("", &mut |_, p| {
+ if over.contains(&p.uid)
+ && let Some(control) = essential::control_of(&p.match_id)
+ {
+ out.push(essential::Override { control, value: ctx.value(layer, p) });
+ }
+ });
+ out
+ }
diff --cc crates/render/src/pipeline.rs
index 000000000,92b5b7f5c..a34605c2e
mode 000000,100644..100644
--- a/crates/render/src/pipeline.rs
+++ b/crates/render/src/pipeline.rs
@@@ -1,0 -1,886 +1,910 @@@
+ use super::accel::{Accelerator, Backend, CpuFx, FxStep, FxTarget};
+ use super::footage::{FootageSource, is_vector_footage};
+ use super::frames::{blend_frames, content_bounds, field_frame, frame_blend_mode, frame_position, frame_size, interpret_pixels, roi_inside};
+ use super::fx_host::{FxHost, essential_overrides};
+ use super::opts::{Collapse3d, LayerTiming, MAX_THROUGH, RenderOpts, Through};
+ use super::*;
+
+ impl<'a> Renderer<'a> {
+ pub fn new(project: &'a Project, footage: &'a dyn FootageSource, opts: RenderOpts) -> Renderer<'a> {
+ Renderer {
+ project,
+ footage,
+ expr: None,
+ opts,
+ cache: None,
+ profile: None,
+ accel: None,
+ depth: 0,
+ pipe: color::Pipe::of(&project.settings),
+ outer: None,
+ opacity_mul: 1.0,
+ collapse3d: None,
+ inherited: None,
+ defer_dof: false,
+ top: true,
+ through: [None; MAX_THROUGH],
+ through_lost: false,
+ }
+ }
+
+ /// The layer cache to keep this render's buffers in: none once its footage reads were
+ /// called off, as they may have come back empty ([`FootageSource::called_off`], #329).
+ pub(crate) fn cache_to_keep(&self) -> Option<&'a LayerCache> {
+ self.cache.filter(|_| !self.footage.called_off())
+ }
+
+ /// A layer's Quality switch, limited by the precomp layers above it when
+ /// [`RenderOpts::nested_switches`] is on.
+ pub fn quality(&self, layer: &Layer) -> Quality {
+ let rank = |q: Quality| match q {
+ Quality::Best => 0,
+ Quality::Draft => 1,
+ Quality::Wireframe => 2,
+ };
+ match self.inherited {
+ Some((q, _)) if rank(q) > rank(layer.switches.quality) => q,
+ _ => layer.switches.quality,
+ }
+ }
+
+ /// A layer's Motion Blur switch, limited by the precomp layers above it.
+ pub(crate) fn layer_motion_blur(&self, layer: &Layer) -> bool {
+ layer.switches.motion_blur && self.inherited.is_none_or(|(_, mb)| mb)
+ }
+
+ /// The renderer for the nested comp of precomp layer `layer`: its switches pass down when
+ /// [`RenderOpts::nested_switches`] is on.
+ fn nested_through(&self, layer: &Layer) -> Renderer<'a> {
+ let mut sub = self.nested();
+ if self.opts.nested_switches {
+ sub.inherited = Some((self.quality(layer), self.layer_motion_blur(layer)));
+ }
+ sub
+ }
+
+ /// The render options one level down (precomps, collapsed precomps, comps read by effects):
+ /// guide layers render only in their own comp, never when it is nested.
+ fn nested_opts(&self) -> RenderOpts {
+ RenderOpts { guides: false, ..self.opts }
+ }
+
+ /// A renderer for nested work (precomps, layers read by effects): one level deeper.
+ pub(crate) fn nested(&self) -> Renderer<'a> {
+ Renderer {
+ opts: self.nested_opts(),
+ depth: self.depth + 1,
+ outer: None,
+ opacity_mul: 1.0,
+ collapse3d: None,
+ defer_dof: false,
+ top: false,
+ through: [None; MAX_THROUGH],
+ through_lost: false,
+ ..*self
+ }
+ }
+
+ /// A precomp layer's nested comp for an accelerator to render resident (no CPU render and
+ /// upload of the nested frame): the renderer one level down, the comp, its time and the
+ /// buffer scale, exactly as [`Self::layer_source`]'s comp branch would render it. `None`
+ /// when that branch does more (composition proxy, Essential Properties overrides, frame
+ /// blending, recursion) or draws nothing (outside the nested comp's span): use the CPU path.
+ pub fn precomp_source(&self, ctx: &EvalCtx, layer: &Layer) -> Option<(Renderer<'a>, ItemId, Tick, f64)> {
+ let LayerSource::Comp { item } = layer.source else { return None };
+ if layer.switches.adjustment || self.project.comp_contains(item, ctx.comp_id) {
+ return None;
+ }
+ let nc = self.project.comp(item)?;
+ let lt = ctx.nested_time(layer);
+ if self.content_times(ctx, layer).is_some() {
+ return None;
+ }
+ if !nc.covers(lt) || self.proxy_for(item).is_some() || !essential_overrides(ctx, layer).is_empty() || frame_blend_mode(ctx, layer) != FrameBlend::Off {
+ return None;
+ }
+ let s = self.opts.scale;
+ let bs = if s < 1.0 && nc.preserve_resolution { 1.0 } else { s };
+ let base = self.nested_through(layer);
+ Some((Renderer { opts: RenderOpts { scale: bs, ..base.opts }, ..base }, item, lt, bs))
+ }
+
+ /// The nested comp of a precomp layer whose transformations collapse into this comp: the
+ /// Collapse Transformations switch is on and the layer has no masks, effects or layer
+ /// styles (those force a flattened render of the precomp, as in After Effects).
+ pub fn collapsed(&self, ctx: &EvalCtx, layer: &Layer) -> Option<ItemId> {
+ if !layer.switches.collapse || layer.switches.adjustment || self.depth > 12 {
+ return None;
+ }
+ let LayerSource::Comp { item } = &layer.source else { return None };
+ if self.project.comp_contains(*item, ctx.comp_id) || self.project.comp(*item).is_none() {
+ return None;
+ }
+ if layer.masks().is_some_and(|m| !m.children.is_empty()) {
+ return None;
+ }
+ if layer.switches.effects && layer.effects().is_some_and(|fx| fx.groups().any(|g| g.enabled)) {
+ return None;
+ }
+ if styles::active(ctx, layer) {
+ return None;
+ }
+ // Instance overrides (Essential Properties) need the nested comp rendered on its own.
+ if !effectcraft_project::essential::overridden(layer).is_empty() {
+ return None;
+ }
+ Some(*item)
+ }
+
+ /// A renderer and context that draw a collapsed precomp's layers straight into this comp:
+ /// their transforms are concatenated with the precomp layer's (one resample, no
+ /// rasterisation at the precomp's bounds), their opacity multiplied by `opacity`, and their
+ /// 3D layers use this comp's camera and lights.
+ pub fn collapse_into(&self, ctx: &EvalCtx<'a>, layer: &'a Layer, item: ItemId, opacity: f32) -> Option<(Renderer<'a>, EvalCtx<'a>)> {
+ let nc = self.project.comp(item)?;
+ let t = ctx.nested_time(layer);
+ if !nc.covers(t) {
+ return None;
+ }
+ let nctx = EvalCtx { comp_id: item, comp: nc, time: t, ..*ctx };
+ let (l2c, _) = ctx.layer_to_comp(layer);
+ let outer = Some(self.outer.map_or(l2c, |o| o * l2c));
+ let world = ctx.world_matrix(layer);
+ let c3 = Collapse3d {
+ world: self.collapse3d.map_or(world, |c| c.world * world),
+ cam: three_d::compose::camera_for(self, ctx),
+ parent: self.collapse3d.map_or(*ctx, |c| c.parent),
+ };
+ // Motion blur follows the precomp layer's own motion too.
+ let link = Through { comp_id: ctx.comp_id, comp: ctx.comp, time: ctx.time, layer, blur: self.mb_on(ctx, layer) };
+ let mut through = self.through;
+ let slot = through.iter_mut().find(|t| t.is_none());
+ let through_lost = self.through_lost || slot.is_none();
+ if let Some(slot) = slot {
+ *slot = Some(link);
+ }
+ Some((
+ Renderer { opts: self.nested_opts(), depth: self.depth + 1, outer, opacity_mul: opacity, collapse3d: Some(c3), through, through_lost, ..*self },
+ nctx,
+ ))
+ }
+
+ pub(crate) fn opacity_mul(&self) -> f32 {
+ self.opacity_mul
+ }
+
+ /// Draw a collapsed 2D precomp layer: nested layers blend straight into `canvas` with their
+ /// own modes (Normal precomp, no matte); otherwise they are drawn into an isolated buffer
+ /// that then takes the precomp layer's track matte, Preserve Transparency and blend mode.
+ /// Returns the region left to re-quantise (nested layers drawn straight into `canvas`
+ /// quantise their own footprints).
+ pub(crate) fn draw_collapsed(&self, ctx: &EvalCtx<'a>, layer: &Layer, item: ItemId, canvas: &mut Image, blank: bool) -> Region {
+ let opacity = ctx.opacity(layer) as f32 * self.opacity_mul;
+ if opacity <= 0.0 {
+ return Region::Empty;
+ }
+ let matte = layer.track_matte.is_some_and(|tm| tm.layer != layer.id && ctx.comp.layer(tm.layer).is_some());
+ if layer.blend_mode == BlendMode::Normal && !matte && !layer.preserve_transparency {
+ if let Some((sub, nctx)) = self.collapse_into(ctx, layer, item, opacity) {
+ sub.draw_comp(&nctx, canvas, blank);
+ }
+ return Region::Empty;
+ }
+ let Some((sub, nctx)) = self.collapse_into(ctx, layer, item, 1.0) else { return Region::Empty };
+ let mut iso = Image::new(canvas.width, canvas.height);
+ sub.draw_comp(&nctx, &mut iso, true);
+ self.composite_iso(ctx, layer, iso, canvas, opacity);
+ Region::Full
+ }
+
+ /// Whether `layer`'s processed buffer (source → masks → effects) is cached and the same as
+ /// one frame earlier: drawing it from the layer cache (an accelerator uploads it once) beats
+ /// re-running its effects every frame.
+ pub fn layer_is_static(&self, ctx: &EvalCtx, layer: &Layer) -> bool {
+ if self.cache.is_none() {
+ return false;
+ }
+ let (scale, draft, blur) = (self.raster_scale(ctx, layer), self.opts.draft, self.mb_on(ctx, layer));
+ let prev = ctx.time - ctx.comp.frame_rate.frame_duration();
+ let now = cache::layer_key(ctx, layer, scale, draft, blur);
+ now.is_some() && now == cache::layer_key(&ctx.at(prev), layer, scale, draft, blur)
+ }
+
+ /// Rasterisation scale of a layer's source: the output scale, or — for text and shape layers,
+ /// which are always continuously rasterised (#390, #751), and Continuously Rasterize vector
+ /// footage — the output scale times the layer's on-screen scale (quarter-octave steps, rounded
+ /// up, so vector content is drawn at its final size and stays sharp when scaled up).
+ pub fn raster_scale(&self, ctx: &EvalCtx, layer: &Layer) -> f64 {
+ let s = self.opts.scale;
+ let continuous = match layer.source {
+ LayerSource::Text | LayerSource::Shape => true,
+ LayerSource::Footage { item } => {
+ layer.switches.collapse && matches!(self.project.item(item).map(|i| &i.kind), Some(ItemKind::Footage(f)) if is_vector_footage(f))
+ }
+ _ => false,
+ };
+ if !continuous {
+ return s;
+ }
+ let (l2c, _) = ctx.layer_to_comp(layer);
+ let m = self.outer.map_or(l2c, |o| o * l2c);
+ let a = layer.transform().map(|tr| ctx.v3(layer, tr, "anchor", [0.0; 3])).unwrap_or([0.0; 3]);
+ let p0 = m.apply(vec2(a[0], a[1]));
+ let px = m.apply(vec2(a[0] + 1.0, a[1]));
+ let py = m.apply(vec2(a[0], a[1] + 1.0));
+ let k = ((px.x - p0.x).hypot(px.y - p0.y)).max((py.x - p0.x).hypot(py.y - p0.y));
+ if !k.is_finite() || k <= 1e-6 {
+ return s;
+ }
+ // The step is rounded up past rounding noise only: an unscaled layer whose position isn't
+ // a whole number maps the unit vectors to lengths a hair over 1, which must stay 1 (#390:
+ // rounded up to 2^¼, unscaled text was drawn larger and resampled, softer).
+ let mut k = 2f64.powf((k.log2() * 4.0 - 1e-6).ceil() / 4.0).clamp(1.0 / 16.0, 64.0);
+ // Keep the buffer within about 16 million pixels.
+ if let Some(b) = content_bounds(ctx, layer) {
+ let area = ((b[2] - b[0]) * (b[3] - b[1])).max(1.0) * s * s;
+ k = k.min((16.0e6 / area).sqrt().max(1.0));
+ }
+ s * k
+ }
+
+ /// Draw a Wireframe-quality layer: its bounds as a one-pixel outline.
+ pub(crate) fn draw_wireframe(&self, ctx: &EvalCtx, layer: &Layer, canvas: &mut Image) {
+ for (x, y) in self.wireframe_pixels(ctx, layer, (canvas.width, canvas.height)) {
+ canvas.set(x, y, [1.0, 1.0, 1.0, 1.0]);
+ }
+ }
+
+ pub(crate) fn ctx(&self, comp_id: ItemId, comp: &'a Comp, t: Tick) -> EvalCtx<'a> {
+ EvalCtx { project: self.project, comp_id, comp, time: t, expr: self.expr, footage: Some(self.footage) }
+ }
+
+ /// This renderer with another accelerator (or none): the passes of
+ /// [`passes::in_passes`] render with the accelerator, its CPU fallback without.
+ pub fn with_accel(&self, accel: Option<&'a dyn Accelerator>) -> Renderer<'a> {
+ Renderer { accel, ..*self }
+ }
+
+ /// The accelerator to use for this render, if any (see [`Backend`]).
+ pub fn active_accel(&self) -> Option<&'a dyn Accelerator> {
+ let a = self.accel?;
+ match self.opts.backend {
+ Backend::Cpu => None,
+ Backend::Gpu => Some(a),
+ Backend::Auto => self.project.settings.gpu_acceleration.then_some(a),
+ }
+ }
+
+ /// Render a composition at comp time `t` (transparent background, comp size × scale).
+ /// Top-level frames go to the GPU when [`Self::active_accel`] is set and handles them.
+ pub fn comp_frame(&self, comp_id: ItemId, t: Tick) -> Image {
+ // Classic 3D runs composite on the GPU too (M12.7), so Auto sends 3D comps there as well;
+ // Auto renders each comp on whichever compositor measured faster ([`AutoPick`]).
+ if self.depth == 0
+ && let Some(a) = self.active_accel()
+ {
+ let auto = self.frame_auto(a, comp_id, false);
+ if auto.is_none_or(|(p, key)| p.choose(key)) {
+ let t0 = web_time::Instant::now();
+ if let Some(img) = a.comp_frame(self, comp_id, t) {
+ if let Some((p, key)) = auto {
+ p.record(key, true, t0.elapsed().as_secs_f64() * 1e3);
+ }
+ return img;
+ }
+ if let Some((p, key)) = auto {
+ p.declined(key);
+ }
+ }
+ let t0 = web_time::Instant::now();
+ let img = self.comp_frame_cpu(comp_id, t);
+ if let Some((p, key)) = auto {
+ p.record(key, false, t0.elapsed().as_secs_f64() * 1e3);
+ }
+ return img;
+ }
+ self.comp_frame_cpu(comp_id, t)
+ }
+
+ /// The Auto timing history and key for a top-level frame of `comp` (`None` unless the
+ /// backend is [`Backend::Auto`] and the accelerator keeps history).
+ pub fn frame_auto(&self, a: &'a dyn Accelerator, comp: ItemId, display: bool) -> Option<(&'a AutoPick, AutoKey)> {
+ if self.opts.backend != Backend::Auto || self.opts.roi.is_some() {
+ return None;
+ }
+ Some((a.auto_pick()?, AutoKey::new(comp, self.opts.scale, display)))
+ }
+
+ /// [`Self::comp_frame`] on the CPU compositor only.
+ pub fn comp_frame_cpu(&self, comp_id: ItemId, t: Tick) -> Image {
+ let Some(comp) = self.project.comp(comp_id) else { return Image::new(1, 1) };
+ let s = self.opts.scale;
+ let (w, h) = frame_size(comp.width, comp.height, s);
+ // Region of interest on a comp with 3D layers: render the frame and crop it. A region
+ // reaching past the comp frame (the Extended Viewer) renders Classic 3D natively — the
+ // planes project through the offset camera — and Advanced 3D as the frame, padded.
+ if self.depth == 0
+ && let Some(r) = self.opts.roi
+ && comp.has_3d()
+ && (roi_inside(r, comp.width, comp.height) || comp.renderer == effectcraft_project::Renderer::Advanced3D)
+ {
+ let full = Renderer { opts: RenderOpts { roi: None, ..self.opts }, ..*self }.comp_frame(comp_id, t);
+ let (x0, y0) = ((r[0] * s).round() as i64, (r[1] * s).round() as i64);
+ let (rw, rh) = (((r[2] * s).round() as u32).max(1), ((r[3] * s).round() as u32).max(1));
+ let mut out = Image::new(rw, rh);
+ for y in 0..rh as i64 {
+ let sy = y + y0;
+ if sy < 0 || sy >= full.height as i64 {
+ continue;
+ }
+ for x in 0..rw as i64 {
+ let sx = x + x0;
+ if sx >= 0 && sx < full.width as i64 {
+ out.data[(y * rw as i64 + x) as usize] = full.data[(sy * full.width as i64 + sx) as usize];
+ }
+ }
+ }
+ return out;
+ }
+ let (w, h) = match self.roi_offset() {
+ Some((_, _, rw, rh)) => (rw, rh),
+ None => (w, h),
+ };
+ let mut canvas = Image::new(w, h);
+ if self.depth > 16 {
+ return canvas;
+ }
+ let ctx = self.ctx(comp_id, comp, t);
+ self.draw_comp(&ctx, &mut canvas, true);
+ // The canvas is already quantised after every layer; only re-encoding changes it.
+ if let Some(c) = self.pipe.from_blend() {
+ color::convert(&mut canvas, &c);
+ self.pipe.quantize(&mut canvas);
+ }
+ // The top-level comp leaves the working space for the (sRGB) display / output.
+ if self.depth == 0
+ && let Some(c) = self.pipe.output()
+ {
+ color::convert(&mut canvas, &c);
+ self.pipe.quantize(&mut canvas);
+ }
+ if self.depth == 0
+ && let Some((lin, mode, enc)) = self.pipe.output_hdr()
+ {
+ color::output_hdr(&mut canvas, lin, mode, enc);
+ self.pipe.quantize(&mut canvas);
+ }
+ canvas
+ }
+
+ /// Draw a comp's layers (bottom to top) into `canvas` (blending space).
+ /// `blank`: the canvas is fully transparent (lets the first layer skip re-quantising).
+ fn draw_comp(&self, ctx: &EvalCtx<'a>, canvas: &mut Image, mut blank: bool) {
+ // Bottom-to-top, with runs of consecutive 3D layers depth-sorted (farthest first).
+ let visible = self.visible_layers(ctx);
+ let mut i = 0;
+ while i < visible.len() {
+ if visible[i].is_3d() {
+ let mut j = i;
+ while j < visible.len() && visible[j].is_3d() {
+ j += 1;
+ }
+ three_d::compose::draw_run(self, ctx, &visible[i..j], canvas);
+ i = j;
+ self.pipe.quantize(canvas);
+ blank = false;
+ } else {
+ let changed = match self.collapsed(ctx, visible[i]) {
+ Some(item) => self.draw_collapsed(ctx, visible[i], item, canvas, blank),
+ None => self.draw_layer(ctx, visible[i], canvas, blank),
+ };
+ i += 1;
+ // 8/16 bpc: the comp is an integer buffer after every layer (only the pixels the
+ // layer touched need re-quantising).
+ self.pipe.quantize_region(canvas, changed);
+ blank = false;
+ }
+ }
+ }
+
+ /// Evaluate an effect instance's parameters.
+ fn effect_params(&self, ctx: &EvalCtx, layer: &Layer, g: &effectcraft_project::PropGroup) -> Params {
+ // Nested groups (Paint strokes, Puppet meshes and pins) are flattened too.
+ effectcraft_effects::flatten_params(g, &mut |pr| ctx.value(layer, pr))
+ }
+
+ pub(crate) fn apply_effects(&self, ctx: &EvalCtx, layer: &Layer, buf: Buf, adjustment: bool) -> Buf {
+ self.apply_effects_timed(ctx, layer, buf, adjustment, usize::MAX, None)
+ }
+
+ /// Run the first `limit` effects of the layer's stack (by position; disabled ones count) on
+ /// `buf` (layer space, or the comp below for an adjustment layer).
+ fn apply_effects_timed(&self, ctx: &EvalCtx, layer: &Layer, mut buf: Buf, adjustment: bool, limit: usize, timing: Option<&mut Vec<(String, f64)>>) -> Buf {
+ // The comp below an adjustment layer is not in its layer space: it stays as it is.
+ let origin = if adjustment { [0.0; 2] } else { ctx.effect_bounds(layer).1 };
+ buf.rebase(origin);
+ let mut out = self.effect_space_stack(ctx, layer, buf, adjustment, limit, timing, origin);
+ out.rebase([-origin[0], -origin[1]]);
+ out
+ }
+
+ /// [`Renderer::apply_effects_timed`] on a buffer already in effect space (measured from
+ /// `origin`, in layer coordinates); the result stays in effect space.
+ #[allow(clippy::too_many_arguments)]
+ fn effect_space_stack(
+ &self,
+ ctx: &EvalCtx,
+ layer: &Layer,
+ buf: Buf,
+ adjustment: bool,
+ limit: usize,
+ timing: Option<&mut Vec<(String, f64)>>,
+ origin: [f64; 2],
+ ) -> Buf {
+ let mut t = CpuFx { accel: self.active_accel(), levels: self.pipe.levels, buf: Some(buf) };
+ self.run_effect_stack(ctx, layer, adjustment, limit, timing, origin, &mut t);
+ t.buf.unwrap_or_else(|| Buf { img: Image::new(1, 1), offset: [0.0; 2], scale: self.opts.scale })
+ }
+
+ /// Run the layer's video effect stack on `target` (in effect space, measured from `origin`
+ /// in layer coordinates): runs of GPU-capable effects go to [`FxTarget::gpu`] (when an
+ /// accelerator is active and supports them), the rest to [`FxTarget::cpu`] one by one
+ /// (quantised to the bit depth after each).
+ #[allow(clippy::too_many_arguments)]
+ pub(crate) fn run_effect_stack(
+ &self,
+ ctx: &EvalCtx,
+ layer: &Layer,
+ adjustment: bool,
+ limit: usize,
+ mut timing: Option<&mut Vec<(String, f64)>>,
+ origin: [f64; 2],
+ target: &mut dyn FxTarget,
+ ) {
+ if !layer.switches.effects {
+ return;
+ }
+ let Some(fx) = layer.effects() else { return };
+ let lt = layer.layer_time(ctx.time);
+ let layer_size = ctx.effect_bounds(layer).0;
+ // #659: an authored layer's buffer spans only its painted content while the stack works
+ // on the layer's whole region (`layer_size`): give the buffer the room a sized source
+ // already has, so tiling or displacement can place pixels outside the content instead
+ // of losing them at its edge. Only when something will actually run, and not for an
+ // adjustment layer, whose buffer is the comp below and already spans it.
+ if !adjustment
+ && fx.groups().any(|g| g.enabled && matches!(&g.kind, GroupKind::Effect { effect } if effectcraft_effects::find(effect).is_some_and(|s| !effectcraft_effects::audio_fx::is_audio_effect(s.id)))) {
+ target.cover(layer_size);
+ }
+ let mut mask_shapes = masks::shapes(ctx, layer);
+ if origin != [0.0; 2] {
+ for q in mask_shapes.iter_mut().flat_map(|m| m.points.iter_mut()) {
+ *q = [q[0] - origin[0], q[1] - origin[1]];
+ }
+ }
+ // Capture once, before preceding effects can expand or replace the input. An
+ // adjustment stack's original is the comp below, not its solid source.
+ let needs_original =
+ fx.groups().take(limit).any(|g| g.enabled && matches!(&g.kind, GroupKind::Effect { effect } if effect == "ec.channel.cccomposite"));
+ let mut original = None;
+ if needs_original {
+ target.cpu(&mut |buf| {
+ original = Some(buf.clone());
+ buf
+ });
+ }
+ let host = FxHost { r: self, ctx, layer, origin, index: 0, original: original.as_ref() };
+ let env = EffectEnv {
+ masks: &mask_shapes,
+ host: Some(&host),
+ comp_time: ctx.time.seconds(),
+ frame_rate: ctx.comp.frame_rate.as_f64(),
+ effect_index: 0,
+ working_space: self.pipe.space,
+ working_linear: self.pipe.linear,
+ float_depth: self.pipe.levels.is_none(),
+ shutter: self.mb_on(ctx, layer).then_some((ctx.comp.shutter_angle, ctx.comp.shutter_phase, ctx.comp.motion_blur_samples)),
+ };
+ // Video effects in stack order (index, group, spec); disabled and audio effects skipped.
+ let stack: Vec<(usize, &effectcraft_project::PropGroup, &'static effectcraft_effects::EffectSpec)> = fx
+ .groups()
+ .enumerate()
+ .take_while(|(i, _)| *i < limit)
+ .filter(|(_, g)| g.enabled)
+ .filter_map(|(i, g)| match &g.kind {
+ GroupKind::Effect { effect } => effectcraft_effects::find(effect).map(|s| (i, g, s)),
+ _ => None,
+ })
+ .filter(|(_, _, s)| !effectcraft_effects::audio_fx::is_audio_effect(s.id))
+ .collect();
+ let accel = self.active_accel();
+ let mut k = 0;
+ while k < stack.len() {
+ let (i, g, spec) = stack[k];
+ // A run of GPU effects goes to the accelerator in one go.
+ if let Some(a) = accel
+ && spec.gpu
+ && a.supports_effect(spec.id)
+ {
+ let run: Vec<_> = stack[k..].iter().take_while(|(_, _, s)| s.gpu && a.supports_effect(s.id)).collect();
+ let params: Vec<Params> = run.iter().map(|(_, g, _)| self.effect_params(ctx, layer, g)).collect();
+ let hosts: Vec<_> = run.iter().map(|(i, _, _)| FxHost { index: *i, ..host }).collect();
+ let steps: Vec<FxStep> = run
+ .iter()
+ .zip(&params)
+ .zip(&hosts)
+ .map(|(((i, g, s), params), host)| FxStep {
+ spec: s,
+ ctx: EffectCtx {
+ params,
+ time: lt.seconds(),
+ layer_size,
+ seed: g.uid as u32,
+ adjustment,
+ env: EffectEnv { host: Some(host), effect_index: *i, ..env },
+ },
+ })
+ .collect();
+ let t0 = web_time::Instant::now();
+ if target.gpu(&steps) {
+ if let Some(v) = timing.as_deref_mut() {
+ let ms = t0.elapsed().as_secs_f64() * 1e3 / run.len() as f64;
+ v.extend(run.iter().map(|(_, _, s)| (format!("{} (gpu)", s.id), ms)));
+ }
+ k += run.len();
+ continue;
+ }
+ }
+ k += 1;
+ let params = self.effect_params(ctx, layer, g);
+ let host = FxHost { index: i, ..host };
+ let env = EffectEnv { host: Some(&host), effect_index: i, ..env };
+ let ectx = EffectCtx { params: &params, time: lt.seconds(), layer_size, seed: g.uid as u32, adjustment, env };
+ let t0 = web_time::Instant::now();
+ target.cpu(&mut |buf| {
+ let mut buf = effectcraft_effects::apply(spec, &ectx, buf);
+ // 8/16 bpc effects write integer pixels.
+ self.pipe.quantize(&mut buf.img);
+ buf
+ });
+ if let Some(v) = timing.as_deref_mut() {
+ v.push((spec.id.to_string(), t0.elapsed().as_secs_f64() * 1e3));
+ }
+ }
+ }
+
+ /// Source pixels of a layer in layer space (before masks/effects).
+ pub(crate) fn source(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Buf> {
+ let s = self.opts.scale;
+ match &layer.source {
+ LayerSource::Solid { item } => {
+ let ItemKind::Solid(sol) = &self.project.item(*item)?.kind else { return None };
+ let w = ((sol.width as f64 * s).ceil() as u32).max(1);
+ let h = ((sol.height as f64 * s).ceil() as u32).max(1);
+ if layer.switches.adjustment {
+ return Some(Buf { img: Image::filled(w, h, [1.0; 4]), offset: [0.0; 2], scale: s });
+ }
+ let mut c = sol.color;
+ if let Some(conv) = self.pipe.authored_in() {
+ c = conv.apply(c);
+ }
+ let px = self.pipe.quantize_px([c[0], c[1], c[2], 1.0]);
+ Some(Buf { img: Image::filled(w, h, px), offset: [0.0; 2], scale: s })
+ }
+ LayerSource::Comp { item } => {
+ if self.project.comp_contains(*item, ctx.comp_id) {
+ return None;
+ }
+ // A composition proxy (a rendered still or movie) stands in for the comp.
+ // Nothing before the nested comp starts or after it ends.
+ let lt = ctx.nested_time(layer);
+ if !self.project.comp(*item).is_some_and(|nc| nc.covers(lt)) {
+ return None;
+ }
+ if let Some(pf) = self.proxy_for(*item)
+ && let Some(nc) = self.project.comp(*item)
+ {
+ let img = self.footage.frame_with(*item, pf, lt, None, self.pipe.float_encoding())?;
+ return Some(self.footage_buf(&img, pf, nc.width, nc.height));
+ }
+ // Essential Properties overrides render the nested comp with this instance's
+ // values.
+ let ov = essential_overrides(ctx, layer);
+ let tmp = if ov.is_empty() { None } else { effectcraft_project::essential::with_overrides(self.project, *item, &ov) };
+ // Preserve resolution when nested: drawn at full size even when this comp renders
+ // smaller (the buffer's scale places it).
+ let full = s < 1.0 && self.project.comp(*item).is_some_and(|nc| nc.preserve_resolution);
+ let bs = if full { 1.0 } else { s };
+ let base = self.nested_through(layer);
+ let base = Renderer { opts: RenderOpts { scale: bs, ..base.opts }, ..base };
+ let sub = match &tmp {
+ Some(p) => Renderer { project: p, ..base },
+ None => base,
+ };
+ // Frame blending between the nested comp's frames (time-stretched/remapped).
+ let mode = frame_blend_mode(ctx, layer);
+ if mode != FrameBlend::Off
+ && let Some(nc) = self.project.comp(*item)
+ {
+ let (i, w) = frame_position(lt, nc.frame_rate);
+ if w > 1e-6 {
+ let a = sub.comp_frame(*item, nc.frame_rate.tick_of(i));
+ let b = sub.comp_frame(*item, nc.frame_rate.tick_of(i + 1));
+ return Some(Buf { img: blend_frames(mode, &a, &b, w as f32), offset: [0.0; 2], scale: bs });
+ }
+ }
+ Some(Buf { img: sub.comp_frame(*item, lt), offset: [0.0; 2], scale: bs })
+ }
+ LayerSource::Footage { item } => {
+ let it = self.project.item(*item)?;
+ let ItemKind::Footage(f) = &it.kind else { return None };
+ if !f.has_video {
+ return None;
+ }
+ // Continuously rasterised vector footage: drawn at the on-screen scale.
+ if layer.switches.collapse && is_vector_footage(f) {
+ let k = self.raster_scale(ctx, layer);
+ if let Some(img) = self.footage.vector_frame(*item, f, k) {
+ let mut buf = Buf { img: (*img).clone(), offset: [0.0; 2], scale: k };
+ if let Some(c) = self.pipe.media_in(f) {
+ color::convert(&mut buf.img, &c);
+ }
+ return Some(buf);
+ }
+ }
+ let lt = ctx.source_time(layer);
+ // The proxy is decoded instead, at its own size, and fills the footage's frame.
+ let proxy = self.proxy_for(*item);
+ let pf = proxy.unwrap_or(f);
+ let size = self.reduced_size(f.width, f.height).filter(|_| proxy.is_none());
+ let img = self.footage_frame(ctx, layer, *item, pf, lt, size)?;
+ Some(self.footage_buf(&img, pf, f.width, f.height))
+ }
+ LayerSource::Text => Some(self.authored(text::render(ctx, layer, self.raster_scale(ctx, layer)))),
+ LayerSource::Shape => layer.props.sub("contents").map(|c| self.authored(shapes::render(ctx, layer, c, self.raster_scale(ctx, layer)))),
+ _ => None,
+ }
+ }
+
+ /// The proxy footage used for `item` under this render's Proxy Use, if any.
+ pub fn proxy_for(&self, item: ItemId) -> Option<&'a Footage> {
+ let it = self.project.item(item)?;
+ let px = it.proxy.as_deref()?;
+ (self.opts.proxy.uses(matches!(it.kind, ItemKind::Comp(_)), px.enabled) && px.footage.has_video).then_some(&px.footage)
+ }
+
+ /// A decoded frame of `f` as a layer buffer covering `w`×`h` layer pixels (the footage's
+ /// nominal size; proxies are scaled up to it), converted from its colour profile.
+ fn footage_buf(&self, img: &Image, f: &Footage, w: u32, h: u32) -> Buf {
+ let s = self.opts.scale;
+ let k = if img.width > 0 { w.max(1) as f64 / img.width as f64 } else { 1.0 };
+ // Keep native pixels when downsampling is small; resample otherwise.
+ let mut buf = match self.reduced_size(w, h) {
+ // The source resampled it already (`FootageSource::frame_at_size`).
+ Some(size) if (img.width, img.height) == size => Buf { img: img.clone(), offset: [0.0; 2], scale: s },
+ Some((rw, rh)) if k <= 1.0 + 1e-9 => Buf { img: effectcraft_raster::resample(img, rw, rh), offset: [0.0; 2], scale: s },
+ _ => Buf { img: img.clone(), offset: [0.0; 2], scale: 1.0 / k },
+ };
+ if let Some(c) = self.pipe.media_in(f) {
+ color::convert(&mut buf.img, &c);
+ }
+ buf
+ }
+
+ /// The size of `w` × `h` layer pixels in this render when it is reduced enough that footage
+ /// is resampled to it (below 3/4 scale).
+ fn reduced_size(&self, w: u32, h: u32) -> Option<(u32, u32)> {
+ let s = self.opts.scale;
+ (s < 0.75).then(|| (((w as f64 * s).round() as u32).max(1), ((h as f64 * s).round() as u32).max(1)))
+ }
+
+ /// Authored colours into the working space (linear working spaces).
+ fn authored(&self, mut buf: Buf) -> Buf {
+ if let Some(c) = self.pipe.authored_in() {
+ color::convert(&mut buf.img, &c);
+ }
+ buf
+ }
+
+ /// A footage frame at source time `t`, frame-blended between the two nearest source frames
+ /// when the layer's Frame Blending switch (and the comp's Enable Frame Blending) is on and
+ /// `t` falls between frames (footage rate ≠ comp rate, time stretch, time remapping).
+ /// `size`: a plain frame may come resampled to it ([`FootageSource::frame_at_size`]).
+ fn footage_frame(&self, ctx: &EvalCtx, layer: &Layer, item: ItemId, f: &Footage, t: Tick, size: Option<(u32, u32)>) -> Option<Arc<Image>> {
+ // Interpret Footage ▸ Separate Fields: each field is a frame at twice the rate.
+ if f.fields != effectcraft_project::FieldOrder::Off && matches!(f.kind, FootageKind::Video | FootageKind::Sequence) {
+ let field_rate = FrameRate::new(f.frame_rate.num * 2, f.frame_rate.den);
+ let i = field_rate.frame_at(t).max(0);
+ let img = self.footage.frame_with(item, f, f.frame_rate.tick_of(i / 2), None, self.pipe.float_curve(f))?;
+ let dominant_upper = f.fields == effectcraft_project::FieldOrder::UpperFirst;
+ // Upper field = even lines (0, 2, …).
+ let parity = if (i % 2 == 0) == dominant_upper { 0 } else { 1 };
+ return Some(Arc::new(interpret_pixels(&field_frame(&img, parity), f, self.pipe.linear_footage_space(f))));
+ }
+ // Interpretation is per pixel but not linear: it runs on the frame before resampling.
+ let size = size.filter(|_| !(f.invert_alpha || f.linear_light_applies()));
+ let img = self.footage_frame_raw(ctx, layer, item, f, t, size)?;
+ if f.invert_alpha || f.linear_light_applies() { Some(Arc::new(interpret_pixels(&img, f, self.pipe.linear_footage_space(f)))) } else { Some(img) }
+ }
+
+ fn footage_frame_raw(&self, ctx: &EvalCtx, layer: &Layer, item: ItemId, f: &Footage, t: Tick, size: Option<(u32, u32)>) -> Option<Arc<Image>> {
+ let mode = frame_blend_mode(ctx, layer);
+ let float = self.pipe.float_curve(f);
+ if mode != FrameBlend::Off && matches!(f.kind, FootageKind::Video | FootageKind::Sequence) {
+ let (i, w) = frame_position(t, f.frame_rate);
+ if w > 1e-6 {
+ // Blended frames are cached (Pixel Motion is expensive).
+ let key = self.cache.map(|_| {
+ use std::hash::{Hash, Hasher};
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ (0x00f8_a3e5_u64, item, i, (w as f32).to_bits(), mode as u8, f.frame_rate.num, f.frame_rate.den, &f.path, float).hash(&mut h);
+ h.finish()
+ });
+ if let (Some(c), Some(k)) = (self.cache, key)
+ && let Some(b) = c.get(k)
+ {
+ return Some(Arc::new(b.img.clone()));
+ }
+ let a = self.footage.frame_with(item, f, f.frame_rate.tick_of(i), None, float);
+ let b = self.footage.frame_with(item, f, f.frame_rate.tick_of(i + 1), None, float);
+ if let (Some(a), Some(b)) = (a, b) {
+ let img = blend_frames(mode, &a, &b, w as f32);
+ if let (Some(c), Some(k)) = (self.cache_to_keep(), key) {
+ c.insert(k, Arc::new(Buf { img: img.clone(), offset: [0.0; 2], scale: 1.0 }));
+ }
+ return Some(Arc::new(img));
+ }
+ }
+ }
+ self.footage.frame_with(item, f, t, size, float)
+ }
+
+ /// Source → masks, clamped/quantised to the project depth.
+ fn masked_source(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Buf> {
+ let mut buf = match self.content_times(ctx, layer) {
+ Some(times) => self.blurred_source(ctx, layer, &times)?,
+ None => self.source(ctx, layer)?,
+ };
+ // A solid is filled with a quantised colour: only masks can take it off the grid.
+ let solid = matches!(layer.source, LayerSource::Solid { .. });
+ if masks::apply(ctx, layer, &mut buf, self.mask_blur(ctx, layer)) || !solid {
+ self.pipe.quantize(&mut buf.img);
+ }
+ Some(buf)
+ }
+
+ /// Fully processed layer buffer (source → masks → effects → layer styles, flattened).
+ /// Served from the layer cache when the layer's content key matches.
+ pub fn layer_buf(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Arc<Buf>> {
+ self.layer_buf_keyed(ctx, layer).map(|(b, _)| b)
+ }
+
+ /// [`Self::layer_buf`] in the blending space (linear with Blend Colors Using 1.0 Gamma).
+ pub fn blend_layer_buf(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Arc<Buf>> {
+ let (b, k) = self.layer_buf_keyed(ctx, layer)?;
+ Some(self.to_blend(b, k))
+ }
+
+ /// A buffer converted to the blending space (cached under a key derived from `key`).
+ pub(crate) fn to_blend(&self, b: Arc<Buf>, key: Option<u64>) -> Arc<Buf> {
+ let Some(c) = self.pipe.to_blend() else { return b };
+ let key = key.map(|k| cache::derive(k, 0x1ea7));
+ if let (Some(cache), Some(k)) = (self.cache, key)
+ && let Some(x) = cache.get(k)
+ {
+ return x;
+ }
+ let mut nb = (*b).clone();
+ color::convert(&mut nb.img, &c);
+ let nb = Arc::new(nb);
+ // The buffer the cache keeps (another worker's, if it kept one first).
+ match (self.cache_to_keep(), key) {
+ (Some(cache), Some(k)) => cache.insert(k, nb),
+ _ => nb,
+ }
+ }
+
+ fn layer_buf_keyed(&self, ctx: &EvalCtx, layer: &Layer) -> Option<(Arc<Buf>, Option<u64>)> {
+ let st = self.styled(ctx, layer, None)?;
+ if st.passes.is_empty() {
+ return Some((st.body, st.key));
+ }
+ let key = st.key.map(|k| cache::derive(k, 0xf1a7));
+ if let (Some(c), Some(k)) = (self.cache, key)
+ && let Some(b) = c.get(k)
+ {
+ return Some((b, key));
+ }
+ let flat = Arc::new(styles::Styled { passes: st.passes.iter().map(|(b, m)| ((**b).clone(), *m)).collect(), body: (*st.body).clone() }.flatten());
+ // The buffer the cache keeps (another worker's, if it kept one first).
+ let flat = match (self.cache_to_keep(), key) {
+ (Some(c), Some(k)) => c.insert(k, flat),
+ _ => flat,
+ };
+ Some((flat, key))
+ }
+
+ /// A layer's source pixels at the context time, before masks, effects and the transform
+ /// (what the motion tracker analyses, like After Effects' Layer panel). `None` for layers
+ /// without pixels.
+ pub fn layer_source(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Buf> {
+ self.source(ctx, layer)
+ }
+
++ /// A 3D model or primitive layer rendered on its own, through the comp's camera: what an
++ /// effect layer parameter reads when it references one, as After Effects, which renders 3D
++ /// layers through the active camera. The comp's pixels at this render's scale; the layer's
++ /// blend mode, track matte and video switch don't apply (a source read, not a composite —
++ /// the solo clone of a 3D track matte, see `three_d::adv`).
++ pub(crate) fn solo_3d(&self, ctx: &EvalCtx, layer: &Layer) -> Buf {
++ let s = self.opts.scale;
++ let w = ((ctx.comp.width as f64 * s).ceil() as u32).max(1);
++ let h = ((ctx.comp.height as f64 * s).ceil() as u32).max(1);
++ let mut canvas = Image::new(w, h);
++ // Outside the layer's in/out points there is nothing to read: the copy is transparent
++ // there, like any other layer reference (the 3D pipelines don't gate on the range).
++ if !layer.is_active_at(ctx.time) {
++ return Buf { img: canvas, offset: [0.0; 2], scale: s };
++ }
++ let mut solo = layer.clone();
++ solo.track_matte = None;
++ solo.blend_mode = effectcraft_color::BlendMode::Normal;
++ solo.preserve_transparency = false;
++ solo.switches.video = true;
++ three_d::compose::draw_run(self, ctx, &[&solo], &mut canvas);
++ Buf { img: canvas, offset: [0.0; 2], scale: s }
++ }
++
+ /// Layer pixels after source → masks → effects (no layer styles).
+ pub fn content_buf(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Arc<Buf>> {
+ self.content_buf_timed(ctx, layer, None).map(|(b, _)| b)
+ }
+
+ pub(crate) fn content_buf_timed(&self, ctx: &EvalCtx, layer: &Layer, mut timing: Option<&mut LayerTiming>) -> Option<(Arc<Buf>, Option<u64>)> {
+ let key = self.cache.and_then(|_| cache::layer_key(ctx, layer, self.raster_scale(ctx, layer), self.opts.draft, self.mb_on(ctx, layer)));
+ let key = self.content_key(ctx, layer, key);
+ if let (Some(c), Some(k)) = (self.cache, key)
+ && let Some(b) = c.get(k)
+ {
+ if let Some(t) = timing.as_deref_mut() {
+ t.cached = true;
+ }
+ return Some((b, key));
+ }
+ let buf = self.masked_source(ctx, layer)?;
+ let buf = Arc::new(self.apply_effects_timed(ctx, layer, buf, false, usize::MAX, timing.map(|t| &mut t.effects)));
+ // The buffer the cache keeps (another worker's, if it kept one first).
+ let buf = match (self.cache_to_keep(), key) {
+ (Some(c), Some(k)) => c.insert(k, buf),
+ _ => buf,
+ };
+ Some((buf, key))
+ }
+
+ /// A layer's input at the context time: source → masks → its first `effects` effects
+ /// (what Time effects read at neighbouring times), in effect space (see [`effect_bounds`]):
+ /// what effect `effects` sees. Served from / stored in the layer cache under its own key,
+ /// so scrubbing reuses frames rendered for earlier output frames.
+ pub fn layer_input(&self, ctx: &EvalCtx, layer: &Layer, effects: usize) -> Option<Arc<Buf>> {
+ let key = self.cache.and_then(|_| cache::input_key(ctx, layer, self.raster_scale(ctx, layer), self.opts.draft, self.mb_on(ctx, layer), effects));
+ let key = self.content_key(ctx, layer, key);
+ if let (Some(c), Some(k)) = (self.cache, key)
+ && let Some(b) = c.get(k)
+ {
+ return Some(b);
+ }
+ let mut buf = self.masked_source(ctx, layer)?;
+ let origin = ctx.effect_bounds(layer).1;
+ buf.rebase(origin);
+ if effects > 0 {
+ buf = self.effect_space_stack(ctx, layer, buf, false, effects, None, origin);
+ }
+ let buf = Arc::new(buf);
+ // The buffer the cache keeps (another worker's, if it kept one first).
+ let buf = match (self.cache_to_keep(), key) {
+ (Some(c), Some(k)) => c.insert(k, buf),
+ _ => buf,
+ };
+ Some(buf)
+ }
+ }