GitCorner

Code

ossartcrafteffectcraft🌐
665bfac0b339
//! Animation menu: animation presets (EffectCraft's own JSON format), Add Keyframe, Keyframe
//! Assistant (Exponential Scale), text animators/selectors, and the
//! Reveal Properties commands.

use std::collections::BTreeMap;

use effectcraft_keyframe::{Interp, Keyframe, Value as KV};
use effectcraft_project::build::{self, Ids};
use effectcraft_project::{GroupKind, Layer, LayerId, LayerSource, Node, Project, PropGroup, Property, Uid};
use effectcraft_time::Tick;
use serde_json::{Value, json};

use super::effect::{effect_time_error, retime_effect};
use super::text_anim::{per_char_on, set_animator_3d};
use super::{CommandSpec, bad, frontend, has_comp, has_keys, has_layers, layer_mut, layers_p, match_path_of, resolve_effect_path, selected_leaf_props, str_p};
use crate::{EngineError, KeyRef, Result, Session, cmd};

/// Preset file format version tag (`*.ecpreset`, JSON).
pub const PRESET_TAG: &str = "effectcraftAnimationPreset";
/// The first preset version that stores effect keys relative to the earliest key (#1971).
const RELATIVE_EFFECT_KEYS: u64 = 2;
/// The first preset version that stores text animators and selectors under `textAnimators`.
const TEXT_ANIMATORS: u64 = 3;

/// The preset format version written under [`PRESET_TAG`]. 4: a property that is a Cineon
/// Converter's Gamma, directly or through Essential Properties, records that Cineon Converter's
/// version in `cineonVersion`; the Gamma properties of version 1 to 3 presets are version 1 Gammas.
pub const PRESET_VERSION: u64 = 4;

fn has_selected_props(s: &Session) -> std::result::Result<(), String> {
    has_comp(s)?;
    if selected_leaf_props(s).is_empty() && selected_effects(s).is_empty() { Err("select properties or effects first".into()) } else { Ok(()) }
}

fn has_text_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| l.props.group("text/animators").is_some()) {
        Ok(())
    } else {
        Err("select a text layer".into())
    }
}

/// Selected effect groups (layer, effect group).
fn selected_effects(s: &Session) -> Vec<(LayerId, PropGroup)> {
    let Some(c) = s.active_comp() else { return vec![] };
    s.state
        .selected_props
        .iter()
        .filter_map(|(l, u)| {
            let layer = c.layer(*l)?;
            let fx = layer.effects()?;
            fx.groups().find(|g| g.uid == *u).map(|g| (*l, g.clone()))
        })
        .collect()
}

/// The text animators that hold a selected property, each once, in stack order. An animator is
/// saved whole: its Properties say what changes and its Selectors where, so neither works alone.
fn selected_animators(s: &Session) -> Vec<PropGroup> {
    let Some(c) = s.active_comp() else { return vec![] };
    let leaves = selected_leaf_props(s);
    let mut layers: Vec<LayerId> = vec![];
    for (lid, _) in &leaves {
        if !layers.contains(lid) {
            layers.push(*lid);
        }
    }
    let mut out = vec![];
    for lid in layers {
        let Some(list) = c.layer(lid).and_then(|l| l.props.group("text/animators")) else { continue };
        out.extend(list.groups().filter(|g| leaves.iter().any(|(l, u)| *l == lid && g.find(*u).is_some())).cloned());
    }
    out
}

/// The earliest key anywhere in `groups`, nested controls included.
fn earliest_key<'a>(groups: impl IntoIterator<Item = &'a PropGroup>) -> Option<Tick> {
    let mut first: Option<Tick> = None;
    for g in groups {
        g.walk("", &mut |_, pr| {
            if let Some(t) = pr.keys.iter().map(|k| k.time).min() {
                first = Some(first.map_or(t, |f| f.min(t)));
            }
        });
    }
    first
}

// ---------------------------------------------------------------- presets

