ANM-6, CMP-5, CMP-3: Wiggler/Smoother/Motion Sketch, marker dialog + timeline markers, pre-compose options + comp navigator

- keys.wiggle / keys.smooth / motion.sketch engine commands (seeded noise, curve-fit
  smoothing within tolerance, pointer-path capture to Position keys), Wiggler, Smoother and
  Motion Sketch panels, viewer capture overlay.
- markers.list/set/delete/convert, Update Markers From Source; Marker dialog (time, duration,
  comment, chapter, URL + frame target, cue point, protected region, label); timeline marker
  drag with snapping, Alt-drag duration, Cmd/Ctrl-click delete, context menu, protected
  regions shaded.
- layer.precompose mode leave|move, adjustDuration, open; Pre-compose dialog; Composition
  Navigator bar and Mini-Flowchart (Tab).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-02 10:47:02 -04:00
co-authored by Claude Opus 5.5
parent ab3b4cfb70
commit 3cdbf22aac
22 changed files with 2279 additions and 74 deletions
+411
View File
@@ -0,0 +1,411 @@
//! Keyframe assistants of the Wiggler, Smoother and Motion Sketch panels (Window ▸ Wiggler /
//! Smoother / Motion Sketch). Each is one undoable command, so agents get the same results as the
//! panels:
//!
//! * `keys.wiggle` adds random deviation keys between the first and last selected keys of each
//! property (Spatial or Temporal path, smooth or jagged noise, one / all-the-same / independent
//! dimensions, frequency in keys per second, magnitude in the property's units). Seeded, so a
//! given selection and seed always produce the same keys.
//! * `keys.smooth` replaces the selected run of keys by the fewest auto-Bezier keys that stay
//! within `tolerance` of the original curve (sampled every frame).
//! * `motion.sketch` turns a recorded pointer path (comp pixels, with capture timestamps) into
//! Position keys, one per frame, then smooths them like the Smoother.
use effectcraft_keyframe::{Interp, Keyframe, Value as KValue, evaluate};
use effectcraft_project::{LayerId, Uid};
use effectcraft_time::{FrameRate, Tick};
use serde_json::{Value, json};
use super::{CommandSpec, bad, f_p, has_comp, has_keys, layer_mut, layer_p, str_p};
use crate::{EngineError, KeyRef, Result, Session, cmd};
// ---------------------------------------------------------------- noise
fn splitmix(mut x: u64) -> u64 {
x = x.wrapping_add(0x9e37_79b9_7f4a_7c15);
x = (x ^ (x >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
x = (x ^ (x >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
x ^ (x >> 31)
}
/// Deterministic uniform noise in [-1, 1] for (seed, stream, index).
fn rnd(seed: u64, stream: u64, i: i64) -> f64 {
let h = splitmix(seed ^ splitmix(stream.wrapping_mul(0x1000_0000_01b3) ^ (i as u64)));
(h >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0
}
/// Wiggler noise type.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Noise {
/// Gradual deviations: lattice noise at half the key rate with cosine interpolation.
Smooth,
/// Independent deviations per key.
Jagged,
}
/// Noise sample `k` (0-based key index) in [-1, 1].
fn noise(kind: Noise, seed: u64, stream: u64, k: i64) -> f64 {
match kind {
Noise::Jagged => rnd(seed, stream, k),
Noise::Smooth => {
let (i, f) = (k.div_euclid(2), (k.rem_euclid(2)) as f64 / 2.0);
let w = (1.0 - (f * std::f64::consts::PI).cos()) / 2.0;
rnd(seed, stream, i) * (1.0 - w) + rnd(seed, stream, i + 1) * w
}
}
}
/// Which dimensions the Wiggler affects.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Dims {
/// Only dimension `n`.
One(usize),
/// All dimensions by the same amount.
Same,
/// Each dimension independently.
Independent,
}
/// Wiggler settings.
#[derive(Clone, Copy, Debug)]
pub struct WiggleOpts {
/// Spatial path (deviate values along the motion path) or temporal path (deviate timing on
/// spatial properties; values on others).
pub spatial: bool,
pub noise: Noise,
pub dims: Dims,
/// Keys per second.
pub frequency: f64,
pub magnitude: f64,
pub seed: u64,
}
/// Wiggle `keys` between keys `a` and `b` (indices, `a < b`): returns the new key list. New keys
/// fall on whole frames of `fr` (via `to_layer`/`to_comp` time maps). `spatial_prop` selects
/// motion-path semantics.
#[allow(clippy::too_many_arguments)]
pub fn wiggle_keys(
keys: &[Keyframe],
a: usize,
b: usize,
spatial_prop: bool,
fr: FrameRate,
to_comp: &dyn Fn(Tick) -> Tick,
to_layer: &dyn Fn(Tick) -> Tick,
o: &WiggleOpts,
stream: u64,
) -> Vec<Keyframe> {
let (t0, t1) = (keys[a].time, keys[b].time);
let (f0, f1) = (fr.frame_at(to_comp(t0)), fr.frame_at(to_comp(t1)));
let fps = fr.as_f64();
let step = ((fps / o.frequency.max(0.01)).round() as i64).max(1);
let orig = keys.to_vec();
let mut out: Vec<Keyframe> = keys.iter().filter(|k| k.time <= t0 || k.time >= t1).cloned().collect();
let template = keys[a].clone();
let dims = template.value.components().len();
let mut k = 1;
loop {
let f = f0 + k * step;
if f >= f1 {
break;
}
let lt = to_layer(fr.tick_of(f));
let base_t = if o.spatial || !spatial_prop {
lt
} else {
// Temporal path on a spatial property: sample the path at a jittered time (magnitude in
// percent of the key spacing), so the speed along the path wiggles.
let jit = noise(o.noise, o.seed, stream, k) * o.magnitude / 100.0 * step as f64 / fps;
Tick::from_seconds_f64((lt.seconds() + jit).clamp(t0.seconds(), t1.seconds()))
};
let Some(v) = evaluate(&orig, base_t, spatial_prop) else { break };
let mut c = v.components();
if o.spatial || !spatial_prop {
for (d, x) in c.iter_mut().enumerate().take(dims) {
let n = match o.dims {
Dims::One(i) if i != d => 0.0,
Dims::One(_) | Dims::Same => noise(o.noise, o.seed, stream, k),
Dims::Independent => noise(o.noise, o.seed, stream.wrapping_add(d as u64 * 7919 + 1), k),
};
*x += n * o.magnitude;
}
}
let mut key = Keyframe::new(lt, v.with_components(&c));
if o.noise == Noise::Smooth {
key.in_interp = Interp::Bezier;
key.out_interp = Interp::Bezier;
key.auto_bezier = true;
}
out.push(key);
k += 1;
}
out.sort_by_key(|k| k.time);
out
}
/// Largest distance between the curve of `keys` and `samples`.
fn max_error(keys: &[Keyframe], samples: &[(Tick, Vec<f64>)], spatial: bool) -> (f64, usize) {
let mut worst = (0.0, 0);
for (i, (t, v)) in samples.iter().enumerate() {
let Some(e) = evaluate(keys, *t, spatial) else { continue };
let d = e.components().iter().zip(v).map(|(a, b)| (a - b) * (a - b)).sum::<f64>().sqrt();
if d > worst.0 {
worst = (d, i);
}
}
worst
}
/// Smoother: replace the keys strictly between `a` and `b` (indices) by the fewest auto-Bezier
/// keys at sample times that keep the curve within `tolerance` of `samples` (the original
/// curve, usually one sample per frame). Keys outside `a..=b` are kept.
pub fn smooth_keys(keys: &[Keyframe], a: usize, b: usize, samples: &[(Tick, Vec<f64>)], tolerance: f64, spatial: bool) -> Vec<Keyframe> {
let template = keys[a].value.clone();
let make = |t: Tick, c: &[f64]| {
let mut k = Keyframe::new(t, template.with_components(c));
if !spatial {
k.in_interp = Interp::Bezier;
k.out_interp = Interp::Bezier;
k.auto_bezier = true;
}
k
};
let mut chosen: Vec<usize> = vec![];
let build = |chosen: &[usize]| {
let mut v: Vec<Keyframe> = keys[..=a].to_vec();
v.extend(chosen.iter().map(|&i| make(samples[i].0, &samples[i].1)));
v.extend(keys[b..].iter().cloned());
v.sort_by_key(|k| k.time);
v
};
loop {
let cur = build(&chosen);
let (err, at) = max_error(&cur, samples, spatial);
let t = samples[at].0;
if err <= tolerance || chosen.contains(&at) || t <= keys[a].time || t >= keys[b].time || chosen.len() >= samples.len() {
return cur;
}
chosen.push(at);
chosen.sort_unstable();
}
}
/// The curve of `keys` sampled at every comp frame between key times `t0` and `t1` (layer time).
fn sample_curve(
keys: &[Keyframe],
t0: Tick,
t1: Tick,
spatial: bool,
fr: FrameRate,
to_comp: &dyn Fn(Tick) -> Tick,
to_layer: &dyn Fn(Tick) -> Tick,
) -> Vec<(Tick, Vec<f64>)> {
let (f0, f1) = (fr.frame_at(to_comp(t0)), fr.frame_at(to_comp(t1)));
(f0..=f1)
.filter_map(|f| {
let t = to_layer(fr.tick_of(f));
(t >= t0 && t <= t1).then(|| evaluate(keys, t, spatial).map(|v| (t, v.components())))?
})
.collect()
}
// ---------------------------------------------------------------- commands
fn grouped_selection(s: &Session) -> std::collections::BTreeMap<(LayerId, Uid), Vec<Tick>> {
let mut g: std::collections::BTreeMap<(LayerId, Uid), Vec<Tick>> = Default::default();
for k in &s.state.selected_keys {
g.entry((k.layer, k.prop)).or_default().push(k.time);
}
for v in g.values_mut() {
v.sort();
}
g
}
fn parse_wiggle(p: &Value) -> Result<WiggleOpts> {
let c = "keys.wiggle";
let spatial = match str_p(p, "apply").unwrap_or("spatial") {
"spatial" | "Spatial Path" => true,
"temporal" | "Temporal Path" => false,
x => return Err(bad(c, format!("apply: spatial|temporal, got `{x}`"))),
};
let noise = match str_p(p, "noise").unwrap_or("smooth") {
"smooth" | "Smooth" => Noise::Smooth,
"jagged" | "Jagged" => Noise::Jagged,
x => return Err(bad(c, format!("noise: smooth|jagged, got `{x}`"))),
};
let dims = match str_p(p, "dimensions").unwrap_or("independent") {
"one" => Dims::One(p.get("dimension").and_then(Value::as_u64).unwrap_or(0) as usize),
"same" | "all" => Dims::Same,
"independent" => Dims::Independent,
x => return Err(bad(c, format!("dimensions: one|same|independent, got `{x}`"))),
};
let frequency = f_p(p, "frequency").unwrap_or(5.0);
if frequency.is_nan() || frequency <= 0.0 {
return Err(bad(c, "frequency must be > 0"));
}
Ok(WiggleOpts {
spatial,
noise,
dims,
frequency,
magnitude: f_p(p, "magnitude").unwrap_or(1.0).abs(),
seed: p.get("seed").and_then(Value::as_u64).unwrap_or(0),
})
}
/// Shared driver: for every property with ≥ `min` selected keys, replace its keys with
/// `f(keys, first, last, spatial, layer_maps)`; select every key in each range afterwards.
#[allow(clippy::type_complexity)]
fn run_on_selection(
s: &mut Session,
label: &str,
cmd: &str,
min: usize,
f: &dyn Fn(&[Keyframe], usize, usize, bool, FrameRate, &dyn Fn(Tick) -> Tick, &dyn Fn(Tick) -> Tick, Uid) -> Vec<Keyframe>,
) -> Result<Value> {
let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
let groups = grouped_selection(s);
if !groups.values().any(|v| v.len() >= min) {
return Err(bad(cmd, format!("select at least {min} keyframes of a property")));
}
let (mut before, mut after) = (0usize, 0usize);
s.edit(label, None, |proj, st| {
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
let fr = comp.frame_rate;
let mut sel = vec![];
for ((lid, uid), times) in groups {
let Some(l) = comp.layer_mut(lid) else { continue };
let lc = l.clone();
let to_comp = |t: Tick| lc.comp_time(t);
let to_layer = |t: Tick| lc.layer_time(t);
let Some(pr) = l.props.find_mut(uid) else { continue };
if times.len() < min || !pr.value.interpolates() {
continue;
}
let (Some(a), Some(b)) =
(effectcraft_keyframe::key_at(&pr.keys, times[0]), effectcraft_keyframe::key_at(&pr.keys, *times.last().unwrap_or(&times[0])))
else {
continue;
};
let in_range = |k: &Keyframe| k.time >= pr.keys[a].time && k.time <= pr.keys[b].time;
before += pr.keys.iter().filter(|k| in_range(k)).count();
let (t0, t1) = (pr.keys[a].time, pr.keys[b].time);
pr.keys = f(&pr.keys, a, b, pr.spatial, fr, &to_comp, &to_layer, uid);
let n: Vec<Tick> = pr.keys.iter().filter(|k| k.time >= t0 && k.time <= t1).map(|k| k.time).collect();
after += n.len();
sel.extend(n.into_iter().map(|time| KeyRef { layer: lid, prop: uid, time }));
}
st.selected_keys = sel;
Ok(())
})?;
Ok(json!({"before": before, "after": after}))
}
fn wiggle(s: &mut Session, p: &Value) -> Result<Value> {
let o = parse_wiggle(p)?;
run_on_selection(s, "Wiggler", "keys.wiggle", 2, &|keys, a, b, spatial, fr, tc, tl, uid| wiggle_keys(keys, a, b, spatial, fr, tc, tl, &o, uid))
}
fn smooth(s: &mut Session, p: &Value) -> Result<Value> {
let tol = f_p(p, "tolerance").unwrap_or(1.0).max(0.0);
run_on_selection(s, "Smoother", "keys.smooth", 3, &|keys, a, b, spatial, fr, tc, tl, _| {
let samples = sample_curve(keys, keys[a].time, keys[b].time, spatial, fr, tc, tl);
smooth_keys(keys, a, b, &samples, tol, spatial)
})
}
/// Motion Sketch: `points` are `[t, x, y]` (t = capture seconds from the start) or `[x, y]`
/// (one per frame); recorded from `start` (default the current time).
fn sketch(s: &mut Session, p: &Value) -> Result<Value> {
let c = "motion.sketch";
let (cid, lid) = layer_p(s, p, c)?;
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let fr = comp.frame_rate;
let fd = fr.frame_duration().seconds();
let pts = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(c, "missing `points`: [[t, x, y]…] or [[x, y]…] in comp pixels"))?;
let mut rec: Vec<(f64, [f64; 2])> = vec![];
for (i, v) in pts.iter().enumerate() {
let a: Vec<f64> = v.as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
match a.len() {
2 => rec.push((i as f64 * fd, [a[0], a[1]])),
3.. => rec.push((a[0], [a[1], a[2]])),
_ => return Err(bad(c, format!("point {i}: expected [t, x, y] or [x, y]"))),
}
}
if rec.len() < 2 {
return Err(bad(c, "need at least two points"));
}
rec.sort_by(|a, b| a.0.total_cmp(&b.0));
// Capture speed: 100 % plays back at the recorded speed; 200 % plays back twice as slow.
let speed = f_p(p, "captureSpeed").unwrap_or(100.0).max(1.0) / 100.0;
let smoothing = f_p(p, "smoothing").unwrap_or(1.0).max(0.0);
let start = p.get("start").and_then(Value::as_f64).map(Tick::from_seconds_f64).unwrap_or_else(|| s.time());
let f0 = fr.frame_at(start);
let t_rec0 = rec[0].0;
let span = (rec.last().map(|r| r.0).unwrap_or(0.0) - t_rec0) * speed;
let nframes = (span / fd).round() as i64;
let end_frame = fr.frame_at(comp.duration - comp.frame_duration());
let at = |secs: f64| {
// Linear interpolation of the recorded path at recording time `secs`.
let i = rec.partition_point(|r| r.0 <= secs).clamp(1, rec.len() - 1);
let (a, b) = (rec[i - 1], rec[i]);
let f = if b.0 > a.0 { ((secs - a.0) / (b.0 - a.0)).clamp(0.0, 1.0) } else { 1.0 };
[a.1[0] + (b.1[0] - a.1[0]) * f, a.1[1] + (b.1[1] - a.1[1]) * f]
};
let n = s.edit("Motion Sketch", None, |proj, st| {
let l = layer_mut(proj, cid, lid)?;
let lc = l.clone();
let pos = l.props.prop_mut("transform/position").ok_or_else(|| bad(c, "the layer has no Position"))?;
let z = pos.value.as_vec3()[2];
let three = matches!(pos.value, KValue::Vec3(_));
let mut new: Vec<Keyframe> = vec![];
for k in 0..=nframes {
let f = f0 + k;
if f > end_frame {
break;
}
let q = at(t_rec0 + k as f64 * fd / speed);
let v = if three { KValue::Vec3([q[0], q[1], z]) } else { KValue::Vec2(q) };
new.push(Keyframe::new(lc.layer_time(fr.tick_of(f)), v));
}
let (Some(t0), Some(t1)) = (new.first().map(|k| k.time), new.last().map(|k| k.time)) else { return Ok(0) };
let mut keys: Vec<Keyframe> = pos.keys.iter().filter(|k| k.time < t0 || k.time > t1).cloned().collect();
keys.extend(new);
keys.sort_by_key(|k| k.time);
let (a, b) = (keys.iter().position(|k| k.time == t0).unwrap_or(0), keys.iter().position(|k| k.time == t1).unwrap_or(0));
if smoothing > 0.0 && b > a + 1 {
let samples: Vec<(Tick, Vec<f64>)> = keys[a..=b].iter().map(|k| (k.time, k.value.components())).collect();
keys = smooth_keys(&keys, a, b, &samples, smoothing, true);
}
pos.keys = keys;
let uid = pos.uid;
st.selected_keys = pos.keys.iter().filter(|k| k.time >= t0 && k.time <= t1).map(|k| KeyRef { layer: lid, prop: uid, time: k.time }).collect();
Ok(st.selected_keys.len())
})?;
Ok(json!({"keys": n}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"keys.wiggle",
"Wiggler",
[],
None,
"{apply?: spatial|temporal, noise?: smooth|jagged, dimensions?: one|same|independent, dimension? (index for `one`), frequency? (keys/s, 5), magnitude?, seed?}",
has_keys,
wiggle
),
cmd!("keys.smooth", "Smoother", [], None, "{tolerance? (property units, 1)}", has_keys, smooth),
cmd!(
"motion.sketch",
"Motion Sketch",
[],
None,
"{layer?, points: [[t, x, y]…] (t = capture seconds) | [[x, y]…] (one per frame), start? (s, default current time), captureSpeed? (%, 100), smoothing? (px, 1)}",
has_comp,
sketch
),
]
}
+1 -1
View File
@@ -74,7 +74,7 @@ pub fn specs() -> Vec<CommandSpec> {
fe!("window.editWorkspaces", "Edit Workspaces...", ["Window", "Workspace"], None, "{name, rename?: new name, delete?: bool}", always),
fe!("window.resetWorkspace", "Reset to Saved Layout", ["Window", "Workspace"], None, "{}", always),
fe!("comp.flowchart", "Composition Flowchart", ["Composition"], Some("Cmd+F11"), "{}", always),
fe!("comp.miniFlowchart", "Composition Mini-Flowchart", ["Composition"], None, "{}", has_comp),
fe!("comp.miniFlowchart", "Composition Mini-Flowchart", ["Composition"], Some("Tab"), "{}", has_comp),
fe!("layer.openLayer", "Open Layer", ["Layer"], None, "{layer?}", has_layers),
fe!("effect.manage", "Manage Effects...", ["Effect"], None, "{}", always),
fe!("anim.browsePresets", "Browse Presets...", ["Animation"], None, "{}", always),
+71 -4
View File
@@ -715,15 +715,65 @@ fn arrange(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
/// Layer ▸ Pre-compose. `mode: move` (default; "Move all attributes into the new composition")
/// nests the selected layers as they are; `mode: leave` ("Leave all attributes in", one footage,
/// solid or precomp layer) nests only the layer's source, sized to it, and keeps the layer's
/// transform, masks, effects and timing in the current comp. `adjustDuration` (move) trims the
/// new comp to the selected layers' span; `open` opens the new comp.
fn precompose(s: &mut Session, p: &Value) -> Result<Value> {
let c = "layer.precompose";
let (cid, ids) = layers_p(s, p)?;
if ids.is_empty() {
return Err(bad("layer.precompose", "no layers"));
return Err(bad(c, "no layers"));
}
let name = str_p(p, "name").unwrap_or("Pre-comp 1").to_string();
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
let leave = match str_p(p, "mode").unwrap_or("move") {
"move" => false,
"leave" => true,
x => return Err(bad(c, format!("mode: move|leave, got `{x}`"))),
};
let adjust = b_p(p, "adjustDuration").unwrap_or(false);
if leave {
let [lid] = ids[..] else { return Err(bad(c, "\"Leave all attributes\" needs exactly one layer")) };
let layer = comp.layer(lid).ok_or(EngineError::NoComp)?.clone();
let Some(src_item) = layer.source.item() else {
return Err(bad(c, "\"Leave all attributes\" is available for footage, solid and precomp layers only"));
};
let (w, h) = effectcraft_render::source_size(&s.project, &layer);
let (w, h) = if w == 0 || h == 0 { (comp.width, comp.height) } else { (w, h) };
let dur = match s.project.item(src_item).map(|i| &i.kind) {
Some(ItemKind::Comp(nc)) => nc.duration,
Some(ItemKind::Footage(f)) if f.duration > Tick(0) => f.duration,
_ => comp.duration,
};
let new = s.edit("Pre-compose", None, |proj, st| {
let mut inner = Comp::new(w, h, comp.frame_rate, dur);
inner.background = comp.background;
let mut il = build::layer(proj, &inner, &layer.name, layer.source.clone(), (w, h), Some(dur));
il.name = layer.name.clone();
inner.layers.push(il);
let iid = proj.add_item(&name, Label::Sandstone, None, ItemKind::Comp(inner.into()));
let l = layer_mut(proj, cid, lid)?;
l.source = LayerSource::Comp { item: iid };
l.name = name.clone();
st.selected_layers = vec![lid];
Ok((iid, lid))
})?;
if b_p(p, "open").unwrap_or(false) {
s.open_comp(new.0);
}
return Ok(json!({"comp": new.0.0, "layer": new.1.0}));
}
let span = {
let sel: Vec<&effectcraft_project::Layer> = comp.layers.iter().filter(|l| ids.contains(&l.id)).collect();
let a = sel.iter().map(|l| l.in_point).min().unwrap_or(Tick(0)).max(Tick(0));
let b = sel.iter().map(|l| l.out_point).max().unwrap_or(comp.duration).min(comp.duration);
(a, b)
};
let (offset, dur) = if adjust && span.1 > span.0 { (span.0, span.1 - span.0) } else { (Tick(0), comp.duration) };
let new = s.edit("Pre-compose", None, |proj, st| {
let mut inner = Comp::new(comp.width, comp.height, comp.frame_rate, comp.duration);
let mut inner = Comp::new(comp.width, comp.height, comp.frame_rate, dur);
inner.background = comp.background;
inner.layers = comp.layers.iter().filter(|l| ids.contains(&l.id)).cloned().collect();
for l in &mut inner.layers {
@@ -733,10 +783,16 @@ fn precompose(s: &mut Session, p: &Value) -> Result<Value> {
if l.track_matte.is_some_and(|m| !ids.contains(&m.layer)) {
l.track_matte = None;
}
l.start_time -= offset;
l.in_point -= offset;
l.out_point -= offset;
}
let iid = proj.add_item(&name, Label::Sandstone, None, ItemKind::Comp(inner.into()));
let mut l = build::layer(proj, &comp, &name, LayerSource::Comp { item: iid }, (comp.width, comp.height), Some(comp.duration));
let mut l = build::layer(proj, &comp, &name, LayerSource::Comp { item: iid }, (comp.width, comp.height), Some(dur));
l.name = name.clone();
l.start_time = offset;
l.in_point = offset;
l.out_point = offset + dur;
let c = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
let at = c.layers.iter().position(|l| ids.contains(&l.id)).unwrap_or(0);
c.layers.retain(|l| !ids.contains(&l.id));
@@ -745,6 +801,9 @@ fn precompose(s: &mut Session, p: &Value) -> Result<Value> {
st.selected_layers = vec![lid];
Ok((iid, lid))
})?;
if b_p(p, "open").unwrap_or(false) {
s.open_comp(new.0);
}
Ok(json!({"comp": new.0.0, "layer": new.1.0}))
}
@@ -1033,7 +1092,15 @@ pub fn specs() -> Vec<CommandSpec> {
slip(s, &p)
}),
cmd!("layer.arrange", "Arrange", ["Layer", "Arrange"], None, "{layers?, to: front|forward|backward|back, index?}", has_layers, arrange),
cmd!("layer.precompose", "Pre-compose...", ["Layer"], Some("Cmd+Shift+C"), "{layers?, name?}", has_layers, precompose),
cmd!(
"layer.precompose",
"Pre-compose...",
["Layer"],
Some("Cmd+Shift+C"),
"{layers?, name?, mode?: move|leave, adjustDuration?, open?}",
has_layers,
precompose
),
cmd!(
"layer.addMask",
"New Mask",
+323
View File
@@ -0,0 +1,323 @@
//! Composition and layer markers: the Composition/Layer Marker dialog (`markers.set`), dragging
//! and Alt-dragging the duration in the Timeline (`markers.set` with `merge`), deleting
//! (`markers.delete`, Ctrl/Cmd-click), converting between layer and comp markers
//! (`markers.convert`) and Layer ▸ Markers ▸ Update Markers From Source. Times in parameters are
//! comp seconds; layer markers are stored in layer time. All commands are undoable.
use effectcraft_color::Label;
use effectcraft_project::{Comp, CuePoint, ItemId, LayerId, LayerSource, Marker};
use effectcraft_time::Tick;
use serde_json::{Value, json};
use super::{CommandSpec, b_p, bad, comp_id, f_p, has_comp, has_layers, layers_p, merge_p, resolve_layer, str_p};
use crate::{EngineError, Result, Session, cmd, query};
/// Where a marker lives.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Owner {
Comp,
Layer(LayerId),
}
fn owner(s: &Session, p: &Value, cmd: &str) -> Result<(ItemId, Owner)> {
let cid = comp_id(s, p)?;
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
match p.get("layer") {
None | Some(Value::Null) => Ok((cid, Owner::Comp)),
Some(v) => resolve_layer(comp, v).map(|l| (cid, Owner::Layer(l))).ok_or_else(|| bad(cmd, format!("no layer {v}"))),
}
}
fn markers_of(c: &Comp, o: Owner) -> Option<&Vec<Marker>> {
match o {
Owner::Comp => Some(&c.markers),
Owner::Layer(l) => c.layer(l).map(|l| &l.markers),
}
}
/// Comp time ↔ marker time (layer markers are in layer time).
fn to_marker_time(c: &Comp, o: Owner, comp_t: Tick) -> Tick {
match o {
Owner::Comp => comp_t,
Owner::Layer(l) => c.layer(l).map_or(comp_t, |l| l.layer_time(comp_t)),
}
}
fn to_comp_time(c: &Comp, o: Owner, t: Tick) -> Tick {
match o {
Owner::Comp => t,
Owner::Layer(l) => c.layer(l).map_or(t, |l| l.comp_time(t)),
}
}
/// `index` (0-based) or `at` (comp seconds, within half a frame).
fn find_index(c: &Comp, o: Owner, p: &Value, cmd: &str) -> Result<usize> {
let ms = markers_of(c, o).ok_or_else(|| bad(cmd, "no such layer"))?;
if let Some(i) = p.get("index").and_then(Value::as_u64) {
return (i < ms.len() as u64).then_some(i as usize).ok_or_else(|| bad(cmd, format!("no marker #{i} ({} markers)", ms.len())));
}
if let Some(at) = f_p(p, "at") {
let t = Tick::from_seconds_f64(at);
let half = Tick(c.frame_duration().0 / 2);
return ms.iter().position(|m| (to_comp_time(c, o, m.time) - t).0.abs() <= half.0).ok_or_else(|| bad(cmd, format!("no marker at {at} s")));
}
Err(bad(cmd, "give the marker `index` (0-based) or `at` (comp seconds)"))
}
fn marker_json(c: &Comp, o: Owner, i: usize, m: &Marker) -> Value {
json!({
"index": i,
"time": to_comp_time(c, o, m.time).seconds(),
"duration": m.duration.seconds(),
"comment": m.comment,
"chapter": m.chapter,
"url": m.url,
"frameTarget": m.frame_target,
"cuePoint": m.cue_point.as_ref().map(|q| json!({"name": q.name, "navigation": q.navigation, "params": q.params})),
"protected": m.protected,
"label": m.label.name(),
})
}
fn list(s: &mut Session, p: &Value) -> Result<Value> {
let (cid, o) = owner(s, p, "markers.list")?;
let c = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let ms = markers_of(c, o).cloned().unwrap_or_default();
Ok(Value::Array(ms.iter().enumerate().map(|(i, m)| marker_json(c, o, i, m)).collect()))
}
fn locked(c: &Comp, o: Owner) -> bool {
matches!(o, Owner::Layer(l) if c.layer(l).is_some_and(|l| l.markers_locked))
}
/// Apply the dialog fields in `p` to `m`. `time`/`duration` are comp seconds.
fn apply_fields(c: &Comp, o: Owner, m: &mut Marker, p: &Value, cmd: &str) -> Result<()> {
let fr = c.frame_rate;
if let Some(t) = f_p(p, "time") {
let ct = fr.snap_nearest(Tick::from_seconds_f64(t.max(0.0)));
m.time = to_marker_time(c, o, ct);
}
if let Some(d) = f_p(p, "duration") {
m.duration = fr.snap_nearest(Tick::from_seconds_f64(d.max(0.0)));
}
if let Some(v) = str_p(p, "comment") {
m.comment = v.into();
}
if let Some(v) = str_p(p, "chapter") {
m.chapter = v.into();
}
if let Some(v) = str_p(p, "url") {
m.url = v.into();
}
if let Some(v) = str_p(p, "frameTarget") {
m.frame_target = v.into();
}
if let Some(v) = b_p(p, "protected") {
m.protected = v;
}
if let Some(l) = p.get("label") {
m.label = match l {
Value::Number(n) => Label::ALL.get(n.as_u64().unwrap_or(0) as usize).copied(),
Value::String(s) => Label::from_name(s),
_ => None,
}
.ok_or_else(|| bad(cmd, format!("unknown label {l}")))?;
}
match p.get("cuePoint") {
Some(Value::Null) => m.cue_point = None,
Some(q @ Value::Object(_)) => {
let name = q.get("name").and_then(Value::as_str).unwrap_or_default().to_string();
let navigation = q.get("navigation").and_then(Value::as_bool).unwrap_or(false) || q.get("kind").and_then(Value::as_str) == Some("navigation");
let params = q
.get("params")
.and_then(Value::as_array)
.map(|a| {
a.iter()
.filter_map(|e| match e {
Value::Array(kv) => Some((kv.first()?.as_str()?.to_string(), kv.get(1).and_then(Value::as_str).unwrap_or_default().to_string())),
Value::Object(o) => {
Some((o.get("name")?.as_str()?.to_string(), o.get("value").and_then(Value::as_str).unwrap_or_default().to_string()))
}
_ => None,
})
.collect()
})
.unwrap_or_default();
m.cue_point = Some(CuePoint { name, navigation, params });
}
Some(v) => return Err(bad(cmd, format!("cuePoint: {{name, navigation?, params?: [[name, value]…]}} or null, got {v}"))),
None => {}
}
Ok(())
}
fn markers_mut(c: &mut Comp, o: Owner) -> Option<&mut Vec<Marker>> {
match o {
Owner::Comp => Some(&mut c.markers),
Owner::Layer(l) => c.layer_mut(l).map(|l| &mut l.markers),
}
}
/// Edit (or with `new: true`, add) a marker. Returns its new index.
fn set(s: &mut Session, p: &Value) -> Result<Value> {
let c = "markers.set";
let (cid, o) = owner(s, p, c)?;
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
if locked(comp, o) {
return Err(bad(c, "the layer's markers are locked"));
}
let adding = b_p(p, "new").unwrap_or(false);
let idx = if adding { None } else { Some(find_index(comp, o, p, c)?) };
let now = s.time();
let label = if adding { "Add Marker" } else { "Marker Settings" };
let i = s.edit(label, merge_p(p), |proj, _| {
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
let snapshot = comp.clone();
let mut m = match idx {
Some(i) => markers_of(&snapshot, o).and_then(|v| v.get(i)).cloned().ok_or_else(|| bad(c, "marker vanished"))?,
None => Marker { time: to_marker_time(&snapshot, o, snapshot.frame_rate.snap_nearest(now)), ..Default::default() },
};
apply_fields(&snapshot, o, &mut m, p, c)?;
let v = markers_mut(comp, o).ok_or_else(|| bad(c, "no such layer"))?;
if let Some(i) = idx {
v.remove(i);
}
v.push(m.clone());
v.sort_by_key(|x| x.time);
Ok(v.iter().position(|x| *x == m).unwrap_or(0))
})?;
Ok(json!({"index": i}))
}
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
let c = "markers.delete";
let (cid, o) = owner(s, p, c)?;
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
if locked(comp, o) {
return Err(bad(c, "the layer's markers are locked"));
}
let i = find_index(comp, o, p, c)?;
s.edit("Delete Marker", None, |proj, _| {
markers_mut(proj.comp_mut(cid).ok_or(EngineError::NoComp)?, o).ok_or_else(|| bad(c, "no such layer"))?.remove(i);
Ok(())
})?;
Ok(Value::Null)
}
/// Layer marker → comp marker (when `layer` is given), or comp marker → layer marker on
/// `toLayer` (default: the selected layers).
fn convert(s: &mut Session, p: &Value) -> Result<Value> {
let c = "markers.convert";
let (cid, o) = owner(s, p, c)?;
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
let i = find_index(&comp, o, p, c)?;
let m = markers_of(&comp, o).and_then(|v| v.get(i)).cloned().ok_or_else(|| bad(c, "no marker"))?;
let ct = to_comp_time(&comp, o, m.time);
let targets: Vec<LayerId> = match o {
Owner::Layer(_) => vec![],
Owner::Comp => match p.get("toLayer") {
Some(v) => vec![resolve_layer(&comp, v).ok_or_else(|| bad(c, format!("no layer {v}")))?],
None => s.state.selected_layers.iter().copied().filter(|l| comp.layer(*l).is_some()).collect(),
},
};
if o == Owner::Comp && targets.is_empty() {
return Err(bad(c, "select the layer to receive the marker (or give `toLayer`)"));
}
let label = if o == Owner::Comp { "Convert to Layer Marker" } else { "Convert to Composition Marker" };
s.edit(label, None, |proj, _| {
let cm = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
markers_mut(cm, o).ok_or_else(|| bad(c, "no such layer"))?.remove(i);
match o {
Owner::Layer(_) => {
cm.markers.push(Marker { time: ct, ..m.clone() });
cm.markers.sort_by_key(|x| x.time);
}
Owner::Comp => {
for lid in &targets {
if let Some(l) = cm.layer_mut(*lid) {
let lt = l.layer_time(ct);
l.markers.push(Marker { time: lt, ..m.clone() });
l.markers.sort_by_key(|x| x.time);
}
}
}
}
Ok(())
})?;
Ok(Value::Null)
}
/// Layer ▸ Markers ▸ Update Markers From Source: copy a precomp's composition markers onto the
/// layer (layer time is the nested comp's time), skipping ones already there.
fn update_from_source(s: &mut Session, p: &Value) -> Result<Value> {
let (cid, ids) = layers_p(s, p)?;
let src: Vec<(LayerId, Vec<Marker>)> = {
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
ids.iter()
.filter_map(|id| {
let l = comp.layer(*id)?;
match &l.source {
LayerSource::Comp { item } => Some((*id, s.project.comp(*item)?.markers.clone())),
_ => None,
}
})
.collect()
};
if src.is_empty() {
return Err(bad("layer.updateMarkersFromSource", "select a precomposition layer"));
}
let n = s.edit("Update Markers From Source", None, |proj, _| {
let c = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
let mut n = 0;
for (lid, ms) in &src {
let Some(l) = c.layer_mut(*lid) else { continue };
if l.markers_locked {
continue;
}
for m in ms {
if !l.markers.iter().any(|x| x.time == m.time) {
l.markers.push(m.clone());
n += 1;
}
}
l.markers.sort_by_key(|x| x.time);
}
Ok(n)
})?;
Ok(json!({"added": n}))
}
fn has_precomp_layer(s: &Session) -> std::result::Result<(), String> {
has_layers(s)?;
let c = s.active_comp().ok_or("no composition")?;
if s.state.selected_layers.iter().filter_map(|l| c.layer(*l)).any(|l| matches!(l.source, LayerSource::Comp { .. })) {
Ok(())
} else {
Err("select a precomposition layer".into())
}
}
pub fn specs() -> Vec<CommandSpec> {
vec![
query!("markers.list", "List Markers", "{layer? (omit for composition markers)}", list),
cmd!(
"markers.set",
"Marker Settings",
[],
None,
"{layer? (omit: comp marker), index? (0-based) | at? (comp s) | new?: true, time? (comp s), duration? (s), comment?, chapter?, url?, frameTarget?, cuePoint?: {name, navigation?, params?: [[name, value]…]} | null, protected?, label?}",
has_comp,
set
),
cmd!("markers.delete", "Delete Marker", [], None, "{layer?, index? | at? (comp s)}", has_comp, delete),
cmd!(
"markers.convert",
"Convert Marker",
[],
None,
"{layer? (layer marker → comp marker), index? | at?, toLayer? (comp marker → layer marker)}",
has_comp,
convert
),
cmd!("layer.updateMarkersFromSource", "Update Markers From Source", ["Layer", "Markers"], None, "{layers?}", has_precomp_layer, update_from_source),
]
}
+4
View File
@@ -2,6 +2,7 @@
//! shortcut and viewer/timeline gesture maps to one of these.
mod anim;
pub mod anim_tools;
mod animation;
mod comp;
mod comp_more;
@@ -16,6 +17,7 @@ mod layer_menu;
mod layer_time;
mod link;
mod lottie;
mod markers;
mod mask;
pub mod paint;
mod paths;
@@ -95,7 +97,9 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(layer_time::specs());
v.extend(prop::specs());
v.extend(anim::specs());
v.extend(anim_tools::specs());
v.extend(link::specs());
v.extend(markers::specs());
v.extend(mask::specs());
v.extend(paths::specs());
v.extend(effect::specs());
-1
View File
@@ -37,7 +37,6 @@ pub fn specs() -> Vec<CommandSpec> {
// Time (timeline milestone).
stub!("layer.alignVideoToData", "Align Video to Data", ["Layer", "Time"], "{}"),
stub!("layer.environment", "Environment Layer", ["Layer"], "{}"),
stub!("layer.updateMarkersFromSource", "Update Markers From Source", ["Layer", "Markers"], "{}"),
stub!("layer.create", "Create", [], "{op}"),
stub!("layer.autoTrace", "Auto-trace...", ["Layer"], "{}"),
stub!("layer.sceneEditDetection", "Scene Edit Detection...", ["Layer"], "{}"),
+4
View File
@@ -518,12 +518,16 @@ mod tests;
#[cfg(test)]
mod tests_3d;
#[cfg(test)]
mod tests_anim_tools;
#[cfg(test)]
mod tests_effects;
#[cfg(test)]
mod tests_fidelity;
#[cfg(test)]
mod tests_lottie;
#[cfg(test)]
mod tests_markers;
#[cfg(test)]
mod tests_menu_cmds;
#[cfg(test)]
mod tests_settings;
+113
View File
@@ -0,0 +1,113 @@
//! Wiggler, Smoother and Motion Sketch (`keys.wiggle`, `keys.smooth`, `motion.sketch`).
use effectcraft_keyframe::evaluate;
use serde_json::json;
use crate::tests_timeline::{animate, prop, setup};
fn select(s: &mut crate::Session, layer: u64, path: &str) {
s.execute("prop.select", json!({"layer": layer, "path": path})).unwrap();
}
#[test]
fn wiggle_adds_keys_at_frequency_within_magnitude() {
let (mut s, l) = setup();
animate(&mut s, l, "transform/position", &[(0.0, json!([100, 100])), (2.0, json!([300, 100]))]);
let orig = prop(&s, l, "transform/position");
select(&mut s, l, "transform/position");
let opts = json!({"apply": "spatial", "noise": "jagged", "dimensions": "independent", "frequency": 5, "magnitude": 20, "seed": 7});
let r = s.execute("keys.wiggle", opts.clone()).unwrap();
let p = prop(&s, l, "transform/position");
// 2 s at 5 keys/s: 9 keys between the two originals (one every 6 frames at 30 fps).
assert_eq!(p.keys.len(), 11, "{r}");
assert_eq!(r["after"], 11);
let step = p.keys[2].time - p.keys[1].time;
assert!((step.seconds() - 0.2).abs() < 1e-9);
for k in &p.keys[1..10] {
let base = evaluate(&orig.keys, k.time, true).unwrap().as_vec2();
let v = k.value.as_vec2();
assert!((v[0] - base[0]).abs() <= 20.0 + 1e-9 && (v[1] - base[1]).abs() <= 20.0 + 1e-9, "{v:?} vs {base:?}");
}
assert!(p.keys[1..10].iter().any(|k| (k.value.as_vec2()[1] - 100.0).abs() > 1.0), "noise was applied");
// End keys untouched; deterministic for the same seed; undo restores.
assert_eq!(p.keys[0].value, orig.keys[0].value);
assert_eq!(p.keys[10].value, orig.keys[1].value);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(prop(&s, l, "transform/position").keys.len(), 2);
select(&mut s, l, "transform/position");
s.execute("keys.wiggle", opts).unwrap();
assert_eq!(prop(&s, l, "transform/position").keys, p.keys);
}
#[test]
fn wiggle_one_dimension_and_smooth_noise() {
let (mut s, l) = setup();
animate(&mut s, l, "transform/position", &[(0.0, json!([100, 100])), (1.0, json!([100, 100]))]);
select(&mut s, l, "transform/position");
s.execute("keys.wiggle", json!({"dimensions": "one", "dimension": 1, "frequency": 10, "magnitude": 50})).unwrap();
let p = prop(&s, l, "transform/position");
assert_eq!(p.keys.len(), 11);
for k in &p.keys {
let v = k.value.as_vec2();
assert!((v[0] - 100.0).abs() < 1e-9);
assert!((v[1] - 100.0).abs() <= 50.0);
}
// Opacity (non-spatial): the temporal path deviates the value.
animate(&mut s, l, "transform/opacity", &[(0.0, json!(50)), (1.0, json!(50))]);
select(&mut s, l, "transform/opacity");
s.execute("keys.wiggle", json!({"apply": "temporal", "frequency": 4, "magnitude": 10})).unwrap();
let o = prop(&s, l, "transform/opacity");
assert!(o.keys.len() >= 5);
assert!(o.keys.iter().all(|k| (k.value.as_f64() - 50.0).abs() <= 10.0));
assert!(s.execute("keys.wiggle", json!({"noise": "wobbly"})).is_err());
}
#[test]
fn smoother_reduces_keys_within_tolerance() {
let (mut s, l) = setup();
// A ramp keyed every frame with a little jitter.
let keys: Vec<(f64, serde_json::Value)> = (0..=60).map(|f| (f as f64 / 30.0, json!(f as f64 * 1.5 + if f % 2 == 0 { 0.2 } else { -0.2 }))).collect();
animate(&mut s, l, "transform/opacity", &keys);
let orig = prop(&s, l, "transform/opacity");
assert_eq!(orig.keys.len(), 61);
select(&mut s, l, "transform/opacity");
let r = s.execute("keys.smooth", json!({"tolerance": 1.0})).unwrap();
let p = prop(&s, l, "transform/opacity");
assert!(p.keys.len() < 10, "{} keys ({r})", p.keys.len());
for f in 0..=60 {
let t = s.active_comp().unwrap().frame_rate.tick_of(f);
let a = evaluate(&orig.keys, t, false).unwrap().as_f64();
let b = evaluate(&p.keys, t, false).unwrap().as_f64();
assert!((a - b).abs() <= 1.0 + 1e-6, "frame {f}: {a} vs {b}");
}
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(prop(&s, l, "transform/opacity").keys.len(), 61);
}
#[test]
fn motion_sketch_records_position_keys() {
let (mut s, l) = setup();
// 1 s of capture: a straight line from (0,0) to (300,150), sampled every 0.1 s.
let pts: Vec<serde_json::Value> = (0..=10).map(|i| json!([i as f64 * 0.1, i as f64 * 30.0, i as f64 * 15.0])).collect();
let r = s.execute("motion.sketch", json!({"layer": l, "points": pts, "start": 0.5, "smoothing": 0})).unwrap();
let p = prop(&s, l, "transform/position");
assert_eq!(r["keys"], 31);
assert_eq!(p.keys.len(), 31);
assert_eq!(p.keys[0].time.seconds(), 0.5);
assert_eq!(p.keys[0].value.as_vec2(), [0.0, 0.0]);
let last = p.keys[30].value.as_vec2();
assert!((last[0] - 300.0).abs() < 1e-6 && (last[1] - 150.0).abs() < 1e-6);
// Smoothing collapses the straight line to (almost) its end points; 200 % capture speed
// plays back over twice the time.
s.execute("edit.undo", json!({})).unwrap();
s.execute("motion.sketch", json!({"layer": l, "points": pts, "start": 0, "smoothing": 2, "captureSpeed": 200})).unwrap();
let p = prop(&s, l, "transform/position");
assert!(p.keys.len() <= 4, "{}", p.keys.len());
assert!((p.keys.last().unwrap().time.seconds() - 2.0).abs() < 1e-9);
// [x, y] points: one per frame.
s.execute("motion.sketch", json!({"layer": l, "points": [[0, 0], [10, 0], [20, 0]], "start": 3, "smoothing": 0})).unwrap();
let p = prop(&s, l, "transform/position");
let t = s.active_comp().unwrap().frame_rate.tick_of(92);
assert!(p.keys.iter().any(|k| k.time == t && k.value.as_vec2() == [20.0, 0.0]));
assert!(s.execute("motion.sketch", json!({"layer": l, "points": [[1, 2]]})).is_err());
}
+149
View File
@@ -0,0 +1,149 @@
//! Composition / layer markers: dialog fields, move, duration, delete, convert, update from
//! source, all with undo.
use serde_json::json;
use crate::tests_timeline::setup;
#[test]
fn comp_marker_dialog_fields_and_undo() {
let (mut s, _) = setup();
s.execute("time.set", json!({"time": 1.0})).unwrap();
s.execute("comp.addMarker", json!({"comment": "a"})).unwrap();
let r = s
.execute(
"markers.set",
json!({"index": 0, "time": 1.51, "duration": 0.5, "comment": "Intro", "chapter": "One", "url": "https://getartcraft.com", "frameTarget": "_blank",
"cuePoint": {"name": "cue", "navigation": true, "params": [["k", "v"]]}, "protected": true, "label": "Aqua"}),
)
.unwrap();
assert_eq!(r["index"], 0);
let l = s.execute("markers.list", json!({})).unwrap();
let m = &l[0];
// Snapped to whole frames (30 fps).
assert!((m["time"].as_f64().unwrap() - 1.5).abs() < 1e-9, "{m}");
assert!((m["duration"].as_f64().unwrap() - 0.5).abs() < 1e-9);
assert_eq!(m["comment"], "Intro");
assert_eq!(m["chapter"], "One");
assert_eq!(m["url"], "https://getartcraft.com");
assert_eq!(m["frameTarget"], "_blank");
assert_eq!(m["cuePoint"]["name"], "cue");
assert_eq!(m["cuePoint"]["navigation"], true);
assert_eq!(m["cuePoint"]["params"][0][1], "v");
assert_eq!(m["protected"], true);
assert_eq!(m["label"], "Aqua");
s.execute("edit.undo", json!({})).unwrap();
let l = s.execute("markers.list", json!({})).unwrap();
assert_eq!(l[0]["comment"], "a");
assert_eq!(l[0]["time"], 1.0);
s.execute("edit.redo", json!({})).unwrap();
// Find by time, clear the cue point, delete with undo.
s.execute("markers.set", json!({"at": 1.5, "cuePoint": null})).unwrap();
assert!(s.execute("markers.list", json!({})).unwrap()[0]["cuePoint"].is_null());
s.execute("markers.delete", json!({"at": 1.5})).unwrap();
assert_eq!(s.execute("markers.list", json!({})).unwrap().as_array().unwrap().len(), 0);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.execute("markers.list", json!({})).unwrap().as_array().unwrap().len(), 1);
assert!(s.execute("markers.set", json!({"index": 5, "comment": "x"})).is_err());
}
#[test]
fn drag_merges_into_one_undo_step_and_markers_stay_sorted() {
let (mut s, _) = setup();
for t in [0.5, 2.0] {
s.execute("markers.set", json!({"new": true, "time": t})).unwrap();
}
let before = s.history.undo.len();
// A drag: several moves merged under one key; passing the other marker re-sorts.
let mut idx = 0;
for t in [1.0, 1.5, 2.5] {
idx = s.execute("markers.set", json!({"index": idx, "time": t, "merge": "mk-drag"})).unwrap()["index"].as_u64().unwrap();
}
assert_eq!(idx, 1);
assert_eq!(s.history.undo.len(), before + 1);
let l = s.execute("markers.list", json!({})).unwrap();
assert_eq!(l[0]["time"], 2.0);
assert_eq!(l[1]["time"], 2.5);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.execute("markers.list", json!({})).unwrap()[0]["time"], 0.5);
}
#[test]
fn layer_markers_convert_and_update_from_source() {
let (mut s, l) = setup();
// Layer starts at 1 s: layer markers are stored in layer time but addressed in comp time.
s.execute("layer.timing", json!({"layers": [l], "start": 1.0})).unwrap();
s.execute("markers.set", json!({"layer": l, "new": true, "time": 2.0, "comment": "hit"})).unwrap();
let c = s.active_comp().unwrap();
let lay = c.layer(effectcraft_project::LayerId(l)).unwrap();
assert_eq!(lay.markers[0].time.seconds(), 1.0);
assert_eq!(s.execute("markers.list", json!({"layer": l})).unwrap()[0]["time"], 2.0);
// Layer → comp marker keeps the comp time.
s.execute("markers.convert", json!({"layer": l, "index": 0})).unwrap();
assert_eq!(s.execute("markers.list", json!({})).unwrap()[0]["time"], 2.0);
assert_eq!(s.execute("markers.list", json!({"layer": l})).unwrap().as_array().unwrap().len(), 0);
// And back.
s.execute("markers.convert", json!({"index": 0, "toLayer": l})).unwrap();
assert_eq!(s.execute("markers.list", json!({"layer": l})).unwrap()[0]["comment"], "hit");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.execute("markers.list", json!({})).unwrap().as_array().unwrap().len(), 1);
// Locked markers refuse edits.
s.execute("layer.markersLock", json!({"layers": [l], "value": true})).unwrap();
assert!(s.execute("markers.set", json!({"layer": l, "new": true})).is_err());
s.execute("layer.markersLock", json!({"layers": [l], "value": false})).unwrap();
// Update Markers From Source on a precomp layer.
let r = s.execute("layer.precompose", json!({"layers": [l], "name": "Inner"})).unwrap();
let inner = r["comp"].as_u64().unwrap();
let outer_layer = r["layer"].as_u64().unwrap();
s.execute("markers.set", json!({"comp": inner, "new": true, "time": 0.5, "comment": "src"})).unwrap();
s.execute("layer.select", json!({"layers": [outer_layer]})).unwrap();
let r = s.execute("layer.updateMarkersFromSource", json!({})).unwrap();
assert_eq!(r["added"], 1);
let lm = s.execute("markers.list", json!({"layer": outer_layer})).unwrap();
assert!(lm.as_array().unwrap().iter().any(|m| m["comment"] == "src"));
// Idempotent; undoable.
assert_eq!(s.execute("layer.updateMarkersFromSource", json!({})).unwrap()["added"], 0);
s.execute("edit.undo", json!({})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert!(!s.execute("markers.list", json!({"layer": outer_layer})).unwrap().as_array().unwrap().iter().any(|m| m["comment"] == "src"));
}
#[test]
fn precompose_leave_and_move_attributes() {
use effectcraft_project::{ItemId, LayerId, LayerSource};
let (mut s, l) = setup();
s.execute("prop.set", json!({"layer": l, "path": "transform/position", "value": [50, 60]})).unwrap();
let outer = s.active_comp_id().unwrap();
// Leave all attributes: same layer, keeps its transform; the new comp is the source size and
// holds a default layer of the original source.
let r = s.execute("layer.precompose", json!({"layers": [l], "name": "Leave", "mode": "leave"})).unwrap();
assert_eq!(r["layer"], l);
let inner = ItemId(r["comp"].as_u64().unwrap());
let lay = s.project.comp(outer).unwrap().layer(LayerId(l)).unwrap().clone();
assert_eq!(lay.source, LayerSource::Comp { item: inner });
assert_eq!(lay.props.prop("transform/position").unwrap().value.as_vec2(), [50.0, 60.0]);
let ic = s.project.comp(inner).unwrap();
assert_eq!((ic.width, ic.height), (100, 100));
assert_eq!(ic.layers.len(), 1);
assert_eq!(ic.layers[0].props.prop("transform/position").unwrap().value.as_vec2(), [50.0, 50.0]);
assert!(matches!(ic.layers[0].source, LayerSource::Solid { .. }));
s.execute("edit.undo", json!({})).unwrap();
assert!(s.project.comp(inner).is_none());
assert!(matches!(s.project.comp(outer).unwrap().layer(LayerId(l)).unwrap().source, LayerSource::Solid { .. }));
// Leave needs one layer with a source item.
let t = s.execute("layer.newText", json!({"text": "Hi"})).unwrap()["layer"].as_u64().unwrap();
assert!(s.execute("layer.precompose", json!({"layers": [t], "mode": "leave"})).is_err());
assert!(s.execute("layer.precompose", json!({"layers": [t, l], "mode": "leave"})).is_err());
// Move all attributes + adjust duration + open: the layer moves inside, trimmed to its span.
s.execute("layer.timing", json!({"layers": [l], "in": 1.0, "out": 3.0})).unwrap();
let r = s.execute("layer.precompose", json!({"layers": [l], "name": "Move", "adjustDuration": true, "open": true})).unwrap();
let inner = ItemId(r["comp"].as_u64().unwrap());
let ic = s.project.comp(inner).unwrap();
assert!((ic.duration.seconds() - 2.0).abs() < 1e-9);
assert_eq!(ic.layers[0].props.prop("transform/position").unwrap().value.as_vec2(), [50.0, 60.0]);
assert_eq!(ic.layers[0].in_point.seconds(), 0.0);
let nl = s.project.comp(outer).unwrap().layer(LayerId(r["layer"].as_u64().unwrap())).unwrap().clone();
assert_eq!((nl.in_point.seconds(), nl.out_point.seconds()), (1.0, 3.0));
assert_eq!(s.active_comp_id(), Some(inner));
}