Skip to content

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

Merge branch 'worktree-agent-a022a00e662ea8d21'

Brandon Thomas1e8768ad1877
diff --cc crates/effects/src/lib.rs
index efe5ae3e8,0355bd781..6b8b7a97b
--- a/crates/effects/src/lib.rs
+++ b/crates/effects/src/lib.rs
@@@ -222,26 -303,6 +303,31 @@@ pub fn instantiate(spec: &EffectSpec, i
g
}
+/// Effects whose output depends on [`EffectCtx::time`] directly (not only through animated
+/// parameters). The renderer's layer cache folds the layer time into the key for these.
+/// The `time_dependence_is_declared` test checks the list against every registered effect.
+pub const TIME_DEPENDENT: &[&str] = &[
+ "ec.distort.wavewarp",
+ "ec.distort.ripple",
+ "ec.generate.radiowaves",
+ "ec.stylize.scatter",
+ "ec.stylize.strobe",
+ "ec.noise.noise",
+ "ec.noise.addgrain",
+ "ec.noise.noisealpha",
+ "ec.noise.noisehlsauto",
++ "ec.obsolete.lightning",
++ "ec.text.timecode",
++ "ec.text.numbers",
+];
+
+/// See [`TIME_DEPENDENT`].
+pub fn is_time_dependent(id: &str) -> bool {
- TIME_DEPENDENT.contains(&id)
++ // Simulations replay from layer time 0, so every frame differs even when the defaults
++ // happen to look static at the test's two sample times.
++ id.starts_with("ec.sim.") || TIME_DEPENDENT.contains(&id)
+}
+
/// Run an effect on a buffer.
pub fn apply(spec: &EffectSpec, ctx: &EffectCtx, buf: Buf) -> Buf {
(spec.render)(ctx, buf)
@@@ -285,34 -375,4 +400,36 @@@ mod tests
assert!(out.img.data.iter().all(|p| p[3].is_finite() && p[3] >= -1e-4 && p[3] <= 1.0001), "{} alpha out of range", s.id);
}
}
+
+ /// Effects that read the clock must be listed in `TIME_DEPENDENT`, or the layer cache would
+ /// serve stale pixels. Render every effect at two times with default parameters (plus
+ /// "random…" switches turned on) and require identical output from unlisted ones.
+ #[test]
+ fn time_dependence_is_declared() {
+ let mut img = Image::new(40, 30);
+ for y in 0..30 {
+ for x in 0..40 {
+ let a = if (6..34).contains(&x) && (5..25).contains(&y) { 1.0 } else { 0.3 };
+ img.set(x, y, [((x * 7 + y * 3) % 11) as f32 / 11.0 * a, y as f32 / 30.0 * a, 0.4 * a, a]);
+ }
+ }
++ let mut missing = vec![];
+ for s in registry() {
+ let mut params = Params { values: s.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect() };
+ for (k, v) in params.values.iter_mut() {
+ if k.to_lowercase().contains("random") && matches!(v, Value::Bool(_)) {
+ *v = Value::Bool(true);
+ }
+ }
+ let run = |t: f64| {
- let ctx = EffectCtx { params: &params, time: t, layer_size: [40.0, 30.0], seed: 7, adjustment: false };
++ let ctx = EffectCtx { params: &params, time: t, layer_size: [40.0, 30.0], seed: 7, adjustment: false, env: Default::default() };
+ apply(s, &ctx, Buf { img: img.clone(), offset: [0.0, 0.0], scale: 1.0 }).img
+ };
+ let (a, b) = (run(0.0), run(1.37));
- if a != b {
- assert!(is_time_dependent(s.id), "{} depends on time but is not in TIME_DEPENDENT", s.id);
++ if a != b && !is_time_dependent(s.id) {
++ missing.push(s.id);
+ }
+ }
++ assert!(missing.is_empty(), "these depend on time but are not in TIME_DEPENDENT: {missing:?}");
+ }
}
diff --cc crates/render/src/audio.rs
index 1a9467b24,000000000..d7ae47788
mode 100644,000000..100644
--- a/crates/render/src/audio.rs
+++ b/crates/render/src/audio.rs
@@@ -1,203 -1,0 +1,203 @@@
+//! Audio mixdown of a composition: every audible footage layer (and, recursively, precomp layer)
+//! summed with its Audio Levels (dB, per channel), respecting in/out points, the Audio switch and
+//! solo. Levels are evaluated once per call (callers mix in short blocks, e.g. one video frame).
+//! Time-stretched layers are resampled nearest-sample; reversed (negative stretch) layers are
+//! silent for now.
+
+use effectcraft_project::{Comp, ItemId, ItemKind, Layer, LayerSource, Project};
+use effectcraft_time::{TICKS_PER_SECOND, Tick};
+
+use crate::{EvalCtx, ExprHost, FootageSource};
+
+const MAX_DEPTH: usize = 16;
+
+/// `frames` stereo sample frames of `comp`'s mix from comp time `start` at `rate` Hz,
+/// interleaved (L R L R …).
+pub fn mix_comp(project: &Project, footage: &dyn FootageSource, expr: Option<&dyn ExprHost>, comp: ItemId, start: Tick, frames: usize, rate: u32) -> Vec<f32> {
+ let mut out = vec![0.0f32; frames * 2];
+ mix_into(project, footage, expr, comp, start, rate, &mut out, 1.0, 1.0, 0);
+ out
+}
+
+/// Whether the comp has anything audible (footage with audio, or a precomp that has).
+pub fn comp_has_audio(project: &Project, comp: ItemId) -> bool {
+ fn walk(project: &Project, comp: ItemId, depth: usize) -> bool {
+ let Some(c) = project.comp(comp) else { return false };
+ depth < MAX_DEPTH
+ && c.layers.iter().any(|l| {
+ l.switches.audio
+ && match &l.source {
+ LayerSource::Footage { item } => {
+ matches!(project.item(*item).map(|i| &i.kind), Some(ItemKind::Footage(f)) if f.has_audio && !f.missing)
+ }
+ LayerSource::Comp { item } => walk(project, *item, depth + 1),
+ _ => false,
+ }
+ })
+ }
+ walk(project, comp, 0)
+}
+
+fn audible(project: &Project, l: &Layer) -> bool {
+ l.switches.audio
+ && match &l.source {
+ LayerSource::Footage { item } => matches!(project.item(*item).map(|i| &i.kind), Some(ItemKind::Footage(f)) if f.has_audio),
+ LayerSource::Comp { .. } => true,
+ _ => false,
+ }
+}
+
+fn db_to_gain(db: f64) -> f32 {
+ if db <= -96.0 { 0.0 } else { 10f64.powf(db / 20.0) as f32 }
+}
+
+fn units_ceil(t: Tick, rate: u32) -> i64 {
+ let n = t.0 as i128 * rate as i128;
+ let d = TICKS_PER_SECOND as i128;
+ (n.div_euclid(d) + i128::from(n.rem_euclid(d) != 0)) as i64
+}
+
+fn sample_tick(i: i64, rate: u32) -> Tick {
+ Tick(((i as i128 * TICKS_PER_SECOND as i128) / rate as i128) as i64)
+}
+
+#[allow(clippy::too_many_arguments)]
+fn mix_into(
+ project: &Project,
+ footage: &dyn FootageSource,
+ expr: Option<&dyn ExprHost>,
+ comp_id: ItemId,
+ start: Tick,
+ rate: u32,
+ out: &mut [f32],
+ gl: f32,
+ gr: f32,
+ depth: usize,
+) {
+ let Some(comp) = project.comp(comp_id) else { return };
+ if depth >= MAX_DEPTH || rate == 0 {
+ return;
+ }
+ let frames = out.len() / 2;
+ let any_solo = comp.layers.iter().any(|l| l.switches.solo && audible(project, l));
+ let s0 = start.to_units_floor(rate as i64);
+ for l in &comp.layers {
+ if !audible(project, l) || (any_solo && !l.switches.solo) || l.stretch <= 0.0 {
+ continue;
+ }
+ // Sample range of the block that falls inside the layer's [in, out).
+ let a = (units_ceil(l.in_point, rate) - s0).clamp(0, frames as i64) as usize;
+ let b = (units_ceil(l.out_point, rate) - s0).clamp(0, frames as i64) as usize;
+ if a >= b {
+ continue;
+ }
+ let t_a = sample_tick(s0 + a as i64, rate);
+ let (ll, lr) = levels(project, comp_id, comp, l, t_a, expr);
+ let (ll, lr) = (ll * gl, lr * gr);
+ if ll == 0.0 && lr == 0.0 {
+ continue;
+ }
+ let n = b - a;
+ let speed = 100.0 / l.stretch;
+ let src_n = ((n as f64 * speed).ceil() as usize).max(1);
+ let lt = l.layer_time(t_a);
+ let buf = match &l.source {
+ LayerSource::Footage { item } => match project.item(*item).map(|i| &i.kind) {
- Some(ItemKind::Footage(f)) => footage.audio(*item, f, lt, src_n, rate),
++ Some(ItemKind::Footage(f)) => footage.audio(*item, f, lt, src_n, rate).unwrap_or_else(|| vec![0.0; src_n * 2]),
+ _ => continue,
+ },
+ LayerSource::Comp { item } => {
+ if project.comp_contains(*item, comp_id) {
+ continue;
+ }
+ let mut sub = vec![0.0f32; src_n * 2];
+ mix_into(project, footage, expr, *item, lt, rate, &mut sub, 1.0, 1.0, depth + 1);
+ sub
+ }
+ _ => continue,
+ };
+ let same = (speed - 1.0).abs() < 1e-9;
+ for i in 0..n {
+ let j = if same { i } else { ((i as f64 * speed) as usize).min(src_n - 1) };
+ if j * 2 + 1 >= buf.len() {
+ break;
+ }
+ out[(a + i) * 2] += buf[j * 2] * ll;
+ out[(a + i) * 2 + 1] += buf[j * 2 + 1] * lr;
+ }
+ }
+}
+
+fn levels(project: &Project, comp_id: ItemId, comp: &Comp, l: &Layer, t: Tick, expr: Option<&dyn ExprHost>) -> (f32, f32) {
+ let Some(g) = l.props.sub("audio") else { return (1.0, 1.0) };
+ let mut ctx = EvalCtx::new(project, comp_id, comp, t);
+ ctx.expr = expr;
+ let [a, b] = ctx.v2(l, g, "levels", [0.0, 0.0]);
+ (db_to_gain(a), db_to_gain(b))
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::Arc;
+
+ use effectcraft_project::{Footage, FootageKind, build};
+ use effectcraft_time::FrameRate;
+
+ use super::*;
+ use crate::Image;
+
+ /// A 1 kHz-ish constant "tone": every sample is 0.25 (left) / -0.25 (right).
+ struct Dc;
+ impl FootageSource for Dc {
+ fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option<Arc<Image>> {
+ None
+ }
- fn audio(&self, _: ItemId, _: &Footage, start: Tick, frames: usize, _: u32) -> Vec<f32> {
- (0..frames).flat_map(|_| if start >= Tick::ZERO { [0.25, -0.25] } else { [0.0, 0.0] }).collect()
++ fn audio(&self, _: ItemId, _: &Footage, start: Tick, frames: usize, _: u32) -> Option<Vec<f32>> {
++ Some((0..frames).flat_map(|_| if start >= Tick::ZERO { [0.25, -0.25] } else { [0.0, 0.0] }).collect())
+ }
+ }
+
+ #[test]
+ fn mixes_layers_with_levels_and_in_out() {
+ let mut p = Project::default();
+ let f = Footage {
+ path: "x.wav".into(),
+ kind: FootageKind::Audio,
+ width: 0,
+ height: 0,
+ pixel_aspect: 1.0,
+ frame_rate: FrameRate::new(25, 1),
+ native_rate: None,
+ duration: Tick::from_seconds_f64(10.0),
+ has_video: false,
+ has_audio: true,
+ alpha: Default::default(),
+ premul_color: [0.0; 3],
+ loop_count: 1,
+ codec: String::new(),
+ missing: false,
+ sequence: vec![],
+ };
+ let fid = p.add_item("x.wav", effectcraft_color::Label::SeaFoam, None, ItemKind::Footage(f));
+ let comp = Comp::new(64, 64, FrameRate::new(25, 1), Tick::from_seconds_f64(2.0));
+ let mut l1 = build::layer(&mut p, &comp, "a", LayerSource::Footage { item: fid }, (0, 0), None);
+ l1.in_point = Tick::from_seconds_f64(1.0);
+ let mut l2 = build::layer(&mut p, &comp, "b", LayerSource::Footage { item: fid }, (0, 0), None);
+ if let Some(g) = l2.props.sub_mut("audio")
+ && let Some(pr) = g.get_mut("levels")
+ {
+ pr.value = effectcraft_project::Value::Vec2([-6.0206, -96.0]);
+ }
+ let mut comp = comp;
+ comp.layers = vec![l1, l2];
+ let cid = p.add_item("C", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(comp.into()));
+ assert!(comp_has_audio(&p, cid));
+ let rate = 1000;
+ let m = mix_comp(&p, &Dc, None, cid, Tick::from_seconds_f64(0.5), 1000, rate);
+ // first half: only layer b (half gain left, muted right)
+ assert!((m[0] - 0.125).abs() < 1e-3 && m[1].abs() < 1e-6, "{} {}", m[0], m[1]);
+ // second half (≥ 1 s): a + b
+ let i = 700 * 2;
+ assert!((m[i] - 0.375).abs() < 1e-3 && (m[i + 1] + 0.25).abs() < 1e-3, "{} {}", m[i], m[i + 1]);
+ }
+}
diff --cc crates/render/src/lib.rs
index 4d774e278,eeca6aae4..8dce390b0
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@@ -15,9 -13,8 +15,9 @@@ pub mod text
use std::sync::Arc;
+pub use cache::{CacheStats, LayerCache};
use effectcraft_color::BlendMode;
- use effectcraft_effects::{Buf, EffectCtx, Params};
+ use effectcraft_effects::{Buf, EffectCtx, EffectEnv, EffectHost, LayerPixels, Params};
use effectcraft_geom::{Mat3, vec2};
use effectcraft_project::{Comp, Footage, GroupKind, ItemId, ItemKind, Layer, LayerSource, MatteKind, Node, Project, Quality, Sampling};
pub use effectcraft_raster::Image;
@@@ -30,10 -27,42 +30,43 @@@ use rayon::prelude::*
pub trait FootageSource: Send + Sync {
/// The frame of `item` at source time `t`, straight from the file (any size).
fn frame(&self, item: ItemId, footage: &Footage, t: Tick) -> Option<Arc<Image>>;
- /// `frames` stereo sample frames of `item`'s audio from source time `start` at `rate` Hz,
- /// interleaved L R L R… (silence where there is none). Default: no audio.
- fn audio(&self, _item: ItemId, _footage: &Footage, _start: Tick, frames: usize, _rate: u32) -> Vec<f32> {
- vec![0.0; frames * 2]
+ /// `frames` interleaved stereo sample frames of `item`'s audio from source time `t` at
+ /// `rate` Hz (`None` when unavailable).
+ fn audio(&self, _item: ItemId, _footage: &Footage, _t: Tick, _frames: usize, _rate: u32) -> Option<Vec<f32>> {
+ None
+ }
+ }
+
+ /// Layer parameters and audio for effects (see [`effectcraft_effects::EffectHost`]).
+ struct FxHost<'r, 'a, 'c> {
+ r: &'r Renderer<'a>,
+ ctx: &'c EvalCtx<'a>,
+ layer: &'c Layer,
+ }
+
+ impl EffectHost for FxHost<'_, '_, '_> {
+ 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 || self.r.depth > 8 {
+ return None;
+ }
- let sub = Renderer { project: self.r.project, footage: self.r.footage, expr: self.r.expr, opts: self.r.opts, depth: self.r.depth + 1 };
- let buf = if masks_and_effects { sub.layer_buf(self.ctx, other)? } else { sub.source(self.ctx, other)? };
++ let sub = Renderer { depth: self.r.depth + 1, ..*self.r };
++ // The cached layer buffer is shared; effects get their own copy.
++ let buf = if masks_and_effects { (*sub.layer_buf(self.ctx, other)?).clone() } else { sub.source(self.ctx, other)? };
+ let size = source_size(self.r.project, other);
+ let size = if size.0 == 0 { [self.ctx.comp.width as f64, self.ctx.comp.height as f64] } else { [size.0 as f64, size.1 as f64] };
+ Some(LayerPixels { buf, size })
+ }
+
+ 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)
}
}
@@@ -172,12 -181,8 +208,12 @@@ impl<'a> Renderer<'a>
let GroupKind::Effect { effect } = &g.kind else { continue };
let Some(spec) = effectcraft_effects::find(effect) else { continue };
let params = self.effect_params(ctx, layer, g);
- let ectx = EffectCtx { params: &params, time: lt.seconds(), layer_size, seed: g.uid as u32, adjustment };
+ let ectx = EffectCtx { params: &params, time: lt.seconds(), layer_size, seed: g.uid as u32, adjustment, env };
+ let t0 = std::time::Instant::now();
buf = effectcraft_effects::apply(spec, &ectx, buf);
+ if let Some(v) = timing.as_deref_mut() {
+ v.push((spec.id.to_string(), t0.elapsed().as_secs_f64() * 1e3));
+ }
}
buf
}
diff --cc crates/render/src/tests.rs
index 877e9329e,ad6eec2f4..dc1f3cdaf
--- a/crates/render/src/tests.rs
+++ b/crates/render/src/tests.rs
@@@ -161,173 -161,45 +161,210 @@@ fn effects_run_in_pipeline()
assert!(c[1] > 0.99 && c[0] < 0.01, "{c:?}");
}
+// ------------------------------------------------------------------------------ layer cache
+
+fn render_cached(p: &Project, cid: ItemId, t: Tick, cache: Option<&crate::LayerCache>) -> crate::Image {
+ let mut r = crate::Renderer::new(p, &crate::NoFootage, crate::RenderOpts::default());
+ r.cache = cache;
+ r.comp_frame(cid, t)
+}
+
- fn add_effect(p: &mut Project, l: &mut effectcraft_project::Layer, id: &str, params: &[(&str, Value)]) {
++/// [`add_effect`] for a 200×100 layer.
++fn add_effect_200(p: &mut Project, l: &mut effectcraft_project::Layer, id: &str, vals: &[(&str, Value)]) {
++ add_effect(p, l, id, [200.0, 100.0], vals);
++}
++
+ fn add_effect(p: &mut Project, l: &mut effectcraft_project::Layer, id: &str, size: [f64; 2], vals: &[(&str, Value)]) {
let spec = effectcraft_effects::find(id).unwrap();
let mut next = p.next_id;
- let mut g = effectcraft_effects::instantiate(spec, &mut Ids(&mut next), spec.name, [200.0, 100.0]);
+ let mut g = effectcraft_effects::instantiate(spec, &mut Ids(&mut next), spec.name, size);
p.next_id = next;
- for (k, v) in params {
+ for (k, v) in vals {
g.prop_mut(k).unwrap().value = v.clone();
}
l.props.sub_mut("effects").unwrap().children.push(g.into());
}
+/// A comp with a static effected solid, an animated-trim shape, a moving text layer with a blur.
+fn cache_scene() -> (Project, ItemId) {
+ let (mut p, cid, comp) = setup();
+ let mut bg = solid(&mut p, &comp, [0.2, 0.3, 0.4], 200, 100);
- add_effect(&mut p, &mut bg, "ec.color.tint", &[("white", Value::Color([1.0, 0.5, 0.0, 1.0]))]);
++ add_effect_200(&mut p, &mut bg, "ec.color.tint", &[("white", Value::Color([1.0, 0.5, 0.0, 1.0]))]);
+ let mut shape = build::layer(&mut p, &comp, "Shape", LayerSource::Shape, (200, 100), None);
+ let mut next = p.next_id;
+ {
+ let mut ids = Ids(&mut next);
+ let e = build::shape_ellipse(&mut ids, [60.0, 60.0], [0.0, 0.0]);
+ let tr = build::shape_trim(&mut ids, 0.0, 0.0, 0.0);
+ let s = build::shape_stroke(&mut ids, [1.0, 1.0, 1.0, 1.0], 4.0);
+ let g = build::shape_group(&mut ids, "Ring", vec![e, tr, s]);
+ shape.props.sub_mut("contents").unwrap().children.push(g.into());
+ }
+ p.next_id = next;
+ shape.props.prop_mut("contents/group#1/contents/trim/end").unwrap().keys =
+ vec![Keyframe::new(Tick::ZERO, Value::Scalar(10.0)), Keyframe::new(Tick::from_seconds_f64(1.0), Value::Scalar(100.0))];
+ let mut text = build::layer(&mut p, &comp, "Text", LayerSource::Text, (200, 100), None);
+ text.props.prop_mut("text/sourceText").unwrap().value = Value::Text(Box::new(TextDoc { text: "AB".into(), size: 40.0, ..Default::default() }));
+ text.props.prop_mut("transform/position").unwrap().keys =
+ vec![Keyframe::new(Tick::ZERO, Value::Vec3([20.0, 70.0, 0.0])), Keyframe::new(Tick::from_seconds_f64(1.0), Value::Vec3([120.0, 70.0, 0.0]))];
- add_effect(&mut p, &mut text, "ec.blur.gaussian", &[("blurriness", Value::Scalar(6.0))]);
++ add_effect_200(&mut p, &mut text, "ec.blur.gaussian", &[("blurriness", Value::Scalar(6.0))]);
+ let c = p.comp_mut(cid).unwrap();
+ c.layers = vec![text, shape, bg];
+ (p, cid)
+}
+
+fn assert_same(a: &crate::Image, b: &crate::Image, what: &str) {
+ assert_eq!((a.width, a.height), (b.width, b.height), "{what}");
+ for (i, (p, q)) in a.data.iter().zip(&b.data).enumerate() {
+ for c in 0..4 {
+ assert!((p[c] - q[c]).abs() < 1e-6, "{what}: pixel {i}: {p:?} vs {q:?}");
+ }
+ }
+}
+
+#[test]
+fn cached_frames_match_uncached() {
+ let (p, cid) = cache_scene();
+ let cache = crate::LayerCache::default();
+ for f in [0.0, 0.25, 0.5, 0.5, 1.2, 1.5, 0.25] {
+ let t = Tick::from_seconds_f64(f);
+ assert_same(&render_cached(&p, cid, t, Some(&cache)), &render_cached(&p, cid, t, None), &format!("t={f}"));
+ }
+ // bg is static, text only moves (transform), the shape is static after 1 s: lots of reuse.
+ let st = cache.stats();
+ assert!(st.hits >= 10, "{st:?}");
+}
+
+#[test]
+fn static_and_transform_only_layers_are_reused() {
+ let (p, cid) = cache_scene();
+ let cache = crate::LayerCache::default();
+ render_cached(&p, cid, Tick::from_seconds_f64(0.2), Some(&cache));
+ let before = cache.stats();
+ render_cached(&p, cid, Tick::from_seconds_f64(0.4), Some(&cache));
+ let after = cache.stats();
+ // bg (static) + text (only its position animates) hit; the shape's trim animates: miss.
+ assert_eq!(after.hits - before.hits, 2, "{before:?} {after:?}");
+ assert_eq!(after.misses - before.misses, 1, "{before:?} {after:?}");
+}
+
+type Edit = Box<dyn Fn(&mut Project, ItemId)>;
+
+/// Every kind of edit re-renders the affected layer: the cached render of the edited project
+/// equals a fresh uncached render, and differs from the unedited frame.
+#[test]
+fn edits_invalidate_cached_layers() {
+ let (p, cid) = cache_scene();
+ let t = Tick::from_seconds_f64(0.5);
+ let edits: Vec<(&str, Edit)> = vec![
+ (
+ "effect param value",
+ Box::new(|p, cid| p.comp_mut(cid).unwrap().layers[2].props.prop_mut("effects/#1/white").unwrap().value = Value::Color([0.0, 1.0, 0.0, 1.0])),
+ ),
+ (
+ "effect param keyframes",
+ Box::new(|p, cid| {
+ p.comp_mut(cid).unwrap().layers[0].props.prop_mut("effects/#1/blurriness").unwrap().keys =
+ vec![Keyframe::new(Tick::ZERO, Value::Scalar(0.0)), Keyframe::new(Tick::from_seconds_f64(1.0), Value::Scalar(30.0))]
+ }),
+ ),
+ ("effect disabled", Box::new(|p, cid| p.comp_mut(cid).unwrap().layers[2].props.group_mut("effects/#1").unwrap().enabled = false)),
+ ("effects switch off", Box::new(|p, cid| p.comp_mut(cid).unwrap().layers[0].switches.effects = false)),
+ (
+ "effect added",
+ Box::new(|p, cid| {
+ let mut l = p.comp_mut(cid).unwrap().layers[2].clone();
- add_effect(p, &mut l, "ec.channel.invert", &[]);
++ add_effect_200(p, &mut l, "ec.channel.invert", &[]);
+ p.comp_mut(cid).unwrap().layers[2] = l;
+ }),
+ ),
+ (
+ "shape keyframe moved",
+ Box::new(|p, cid| {
+ p.comp_mut(cid).unwrap().layers[1].props.prop_mut("contents/group#1/contents/trim/end").unwrap().keys[1].time = Tick::from_seconds_f64(2.0)
+ }),
+ ),
+ (
+ "text changed",
+ Box::new(|p, cid| {
+ p.comp_mut(cid).unwrap().layers[0].props.prop_mut("text/sourceText").unwrap().value =
+ Value::Text(Box::new(TextDoc { text: "XYZ".into(), size: 40.0, ..Default::default() }))
+ }),
+ ),
+ (
+ "solid colour",
+ Box::new(|p, cid| {
+ let LayerSource::Solid { item } = p.comp(cid).unwrap().layers[2].source else { unreachable!() };
+ if let ItemKind::Solid(s) = &mut p.item_mut(item).unwrap().kind {
+ s.color = [0.9, 0.1, 0.1];
+ }
+ p.comp_mut(cid).unwrap().layers[2].props.group_mut("effects/#1").unwrap().enabled = false;
+ }),
+ ),
+ (
+ "mask added",
+ Box::new(|p, cid| {
+ let mut next = p.next_id;
+ let m = build::mask(&mut Ids(&mut next), "Mask 1", ShapePath::rect([50.0, 50.0], 40.0, 40.0), MaskMode::Add, [255, 255, 0]);
+ p.next_id = next;
+ p.comp_mut(cid).unwrap().layers[2].props.sub_mut("masks").unwrap().children.push(m.into());
+ }),
+ ),
+ ("layer time shifted", Box::new(|p, cid| p.comp_mut(cid).unwrap().layers[1].start_time = Tick::from_seconds_f64(0.3))),
+ ];
+ for (what, edit) in edits {
+ let cache = crate::LayerCache::default();
+ let orig = render_cached(&p, cid, t, Some(&cache));
+ let mut q = p.clone();
+ edit(&mut q, cid);
+ let cached = render_cached(&q, cid, t, Some(&cache));
+ let fresh = render_cached(&q, cid, t, None);
+ assert_same(&cached, &fresh, what);
+ assert!(orig.data.iter().zip(&fresh.data).any(|(a, b)| (a[0] - b[0]).abs() + (a[3] - b[3]).abs() > 1e-3), "{what}: edit had no visible effect");
+ }
+}
+
+#[test]
+fn time_dependent_effects_rerender_every_frame() {
+ let (mut p, cid, comp) = setup();
+ let mut l = solid(&mut p, &comp, [0.5, 0.5, 0.5], 200, 100);
- add_effect(&mut p, &mut l, "ec.noise.noise", &[("amount", Value::Scalar(50.0))]);
++ add_effect_200(&mut p, &mut l, "ec.noise.noise", &[("amount", Value::Scalar(50.0))]);
+ p.comp_mut(cid).unwrap().layers.push(l);
+ let cache = crate::LayerCache::default();
+ let a = render_cached(&p, cid, Tick::from_seconds_f64(0.1), Some(&cache));
+ let b = render_cached(&p, cid, Tick::from_seconds_f64(0.2), Some(&cache));
+ assert_same(&b, &render_cached(&p, cid, Tick::from_seconds_f64(0.2), None), "noise at 0.2");
+ assert!(a != b, "noise must animate");
+}
++
+ #[test]
+ fn effects_see_layer_masks() {
+ let (mut p, cid, comp) = setup();
+ let mut l = solid(&mut p, &comp, [0.0, 0.0, 0.0], 200, 100);
+ let mut next = p.next_id;
+ let m = build::mask(&mut Ids(&mut next), "Mask 1", ShapePath::rect([50.0, 50.0], 40.0, 40.0), MaskMode::None, [255, 255, 0]);
+ p.next_id = next;
+ l.props.sub_mut("masks").unwrap().children.push(m.into());
+ add_effect(&mut p, &mut l, "ec.generate.stroke", [200.0, 100.0], &[("brushSize", Value::Scalar(6.0))]);
+ p.comp_mut(cid).unwrap().layers.push(l);
+ let img = render_frame(&p, cid, Tick::ZERO, 1.0);
+ assert!(img.get(30, 50)[0] > 0.5, "stroke on the mask edge: {:?}", img.get(30, 50));
+ assert!(img.get(50, 50)[0] < 0.01, "inside untouched");
+ assert!(img.get(150, 50)[3] > 0.99, "mode None mask does not cut the layer");
+ }
+
+ #[test]
+ fn effects_read_layer_params() {
+ let (mut p, cid, comp) = setup();
+ let mut src = solid(&mut p, &comp, [0.0, 0.0, 1.0], 200, 100);
+ src.switches.video = false;
+ let src_id = src.id.0;
+ let mut top = solid(&mut p, &comp, [1.0, 0.0, 0.0], 200, 100);
+ add_effect(&mut p, &mut top, "ec.channel.blend", [200.0, 100.0], &[("blendWithLayer", Value::Layer(Some(src_id)))]);
+ let c = p.comp_mut(cid).unwrap();
+ c.layers.push(top);
+ c.layers.push(src);
+ let img = render_frame(&p, cid, Tick::ZERO, 1.0);
+ let px = img.get(100, 50);
+ assert!(px[2] > 0.99 && px[0] < 0.01, "{px:?}");
+ }