fn save_preset(s: &mut Session, p: &Value) -> Result<Value> {
    let path = str_p(p, "path").ok_or_else(|| bad("anim.savePreset", "missing `path`"))?.to_string();
    s.refuse_export(&path)?;
    let comp = s.active_comp().ok_or(EngineError::NoComp)?;
    let t = s.time();
    let mut effects: Vec<(LayerId, PropGroup)> = selected_effects(s);
    let effect_uids: Vec<Uid> = effects.iter().map(|(_, g)| g.uid).collect();
    let mut animators = selected_animators(s);
    let mut props = vec![];
    for (lid, uid) in selected_leaf_props(s) {
        let Some(l) = comp.layer(lid) else { continue };
        // Properties inside a saved effect travel with the effect.
        if l.effects().is_some_and(|fx| fx.groups().any(|g| effect_uids.contains(&g.uid) && g.find(uid).is_some())) {
            continue;
        }
        // So do properties inside a saved text animator.
        if animators.iter().any(|g| g.find(uid).is_some()) {
            continue;
        }
        let (Some(pr), Some(mp)) = (l.props.find(uid), match_path_of(&l.props, uid)) else { continue };
        let version = cineon_gamma_version(&s.project, l, uid, Some(t), NESTING);
        props.push((l.layer_time(t), mp, pr.clone(), version));
    }
    if props.is_empty() && effects.is_empty() && animators.is_empty() {
        return Err(bad("anim.savePreset", "select properties or effects to save"));
    }
    // Key times are stored relative to the earliest key so the preset applies at the CTI.
    let first = props
        .iter()
        .flat_map(|(_, _, pr, _)| pr.keys.iter().map(|k| k.time))
        .chain(earliest_key(effects.iter().map(|(_, g)| g).chain(&animators)))
        .min()
        .unwrap_or(Tick::ZERO);
    for g in effects.iter_mut().map(|(_, g)| g).chain(&mut animators) {
        retime_effect(g, 1.0, "anim.savePreset", |t| Ok(Tick(t.0.checked_sub(first.0).ok_or_else(|| effect_time_error("anim.savePreset"))?)))?;
    }
    let props_json: Vec<Value> = props
        .iter()
        .map(|(_, mp, pr, version)| {
            let mut pr = pr.clone();
            for k in &mut pr.keys {
                k.time -= first;
            }
            let mut v = json!({"path": mp, "value": pr.value, "keys": pr.keys, "expression": pr.expr});
            if let Some((version, _)) = version {
                v["cineonVersion"] = json!(version);
            }
            v
        })
        .collect();
    let fx_json: Vec<Value> = effects.iter().map(|(_, g)| serde_json::to_value(g).unwrap_or_default()).collect();
    let name = str_p(p, "name")
        .map(str::to_string)
        .unwrap_or_else(|| std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default());
    let doc = json!({PRESET_TAG: PRESET_VERSION, "name": name, "properties": props_json, "effects": fx_json, "textAnimators": animators});
    let text = serde_json::to_string_pretty(&doc).unwrap_or_default();
    s.write_output(&path, text.as_bytes())?;
    Ok(json!({"path": path, "properties": props.len(), "effects": effects.len(), "textAnimators": animators.len()}))
}

/// Rewrite an effect property path in a preset (`effects/<effect id>[#n]/<param>`) to the current
/// parameter id when it names a parameter that the effect has since renamed or moved into a
/// twirl-down group. Any other path comes back unchanged.
fn upgrade_effect_path(path: &str) -> String {
    let Some((seg, tail)) = path.strip_prefix("effects/").and_then(|r| r.split_once('/')) else { return path.to_string() };
    let effect = match seg.rsplit_once('#') {
        Some((m, n)) if !m.is_empty() && n.parse::<usize>().is_ok() => m,
        _ => seg,
    };
    match effectcraft_effects::find(effect).and_then(|spec| effectcraft_effects::migrate::current_param_id(spec, tail)) {
        Some(id) if id != tail => format!("effects/{seg}/{id}"),
        _ => path.to_string(),
    }
}

/// The saved animators of a preset. A file that names one wrongly is refused, not partly applied.
fn preset_animators(doc: &Value) -> Result<Vec<PropGroup>> {
    let bad_file = |why: String| bad("anim.applyPreset", format!("bad text animator in the preset: {why}"));
    match doc.get("textAnimators") {
        None => Ok(vec![]),
        Some(Value::Array(list)) => list
            .iter()
            .map(|v| {
                let g: PropGroup = serde_json::from_value(v.clone()).map_err(|e| bad_file(e.to_string()))?;
                if g.match_id == "animator" { Ok(g) } else { Err(bad_file(format!("`{}` is not an animator", g.match_id))) }
            })
            .collect(),
        Some(_) => Err(bad_file("`textAnimators` is not a list".into())),
    }
}

fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
    let doc: Value = match (p.get("preset"), str_p(p, "path")) {
        (Some(v), _) => v.clone(),
        (None, Some(path)) => {
            let bytes = s.services.read_file(path).map_err(|e| EngineError::Other(format!("cannot read {path}: {e}")))?;
            serde_json::from_slice(&bytes).map_err(|e| bad("anim.applyPreset", format!("not a preset: {e}")))?
        }
        _ => return Err(bad("anim.applyPreset", "missing `path` (or inline `preset`)")),
    };
    if doc.get(PRESET_TAG).is_none() {
        return Err(bad("anim.applyPreset", "not an EffectCraft animation preset"));
    }
    let animators = preset_animators(&doc)?;
    let (cid, ids) = layers_p(s, p)?;
    if ids.is_empty() {
        return Err(bad("anim.applyPreset", "select a layer"));
    }
    let mut effects: Vec<PropGroup> =
        doc["effects"].as_array().map(|a| a.iter().filter_map(|v| serde_json::from_value(v.clone()).ok()).collect()).unwrap_or_default();
    // Older presets stored effect keys at the source layer's times.
    if doc[PRESET_TAG].as_u64().unwrap_or(1) < RELATIVE_EFFECT_KEYS
        && let Some(first) = earliest_key(&effects)
    {
        for g in &mut effects {
            retime_effect(g, 1.0, "anim.applyPreset", |t| Ok(Tick(t.0.checked_sub(first.0).ok_or_else(|| effect_time_error("anim.applyPreset"))?)))?;
        }
    }
    // A Cineon Converter saved before version 2 gets its Version (1), as when a project opens.
    if let Some(spec) = effectcraft_effects::find("ec.utility.cineon") {
        for g in &mut effects {
            if matches!(&g.kind, GroupKind::Effect { effect } if effect == spec.id) {
                // The uids are reassigned when the group is applied.
                let mut next = 0;
                effectcraft_effects::migrate::upgrade_instance(spec, g, &mut Ids(&mut next), [0.0; 2]);
            }
        }
    }
    // The Cineon Converter version of each saved Gamma; a format 1 to 3 preset holds version 1 Gammas.
    let legacy = doc[PRESET_TAG].as_u64().unwrap_or(1) < PRESET_VERSION;
    let props: Vec<(String, Property, Option<f64>)> = doc["properties"]
        .as_array()
        .map(|a| {
            a.iter()
                .filter_map(|v| {
                    let path = upgrade_effect_path(v["path"].as_str()?);
                    let value: KV = serde_json::from_value(v["value"].clone()).ok()?;
                    let keys: Vec<Keyframe> = serde_json::from_value(v["keys"].clone()).unwrap_or_default();
                    let expr = serde_json::from_value(v["expression"].clone()).ok().flatten();
                    let mut pr = Property::new(0, "", "", value);
                    pr.keys = keys;
                    pr.expr = expr;
                    let version = v["cineonVersion"].as_f64().or(legacy.then_some(1.0));
                    Some((path, pr, version))
                })
                .collect()
        })
        .unwrap_or_default();
    // Per layer and property: the version of the Cineon Converter Gammas the property drives
    // through Essential Properties.
    let exposed: Vec<Vec<Option<f64>>> = ids
        .iter()
        .map(|lid| {
            let l = s.project.comp(cid).and_then(|c| c.layer(*lid));
            props
                .iter()
                .map(|(path, _, _)| {
                    let l = l?;
                    let pr = l.props.prop(&resolve_effect_path(l, path))?;
                    cineon_gamma_version(&s.project, l, pr.uid, Some(s.time()), NESTING).and_then(|(v, direct)| (!direct).then_some(v))
                })
                .collect()
        })
        .collect();
    let saved_3d = props.iter().any(|(path, src, _)| path == "text/perChar3d" && src.value.as_bool());
    let t = s.time();
    // Effect bounds per layer size the point defaults of parameters added since the preset was saved.
    let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
    let sizes: BTreeMap<LayerId, [f64; 2]> =
        ids.iter().filter_map(|lid| comp.layer(*lid).map(|l| (*lid, effectcraft_render::effect_bounds(&s.project, comp, l).0))).collect();
    let mut applied = 0;
    let mut skipped = vec![];
    s.edit("Apply Animation Preset", None, |proj, _| {
        let mut next = proj.next_id;
        for (li, lid) in ids.iter().enumerate() {
            let size = sizes.get(lid).copied().unwrap_or([100.0, 100.0]);
            let l = layer_mut(proj, cid, *lid)?;
            let lt = l.layer_time(t);
            let was_three_d = per_char_on(l);
            if let Some(fx) = l.props.sub_mut("effects") {
                for g in &effects {
                    let mut g = g.clone();
                    // Effects saved by an earlier version get the upgrade a project gets on open.
                    let spec = match &g.kind {
                        GroupKind::Effect { effect } => effectcraft_effects::find(effect),
                        _ => None,
                    };
                    if let Some(spec) = spec {
                        effectcraft_effects::migrate::upgrade_instance(spec, &mut g, &mut Ids(&mut next), size);
                    }
                    retime_effect(&mut g, 1.0, "anim.applyPreset", |t| Ok(Tick(t.0.checked_add(lt.0).ok_or_else(|| effect_time_error("anim.applyPreset"))?)))?;
                    g.reassign_uids(&mut next);
                    next += 1;
                    fx.children.push(Node::Group(g));
                    applied += 1;
                }
            }
            for (pi, (path, src, version)) in props.iter().enumerate() {
                // A Gamma of a Cineon Converter whose Version is keyframed is converted to that
                // Version, and skipped when the keys hold more than one version or an expression
                // sets the Version. A preset that holds the Version too sets it.
                let version_path = cineon_version_path(path).filter(|vp| !props.iter().any(|(p, v, _)| p == vp && matches!(v.value, KV::Scalar(_))));
                let keyed = match (version, &version_path) {
                    (Some(_), Some(vp)) => {
                        l.props.prop(&resolve_effect_path(l, vp)).filter(|pr| pr.has_expression() || pr.keys.iter().any(|k| !k.muted)).map(constant_version)
                    }
                    _ => None,
                };
                let target = match keyed {
                    Some(None) => {
                        skipped.push(path.clone());
                        continue;
                    }
                    Some(to) => to,
                    None => exposed[li][pi],
                };
                // An exposed Gamma is converted to the scale of the Cineon Converters it drives.
                // One with an enabled expression is skipped: expressions are applied as saved.
                let rescaled;
                let src = match (version, target) {
                    (Some(from), Some(to)) if *from != to && src.has_expression() => {
                        skipped.push(path.clone());
                        continue;
                    }
                    (Some(from), Some(to)) if *from != to => {
                        let mut c = src.clone();
                        rescale_gamma(&mut c, effectcraft_effects::cineon_gamma_scale(*from) / effectcraft_effects::cineon_gamma_scale(to));
                        rescaled = c;
                        &rescaled
                    }
                    _ => src,
                };
                let resolved = resolve_effect_path(l, path);
                match l.props.prop_mut(&resolved) {
                    Some(pr) if std::mem::discriminant(&pr.value) == std::mem::discriminant(&src.value) => {
                        pr.value = src.value.clone();
                        pr.keys = src
                            .keys
                            .iter()
                            .cloned()
                            .map(|mut k| {
                                k.time += lt;
                                k
                            })
                            .collect();
                        if src.expr.is_some() {
                            pr.expr = src.expr.clone();
                        }
                        applied += 1;
                    }
                    _ => {
                        skipped.push(path.clone());
                        continue;
                    }
                }
                // A Cineon Converter's Gamma sets the instance's Version to the one it was saved
                // with, unless that Version is keyframed or the preset holds it.
                if keyed.is_none()
                    && let (Some(v), Some(vp)) = (version, &version_path)
                    && let Some(pr) = l.props.prop_mut(&resolve_effect_path(l, vp))
                {
                    pr.value = KV::Scalar(*v);
                }
            }
            // After the properties, so a saved Per-character 3D setting counts: it needs a 3D layer
            // to draw, as `layer.enablePerChar3D` makes one. Without it the layer's setting stays.
            // Existing animators follow changes to the saved Per-character 3D setting too.
            let three_d = per_char_on(l);
            l.switches.three_d |= three_d && saved_3d;
            let Some(list) = l.props.group_mut("text/animators") else {
                skipped.extend(animators.iter().map(|g| format!("text/animators/{}", g.name)));
                continue;
            };
            if three_d != was_three_d {
                for existing in &mut list.children {
                    if let Node::Group(existing) = existing {
                        set_animator_3d(&mut Ids(&mut next), existing, three_d);
                    }
                }
            }
            for g in &animators {
                let mut g = g.clone();
                // `reassign_uids` replaces every uid, the ones of properties added here included.
                set_animator_3d(&mut Ids(&mut 0), &mut g, three_d);
                retime_effect(&mut g, 1.0, "anim.applyPreset", |t| Ok(Tick(t.0.checked_add(lt.0).ok_or_else(|| effect_time_error("anim.applyPreset"))?)))?;
                g.reassign_uids(&mut next);
                next += 1;
                list.children.push(Node::Group(g));
                applied += 1;
            }
        }
        // Without this, a preset that fits no layer does nothing and says nothing.
        if applied == 0 && !skipped.is_empty() {
            let legacy_text = doc[PRESET_TAG].as_u64().unwrap_or(1) < TEXT_ANIMATORS && props.iter().any(|(path, _, _)| path.starts_with("text/animators/"));
            let message = if legacy_text {
                "nothing in this preset fits the layer. A text animation preset saved by an earlier version only updates animators a layer already has: save it again"
            } else {
                "nothing in this preset fits the selected layer(s)"
            };
            return Err(bad("anim.applyPreset", message));
        }
        proj.next_id = next;
        Ok(())
    })?;
    // Animation ▸ Recent Animation Presets.
    if let Some(path) = str_p(p, "path") {
        s.prefs.push_recent_preset(path);
        s.save_prefs();
        s.prefs_revision += 1;
    }
    Ok(json!({"applied": applied, "skipped": skipped}))
}

/// The preset path of the Version of the Cineon Converter whose Gamma is at preset path `path`
/// (`effects/<match name>[#n]/gamma`, as [`match_path_of`] writes it).
fn cineon_version_path(path: &str) -> Option<String> {
    let (seg, tail) = path.strip_prefix("effects/")?.split_once('/')?;
    (seg.rsplit_once('#').map_or(seg, |(m, _)| m) == "ec.utility.cineon" && tail == "gamma").then(|| format!("effects/{seg}/version"))
}

/// How many nested comps [`cineon_gamma_version`] follows Essential Properties through.
const NESTING: u32 = 16;

/// The version of the Cineon Converter whose Gamma property `uid` of `l` is, and whether that
/// Cineon Converter is on `l`. With `t`, a keyframed Version is read at comp time `t`; without
/// it, a Version whose keyframes hold more than one value has no version. A Version that an
/// expression sets has none either. An Essential
/// Properties value of a precomp layer counts when its control drives only Cineon Converter
/// Gammas of one version, in the nested comp or, through further Essential Properties, in comps
/// up to `depth` levels deeper.
fn cineon_gamma_version(p: &Project, l: &Layer, uid: Uid, t: Option<Tick>, depth: u32) -> Option<(f64, bool)> {
    let direct = l.effects().and_then(|fx| {
        fx.groups().find(|g| matches!(&g.kind, GroupKind::Effect { effect } if effect == "ec.utility.cineon") && g.get("gamma").is_some_and(|pr| pr.uid == uid))
    });
    if let Some(g) = direct {
        let Some(pr) = g.get("version") else { return Some((1.0, true)) };
        if pr.has_expression() {
            return None;
        }
        let version = match t {
            Some(t) => pr.value_at(l.layer_time(t)).as_f64(),
            None => constant_version(pr)?,
        };
        return Some((version, true));
    }
    let LayerSource::Comp { item } = l.source else { return None };
    let depth = depth.checked_sub(1)?;
    let ctl = effectcraft_project::essential::group(l)?.find(uid).and_then(|pr| effectcraft_project::essential::control_of(&pr.match_id))?;
    let c = p.comp(item)?;
    let mut version = None;
    for (lid, target) in c.essential.as_ref()?.resolve(ctl)?.kind.targets() {
        let (v, _) = cineon_gamma_version(p, c.layer(lid)?, target, None, depth)?;
        if version.is_some_and(|x| x != v) {
            return None;
        }
        version = Some(v);
    }
    version.map(|v| (v, false))
}

/// The value a Cineon Converter's Version holds at every time: its value without keyframes
/// that play, and none when the keyframes that play hold more than one value or ease with a
/// speed that moves the value between them, or when an expression sets it.
fn constant_version(pr: &Property) -> Option<f64> {
    if pr.has_expression() {
        return None;
    }
    let keys: Vec<&Keyframe> = pr.keys.iter().filter(|k| !k.muted).collect();
    let first = keys.first().map_or_else(|| pr.value.as_f64(), |k| k.value.as_f64());
    let still = |interp: Interp, eases: &[effectcraft_keyframe::Ease]| interp != Interp::Bezier || eases.iter().all(|e| e.speed == 0.0);
    let eases_between =
        keys.windows(2).any(|w| w[0].out_interp != Interp::Hold && (!still(w[0].out_interp, &w[0].out_ease) || !still(w[1].in_interp, &w[1].in_ease)));
    (keys.iter().all(|k| k.value.as_f64() == first) && !eases_between).then_some(first)
}

/// Multiplies a Gamma value, its keyframes and their speeds by `f`.
fn rescale_gamma(pr: &mut Property, f: f64) {
    if let KV::Scalar(x) = &mut pr.value {
        *x *= f;
    }
    for k in &mut pr.keys {
        if let KV::Scalar(x) = &mut k.value {
            *x *= f;
        }
        for e in k.in_ease.iter_mut().chain(k.out_ease.iter_mut()) {
            e.speed *= f;
        }
    }
}

// ---------------------------------------------------------------- keyframes

fn add_keyframe(s: &mut Session, _: &Value) -> Result<Value> {
    let targets = selected_leaf_props(s);
    if targets.is_empty() {
        return Err(bad("anim.addKeyframe", "select properties first"));
    }
    let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
    let t = s.time();
    let n = s.edit("Add Keyframe", None, |proj, state| {
        let mut n = 0;
        for (lid, uid) in &targets {
            let l = layer_mut(proj, cid, *lid)?;
            let lt = l.layer_time(t);
            let Some(pr) = l.props.find_mut(*uid) else { continue };
            if pr.static_only {
                continue;
            }
            if pr.keys.is_empty() {
                pr.set_animated(true, lt);
            } else {
                let v = pr.value_at(lt);
                pr.set_value_at(lt, v);
            }
            n += 1;
            if pr.match_id == "type" {
                super::prop::sync_polystar_property(proj, state, cid, *lid, *uid, t)?;
            }
        }
        Ok(n)
    })?;
    Ok(json!({"keys": n}))
}

/// Selected keys grouped by (layer, property).
fn keys_by_prop(s: &Session) -> BTreeMap<(LayerId, Uid), Vec<Tick>> {
    let mut m: BTreeMap<(LayerId, Uid), Vec<Tick>> = BTreeMap::new();
    let Some(comp) = s.active_comp() else { return m };
    for k in super::prop::editable_keys(comp, &s.state.selected_keys) {
        m.entry((k.layer, k.prop)).or_default().push(k.time);
    }
    m
}

fn exponential_scale(s: &mut Session, _: &Value) -> Result<Value> {
    let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
    let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
    let fd = comp.frame_duration();
    let groups = keys_by_prop(s);
    let mut done = 0;
    let mut work = vec![];
    for ((lid, uid), mut times) in groups {
        let Some(l) = comp.layer(lid) else { continue };
        if l.transform().and_then(|tr| tr.get("scale")).map(|p| p.uid) != Some(uid) {
            continue;
        }
        times.sort();
        if times.len() >= 2 {
            work.push((lid, uid, times[0], *times.last().unwrap_or(&times[0])));
        }
    }
    if work.is_empty() {
        return Err(bad("keys.exponentialScale", "select two Scale keyframes"));
    }
    s.edit("Exponential Scale", None, |proj, st| {
        for (lid, uid, a, b) in &work {
            let l = layer_mut(proj, cid, *lid)?;
            let Some(pr) = l.props.find_mut(*uid) else { continue };
            let (va, vb) = (pr.value_at(*a).as_vec3(), pr.value_at(*b).as_vec3());
            pr.keys.retain(|k| k.time <= *a || k.time >= *b);
            let n = ((*b - *a).0 / fd.0.max(1)).max(1);
            for i in 0..=n {
                let u = i as f64 / n as f64;
                let t = if i == n { *b } else { *a + Tick(fd.0 * i) };
                let f = |x: f64, y: f64| if x.abs() < 1e-9 || y.abs() < 1e-9 || x.signum() != y.signum() { x + (y - x) * u } else { x * (y / x).powf(u) };
                let v = [f(va[0], vb[0]), f(va[1], vb[1]), f(va[2], vb[2])];
                let mut k = Keyframe::new(t, KV::Vec3(v));
                k.in_interp = Interp::Linear;
                k.out_interp = Interp::Linear;
                effectcraft_keyframe::set_key(&mut pr.keys, k);
                st.selected_keys.push(KeyRef { layer: *lid, prop: *uid, time: t });
            }
            done += 1;
        }
        st.selected_keys.sort_by_key(|k| (k.layer.0, k.prop, k.time));
        st.selected_keys.dedup();
        Ok(())
    })?;
    Ok(json!({"properties": done}))
}

// ---------------------------------------------------------------- text animators

/// Animation ▸ Add Text Selector ▸ Range / Wiggly / Expression (see `layer.addTextSelector`).
fn add_selector(s: &mut Session, p: &Value) -> Result<Value> {
    super::text_anim::add_selector(s, p)
}

fn remove_all_animators(s: &mut Session, p: &Value) -> Result<Value> {
    let (cid, ids) = layers_p(s, p)?;
    s.edit("Remove All Text Animators", None, |proj, _| {
        for lid in &ids {
            if let Some(a) = layer_mut(proj, cid, *lid)?.props.group_mut("text/animators") {
                a.children.clear();
            }
        }
        Ok(())
    })?;
    Ok(Value::Null)
}

// ---------------------------------------------------------------- reveal

/// Whether a static property differs from the value a fresh layer would have. Transform
/// defaults depend on the source size and comp size.
fn modified(pr: &Property, group: &str, default_anchor: [f64; 2], comp_center: [f64; 2]) -> bool {
    if pr.is_animated() || pr.expr.is_some() {
        return true;
    }
    let v = &pr.value;
    let near = |a: &[f64], b: &[f64]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-6);
    match (group, pr.match_id.as_str()) {
        ("transform", "anchor") => !near(&v.as_vec2(), &default_anchor),
        ("transform", "position") => !near(&v.as_vec2(), &comp_center) || v.as_vec3()[2].abs() > 1e-6,
        // Separate Dimensions: X and Y Position default to the comp centre.
        ("transform", "positionX") => (v.as_f64() - comp_center[0]).abs() > 1e-6,
        ("transform", "positionY") => (v.as_f64() - comp_center[1]).abs() > 1e-6,
        ("transform", "scale") => !near(&v.as_vec3(), &[100.0; 3]),
        ("transform", "opacity") => (v.as_f64() - 100.0).abs() > 1e-6,
        ("transform", "orientation") => !near(&v.as_vec3(), &[0.0; 3]),
        ("transform", _) => v.as_f64().abs() > 1e-6,
        _ => false,
    }
}

/// The group a fresh layer of `l`'s kind (`fresh`) has in place of `top`, for the groups whose
/// defaults are fixed: Audio, Material / Geometry / Camera / Light Options, a text layer's Path
/// and More Options, and a camera's or light's Transform (whose defaults aren't a 2D layer's).
fn default_group(top: &PropGroup, l: &Layer, fresh: &Layer) -> Option<PropGroup> {
    let mut next = 0;
    let mut ids = Ids(&mut next);
    let camera_or_light = matches!(l.source, LayerSource::Camera | LayerSource::Light { .. });
    let mut g = match top.match_id.as_str() {
        "transform" if !camera_or_light => return None,
        // Added to a layer after it is made (a source with audio, an Advanced 3D comp).
        "audio" => build::audio(&mut ids),
        "geometryOptions" if matches!(l.source, LayerSource::Text | LayerSource::Shape) => build::extrusion_geometry_options(&mut ids),
        "transform" | "cameraOptions" | "lightOptions" | "materialOptions" | "geometryOptions" | "text" => fresh.props.sub(&top.match_id)?.clone(),
        _ => return None,
    };
    match top.match_id.as_str() {
        // Source Text and the animators are the layer's content, not options with a default.
        "text" => g.children.retain(|c| matches!(c.match_id(), "pathOptions" | "moreOptions")),
        // A model's scale and clip come from its file.
        "geometryOptions" if matches!(l.source, LayerSource::Model { .. }) => g.children.retain(|c| !matches!(c.match_id(), "unitScale" | "animation")),
        _ => {}
    }
    Some(g)
}

/// Static properties of `g` whose value differs from the same property of `default` (matched by
/// match id; properties `default` lacks have no known default and are left out).
fn changed_from(g: &PropGroup, default: &PropGroup, out: &mut Vec<Uid>) {
    for c in &g.children {
        match c {
            Node::Prop(pr) => {
                if default.get(&pr.match_id).is_some_and(|d| d.value != pr.value) && !out.contains(&pr.uid) {
                    out.push(pr.uid);
                }
            }
            Node::Group(sg) => {
                if let Some(d) = default.sub(&sg.match_id) {
                    changed_from(sg, d, out);
                }
            }
        }
    }
}

/// What of effect group `g` differs from `new`, a new instance of the effect: parameters with
/// another value, and in full the groups a new instance lacks (puppet meshes and pins, paint
/// strokes: what the user made).
fn effect_changes(g: &PropGroup, new: &PropGroup, out: &mut Vec<Uid>) {
    for c in &g.children {
        match c {
            Node::Prop(pr) => {
                if new.get(&pr.match_id).is_some_and(|d| d.value != pr.value) && !out.contains(&pr.uid) {
                    out.push(pr.uid);
                }
            }
            Node::Group(sg) => match new.sub(&sg.match_id) {
                Some(d) => effect_changes(sg, d, out),
                None => out.push(sg.uid),
            },
        }
    }
}

fn reveal(s: &mut Session, p: &Value) -> Result<Value> {
    let kind = str_p(p, "kind").unwrap_or("keyframes").to_string();
    let cid = super::comp_id(s, p)?;
    let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
    let layers: Vec<LayerId> = if s.state.selected_layers.is_empty() { comp.layers.iter().map(|l| l.id).collect() } else { s.state.selected_layers.clone() };
    let mut out = vec![];
    for lid in &layers {
        let Some(l) = comp.layer(*lid) else { continue };
        let (w, h) = effectcraft_render::source_size(&s.project, l);
        let anchor = [w as f64 / 2.0, h as f64 / 2.0];
        let center = [comp.width as f64 / 2.0, comp.height as f64 / 2.0];
        // Properties at the top of the layer's tree (Time Remap): enabled time remapping is a
        // modification in itself, so it reveals even with no keys left on it (#990).
        for pr in l.props.props() {
            let hit = match kind.as_str() {
                "keyframes" => pr.is_animated() || pr.match_id == "timeRemap",
                "animation" => pr.is_animated() || pr.has_expression() || pr.match_id == "timeRemap",
                _ => pr.match_id == "timeRemap" || modified(pr, "", anchor, center),
            };
            if hit {
                out.push(json!({"layer": lid.0, "prop": pr.uid}));
            }
        }
        // Modified: a fresh layer of the same kind gives the defaults to compare against.
        let fresh = (kind == "modified").then(|| build::layer(&mut Project::default(), comp, "", l.source.clone(), (w, h), None));
        let camera_or_light = matches!(l.source, LayerSource::Camera | LayerSource::Light { .. });
        for top in l.props.groups() {
            let hit = |pr: &Property| match kind.as_str() {
                "keyframes" => pr.is_animated(),
                "animation" => pr.is_animated() || pr.has_expression(),
                // A camera's or light's Transform is compared with a fresh one's below.
                _ if camera_or_light && top.match_id == "transform" => pr.is_animated() || pr.expr.is_some(),
                _ => modified(pr, &top.match_id, anchor, center),
            };
            let mut found = vec![];
            top.walk("", &mut |_, pr| {
                if hit(pr) {
                    found.push(pr.uid);
                }
            });
            // Modified: masks count as modifications in full (AE reveals them).
            if kind == "modified" && top.match_id == "masks" {
                for g in top.groups() {
                    found.push(g.uid);
                }
            }
            // Modified: an effect's parameters that differ from a new instance's.
            if kind == "modified" && top.match_id == "effects" {
                let size = effectcraft_render::effect_bounds(&s.project, comp, l).0;
                for g in top.groups() {
                    let spec = match &g.kind {
                        GroupKind::Effect { effect } => effectcraft_effects::find(effect),
                        _ => None,
                    };
                    // A missing plug-in's defaults aren't known: the effect shows in full.
                    let Some(spec) = spec else {
                        found.push(g.uid);
                        continue;
                    };
                    let mut next = 0;
                    let new = effectcraft_effects::instantiate(spec, &mut Ids(&mut next), "", size);
                    effect_changes(g, &new, &mut found);
                }
            }
            if kind == "modified" && top.match_id == "text" {
                for g in top.group("animators").into_iter().flat_map(|a| a.groups()) {
                    found.push(g.uid);
                }
            }
            if let Some(fresh) = &fresh {
                if let Some(default) = default_group(top, l, fresh) {
                    changed_from(top, &default, &mut found);
                }
                // Every layer style counts in full, like an effect; so does each overridden
                // Essential Property.
                if top.match_id == effectcraft_project::styles::GROUP {
                    found.extend(top.groups().filter(|g| g.match_id != effectcraft_project::styles::BLENDING).map(|g| g.uid));
                }
                if let GroupKind::Essential { overridden } = &top.kind {
                    for u in overridden {
                        if !found.contains(u) && (top.find(*u).is_some() || top.find_group(*u).is_some()) {
                            found.push(*u);
                        }
                    }
                }
            }
            out.extend(found.into_iter().map(|u| json!({"layer": lid.0, "prop": u})));
        }
    }
    let layers: Vec<u64> = layers.iter().map(|l| l.0).collect();
    frontend(s, "timeline.revealProps", &json!({"props": out, "kind": kind, "layers": layers}))?;
    Ok(json!({"props": out}))
}

/// Is `g` an effect/mask group kind (used by tests).
#[allow(dead_code)]
pub(crate) fn is_indexed(g: &PropGroup) -> bool {
    matches!(g.kind, GroupKind::Indexed | GroupKind::Mask { .. } | GroupKind::Effect { .. })
}

pub fn specs() -> Vec<CommandSpec> {
    vec![
        cmd!(
            "anim.savePreset",
            "Save Animation Preset...",
            ["Animation"],
            None,
            "{path (.ecpreset), name?} — saves the selected properties/effects; a text animator with a selected property is saved whole",
            has_selected_props,
            save_preset
        ),
        cmd!(
            "anim.applyPreset",
            "Apply Animation Preset...",
            ["Animation"],
            None,
            "{path | preset, layers?} — saved effects and text animators are added to each layer, with their keys at the CTI",
            has_layers,
            apply_preset
        ),
        cmd!("anim.addKeyframe", "Add Keyframe", ["Animation"], None, "{} — keys the selected properties at the CTI", has_selected_props, add_keyframe),
        cmd!(
            "keys.exponentialScale",
            "Exponential Scale",
            ["Animation", "Keyframe Assistant"],
            None,
            "{} — two selected Scale keys",
            has_keys,
            exponential_scale
        ),
        cmd!(
            "text.addSelector",
            "Add Text Selector",
            [],
            None,
            "{layer?, animator?: uid|index (1-based; a uid match wins over an index), kind: range|wiggly|expression}",
            has_text_layer,
            add_selector
        ),
        cmd!("text.removeAllAnimators", "Remove All Text Animators", ["Animation"], None, "{layers?}", has_text_layer, remove_all_animators),
        cmd!("anim.reveal", "Reveal Properties", [], None, "{kind: keyframes|animation|modified}", has_comp, reveal),
    ]
}