Merge main into M14.5 (settings and menus)
Reconciled with main's keyframe labels (same Keyframe::label field; keys.setLabel and keys.selectLabelGroup from main are kept, M14.5's duplicates removed; Edit ▸ Label on selected keys delegates to the label helper), proxies (RenderOpts::proxy next to nested_switches/draft_shadows), offloaded renders (Work carries nested_switches), wasm audio pump (preview mix rate), variable font axes and mask feather points. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -87,6 +87,9 @@ fn apply_settings(c: &mut Comp, p: &Value) {
|
||||
if let Some(n) = p.get("motionBlurSamples").and_then(Value::as_u64) {
|
||||
c.motion_blur_samples = (n as u32).clamp(2, 64);
|
||||
}
|
||||
if let Some(n) = p.get("adaptiveSampleLimit").and_then(Value::as_u64) {
|
||||
c.motion_blur_adaptive_limit = (n as u32).clamp(16, 256);
|
||||
}
|
||||
}
|
||||
|
||||
fn new_comp(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -249,7 +252,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Composition...",
|
||||
["Composition"],
|
||||
Some("Cmd+N"),
|
||||
"{name?, width?, height?, frameRate?, duration? (s), startTime? (s) | startTimecode?, background? [r,g,b]|#hex, pixelAspect?, shutterAngle?, shutterPhase?, motionBlurSamples?, renderer? classic3D|advanced3D, anchor?, open?}",
|
||||
"{name?, width?, height?, frameRate?, duration? (s), startTime? (s) | startTimecode?, background? [r,g,b]|#hex, pixelAspect?, shutterAngle?, shutterPhase?, motionBlurSamples?, adaptiveSampleLimit? (16–256), renderer? classic3D|advanced3D, anchor?, open?}",
|
||||
always,
|
||||
new_comp
|
||||
),
|
||||
@@ -258,7 +261,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Composition Settings...",
|
||||
["Composition"],
|
||||
Some("Cmd+K"),
|
||||
"{comp?, name?, width?, height?, anchor? 0-8 (resize anchor, 4 = center), frameRate?, duration?, startTime? (s) | startTimecode?, background?, shutterAngle?, shutterPhase?, motionBlurSamples?, pixelAspect?, renderer? classic3D|advanced3D}",
|
||||
"{comp?, name?, width?, height?, anchor? 0-8 (resize anchor, 4 = center), frameRate?, duration?, startTime? (s) | startTimecode?, background?, shutterAngle?, shutterPhase?, motionBlurSamples?, adaptiveSampleLimit? (16–256), pixelAspect?, renderer? classic3D|advanced3D}",
|
||||
has_comp,
|
||||
settings
|
||||
),
|
||||
|
||||
@@ -0,0 +1,780 @@
|
||||
//! Essential Graphics (Window ▸ Essential Graphics) and master properties.
|
||||
//!
|
||||
//! - **Authoring**: a comp's controls ([`EssentialGraphics`]): Add Property to Essential
|
||||
//! Graphics, Media Replacement for footage layers, groups, comments, renaming, reordering, the
|
||||
//! template name and the panel's Primary composition.
|
||||
//! - **Instances**: every precomp layer of such a comp shows the controls under **Essential
|
||||
//! Properties**; changing one overrides it for that instance only (`essential.set`, or any
|
||||
//! property edit of the master property); Push to Comp writes the override into the source
|
||||
//! comp, Revert drops it.
|
||||
//! - **Templates**: `essential.exportTemplate` writes an open `.ectemplate` (a ZIP holding
|
||||
//! `manifest.json` with the exposed controls, `project.ecproj` with the comp and everything it
|
||||
//! uses, the media files and a poster frame); `essential.importTemplate` merges one into the
|
||||
//! project and adds an instance to the active comp.
|
||||
|
||||
use effectcraft_keyframe::Value as KV;
|
||||
use effectcraft_project::essential::{self, ControlType, EgControl, EgKind, EssentialGraphics};
|
||||
use effectcraft_project::{GroupKind, ItemId, ItemKind, LayerId, LayerSource, ParamUi, Project, Uid};
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, b_p, bad, comp_id, has_comp, layer_p, selected_leaf_props, str_p};
|
||||
use crate::{EngineError, Result, Session, cmd, query};
|
||||
|
||||
/// Format id written into template manifests.
|
||||
pub const TEMPLATE_FORMAT: &str = "effectcraft-template";
|
||||
pub const TEMPLATE_VERSION: u32 = 1;
|
||||
|
||||
fn control_p(p: &Value, cmd: &str) -> Result<u64> {
|
||||
p.get("control").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "missing `control` (control id)"))
|
||||
}
|
||||
|
||||
/// Comp whose Essential Graphics a command edits: `comp`, else the panel's Primary comp, else
|
||||
/// the active comp.
|
||||
fn eg_comp(s: &Session, p: &Value) -> Result<ItemId> {
|
||||
if p.get("comp").is_some() {
|
||||
return comp_id(s, p);
|
||||
}
|
||||
if let Some(c) = s.state.essential_primary.filter(|c| s.project.comp(*c).is_some()) {
|
||||
return Ok(c);
|
||||
}
|
||||
comp_id(s, p)
|
||||
}
|
||||
|
||||
fn eg_of(proj: &mut Project, cid: ItemId) -> Result<&mut EssentialGraphics> {
|
||||
let name = proj.item(cid).map(|i| i.name.clone()).unwrap_or_default();
|
||||
let c = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
|
||||
Ok(c.essential.get_or_insert_with(|| EssentialGraphics { name, controls: vec![] }))
|
||||
}
|
||||
|
||||
/// Insert `ctl` into `group` (or the top level) at `index` (or the end).
|
||||
fn insert(eg: &mut EssentialGraphics, ctl: EgControl, group: Option<u64>, index: Option<usize>, cmd: &str) -> Result<()> {
|
||||
let list = eg.list_mut(group).ok_or_else(|| bad(cmd, "`group` is not a group control"))?;
|
||||
let i = index.unwrap_or(list.len()).min(list.len());
|
||||
list.insert(i, ctl);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_primary(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = comp_id(s, p)?;
|
||||
s.state.essential_primary = Some(cid);
|
||||
s.bump();
|
||||
Ok(json!({"comp": cid.0}))
|
||||
}
|
||||
|
||||
fn set_name(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = eg_comp(s, p)?;
|
||||
let name = str_p(p, "name").ok_or_else(|| bad("essential.setName", "missing `name`"))?.to_string();
|
||||
s.edit("Essential Graphics Name", None, |proj, st| {
|
||||
st.essential_primary.get_or_insert(cid);
|
||||
eg_of(proj, cid)?.name = name.clone();
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"comp": cid.0, "name": name}))
|
||||
}
|
||||
|
||||
/// Add Property to Essential Graphics: `{layer, path|prop}` or the selected properties.
|
||||
fn add_property(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "essential.addProperty";
|
||||
let targets: Vec<(ItemId, LayerId, Uid)> = if p.get("path").is_some() || p.get("prop").is_some() {
|
||||
vec![super::prop::prop_ref(s, p, C)?]
|
||||
} else {
|
||||
let cid = comp_id(s, p)?;
|
||||
selected_leaf_props(s).into_iter().map(|(l, u)| (cid, l, u)).collect()
|
||||
};
|
||||
if targets.is_empty() {
|
||||
return Err(bad(C, "select a property in the timeline (or give `layer` and `path`)"));
|
||||
}
|
||||
let group = p.get("group").and_then(Value::as_u64);
|
||||
let index = p.get("index").and_then(Value::as_u64).map(|i| i as usize);
|
||||
let rename = str_p(p, "name").map(str::to_string);
|
||||
let mut added = vec![];
|
||||
for (cid, lid, uid) in &targets {
|
||||
let l = s.project.comp(*cid).and_then(|c| c.layer(*lid)).ok_or(EngineError::NoComp)?;
|
||||
let pr = l.props.find(*uid).ok_or_else(|| bad(C, "no such property"))?;
|
||||
if control_type(pr).is_none() {
|
||||
return Err(bad(C, format!("`{}` can't be added to Essential Graphics (unsupported property type)", pr.name)));
|
||||
}
|
||||
if s.project.comp(*cid).and_then(|c| c.essential.as_ref()).is_some_and(|e| e.control_for(*lid, *uid).is_some()) {
|
||||
continue;
|
||||
}
|
||||
added.push((*cid, *lid, *uid, rename.clone().unwrap_or_else(|| pr.name.clone())));
|
||||
}
|
||||
let ids = s.edit("Add Property to Essential Graphics", None, |proj, st| {
|
||||
if let Some((cid, ..)) = added.first() {
|
||||
st.essential_primary.get_or_insert(*cid);
|
||||
}
|
||||
let mut ids = vec![];
|
||||
for (k, (cid, lid, uid, name)) in added.iter().enumerate() {
|
||||
let id = proj.alloc();
|
||||
let eg = eg_of(proj, *cid)?;
|
||||
insert(eg, EgControl { id, name: name.clone(), kind: EgKind::Property { layer: *lid, prop: *uid } }, group, index.map(|i| i + k), C)?;
|
||||
ids.push(id);
|
||||
}
|
||||
Ok(ids)
|
||||
})?;
|
||||
Ok(json!({"controls": ids}))
|
||||
}
|
||||
|
||||
fn control_type(pr: &effectcraft_project::Property) -> Option<ControlType> {
|
||||
essential::control_type(pr)
|
||||
}
|
||||
|
||||
/// Media Replacement for a footage layer.
|
||||
fn add_media(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "essential.addMedia";
|
||||
let (cid, lid) = layer_p(s, p, C)?;
|
||||
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?;
|
||||
if !matches!(l.source, LayerSource::Footage { .. }) {
|
||||
return Err(bad(C, "Media Replacement needs a footage layer"));
|
||||
}
|
||||
let name = str_p(p, "name").map(str::to_string).unwrap_or_else(|| format!("{} (Media)", l.name));
|
||||
let group = p.get("group").and_then(Value::as_u64);
|
||||
let id = s.edit("Add Media Replacement", None, |proj, st| {
|
||||
st.essential_primary.get_or_insert(cid);
|
||||
let id = proj.alloc();
|
||||
let eg = eg_of(proj, cid)?;
|
||||
if eg.flat().iter().any(|c| matches!(c.kind, EgKind::Media { layer } if layer == lid)) {
|
||||
return Err(bad(C, "this layer already has a Media Replacement control"));
|
||||
}
|
||||
insert(eg, EgControl { id, name, kind: EgKind::Media { layer: lid } }, group, None, C)?;
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({"control": id}))
|
||||
}
|
||||
|
||||
fn add_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = eg_comp(s, p)?;
|
||||
let name = str_p(p, "name").unwrap_or("Group").to_string();
|
||||
let index = p.get("index").and_then(Value::as_u64).map(|i| i as usize);
|
||||
let id = s.edit("Add Essential Graphics Group", None, |proj, st| {
|
||||
st.essential_primary.get_or_insert(cid);
|
||||
let id = proj.alloc();
|
||||
insert(eg_of(proj, cid)?, EgControl { id, name, kind: EgKind::Group { children: vec![] } }, None, index, "essential.addGroup")?;
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({"control": id}))
|
||||
}
|
||||
|
||||
fn add_comment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = eg_comp(s, p)?;
|
||||
let text = str_p(p, "text").unwrap_or("Comment").to_string();
|
||||
let group = p.get("group").and_then(Value::as_u64);
|
||||
let id = s.edit("Add Essential Graphics Comment", None, |proj, st| {
|
||||
st.essential_primary.get_or_insert(cid);
|
||||
let id = proj.alloc();
|
||||
insert(eg_of(proj, cid)?, EgControl { id, name: "Comment".into(), kind: EgKind::Comment { text } }, group, None, "essential.addComment")?;
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({"control": id}))
|
||||
}
|
||||
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "essential.rename";
|
||||
let cid = eg_comp(s, p)?;
|
||||
let id = control_p(p, C)?;
|
||||
let name = str_p(p, "name").or(str_p(p, "text")).ok_or_else(|| bad(C, "missing `name`"))?.to_string();
|
||||
s.edit("Rename Essential Graphics Control", None, |proj, _| {
|
||||
let c = eg_of(proj, cid)?.find_mut(id).ok_or_else(|| bad(C, format!("no control {id}")))?;
|
||||
match &mut c.kind {
|
||||
// A comment's name is its text.
|
||||
EgKind::Comment { text } => *text = name.clone(),
|
||||
_ => c.name = name.clone(),
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"control": id, "name": name}))
|
||||
}
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "essential.remove";
|
||||
let cid = eg_comp(s, p)?;
|
||||
let id = control_p(p, C)?;
|
||||
s.edit("Remove Essential Graphics Control", None, |proj, _| {
|
||||
eg_of(proj, cid)?.remove(id).ok_or_else(|| bad(C, format!("no control {id}")))?;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"control": id}))
|
||||
}
|
||||
|
||||
fn move_control(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "essential.move";
|
||||
let cid = eg_comp(s, p)?;
|
||||
let id = control_p(p, C)?;
|
||||
let group = p.get("group").and_then(Value::as_u64);
|
||||
let index = p.get("index").and_then(Value::as_u64).map(|i| i as usize);
|
||||
if group == Some(id) {
|
||||
return Err(bad(C, "a group can't contain itself"));
|
||||
}
|
||||
s.edit("Move Essential Graphics Control", None, |proj, _| {
|
||||
let eg = eg_of(proj, cid)?;
|
||||
let ctl = eg.remove(id).ok_or_else(|| bad(C, format!("no control {id}")))?;
|
||||
if matches!(ctl.kind, EgKind::Group { .. }) && group.is_some() {
|
||||
return Err(bad(C, "groups can't be nested"));
|
||||
}
|
||||
insert(eg, ctl, group, index, C)
|
||||
})?;
|
||||
Ok(json!({"control": id}))
|
||||
}
|
||||
|
||||
/// Dropdown Menu Control ▸ Edit: the menu items of a dropdown (popup) property.
|
||||
fn edit_dropdown(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "effect.editDropdown";
|
||||
let items: Vec<String> = match p.get("items") {
|
||||
Some(Value::Array(a)) => a.iter().filter_map(|v| v.as_str().map(str::to_string)).filter(|x| !x.is_empty()).collect(),
|
||||
_ => return Err(bad(C, "missing `items` (array of strings)")),
|
||||
};
|
||||
if items.is_empty() {
|
||||
return Err(bad(C, "a dropdown needs at least one item"));
|
||||
}
|
||||
let q = if p.get("path").is_none() && p.get("prop").is_none() {
|
||||
// The first Dropdown Menu Control of the layer.
|
||||
let (cid, lid) = layer_p(s, p, C)?;
|
||||
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?;
|
||||
let fx = l.effects().and_then(|fx| fx.groups().find(|g| matches!(&g.kind, GroupKind::Effect { effect } if effect == "ec.control.dropdown")));
|
||||
let uid = fx.and_then(|g| g.get("menu")).map(|pr| pr.uid).ok_or_else(|| bad(C, "the layer has no Dropdown Menu Control"))?;
|
||||
let mut q = p.clone();
|
||||
q["prop"] = json!(uid);
|
||||
q["layer"] = json!(lid.0);
|
||||
q
|
||||
} else {
|
||||
p.clone()
|
||||
};
|
||||
let (cid, lid, uid) = super::prop::prop_ref(s, &q, C)?;
|
||||
let n = items.len() as u32;
|
||||
s.edit("Edit Dropdown", None, |proj, _| {
|
||||
let pr = super::layer_mut(proj, cid, lid)?.props.find_mut(uid).ok_or_else(|| bad(C, "no such property"))?;
|
||||
if !matches!(pr.ui, ParamUi::Popup { .. }) {
|
||||
return Err(bad(C, "not a dropdown property"));
|
||||
}
|
||||
pr.ui = ParamUi::Popup { options: items.clone() };
|
||||
let clamp = |v: &mut KV| {
|
||||
if let KV::Enum(i) = v {
|
||||
*i = (*i).min(n - 1);
|
||||
}
|
||||
};
|
||||
clamp(&mut pr.value);
|
||||
for k in &mut pr.keys {
|
||||
clamp(&mut k.value);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"prop": uid, "items": items}))
|
||||
}
|
||||
|
||||
fn solo_supported(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let on = b_p(p, "on").unwrap_or(!s.state.essential_solo);
|
||||
s.state.essential_solo = on;
|
||||
s.bump();
|
||||
Ok(json!({"on": on}))
|
||||
}
|
||||
|
||||
/// Properties of a comp's layers that Essential Graphics can expose (Solo Supported
|
||||
/// Properties): `[{layer, uid, path, name, type}]`.
|
||||
pub fn supported_properties(project: &Project, cid: ItemId) -> Vec<Value> {
|
||||
let Some(c) = project.comp(cid) else { return vec![] };
|
||||
let mut out = vec![];
|
||||
for l in &c.layers {
|
||||
l.props.walk("", &mut |_, pr| {
|
||||
if pr.three_d_only && !l.is_3d() {
|
||||
return;
|
||||
}
|
||||
if let Some(t) = essential::control_type(pr) {
|
||||
let path = super::match_path_of(&l.props, pr.uid).unwrap_or_default();
|
||||
if path.starts_with(essential::GROUP) {
|
||||
return;
|
||||
}
|
||||
out.push(json!({"layer": l.id.0, "layerName": l.name, "uid": pr.uid, "path": path, "name": l.props.name_path_of(pr.uid), "type": t}));
|
||||
}
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn control_json(project: &Project, cid: ItemId, c: &EgControl) -> Value {
|
||||
match &c.kind {
|
||||
EgKind::Property { layer, prop } => {
|
||||
let src = essential::source_prop(project, cid, c);
|
||||
json!({
|
||||
"id": c.id, "name": c.name, "kind": "property", "layer": layer.0, "prop": prop,
|
||||
"layerName": src.map(|(l, _)| l.name.clone()),
|
||||
"path": src.and_then(|(l, _)| super::match_path_of(&l.props, *prop)),
|
||||
"type": src.and_then(|(_, pr)| essential::control_type(pr)),
|
||||
"value": src.map(|(_, pr)| pr.value_at(Tick::ZERO).to_json()),
|
||||
"missing": src.is_none(),
|
||||
})
|
||||
}
|
||||
EgKind::Media { layer } => json!({
|
||||
"id": c.id, "name": c.name, "kind": "media", "type": "media", "layer": layer.0,
|
||||
"item": essential::source_media(project, cid, c).map(|i| i.0),
|
||||
}),
|
||||
EgKind::Comment { text } => json!({"id": c.id, "name": c.name, "kind": "comment", "text": text}),
|
||||
EgKind::Group { children } => json!({
|
||||
"id": c.id, "name": c.name, "kind": "group",
|
||||
"children": children.iter().map(|x| control_json(project, cid, x)).collect::<Vec<_>>(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = eg_comp(s, p)?;
|
||||
let eg = s.project.comp(cid).and_then(|c| c.essential.clone()).unwrap_or_default();
|
||||
let name = if eg.name.is_empty() { s.project.item(cid).map(|i| i.name.clone()).unwrap_or_default() } else { eg.name.clone() };
|
||||
Ok(json!({
|
||||
"comp": cid.0,
|
||||
"primary": s.state.essential_primary.map(|c| c.0),
|
||||
"name": name,
|
||||
"solo": s.state.essential_solo,
|
||||
"controls": eg.controls.iter().map(|c| control_json(&s.project, cid, c)).collect::<Vec<_>>(),
|
||||
"supported": if b_p(p, "supported").unwrap_or(false) { json!(supported_properties(&s.project, cid)) } else { Value::Null },
|
||||
}))
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------ instances
|
||||
|
||||
/// The precomp layer (an instance) and its source comp.
|
||||
fn instance(s: &Session, p: &Value, cmd: &str) -> Result<(ItemId, LayerId, ItemId)> {
|
||||
let (cid, lid) = layer_p(s, p, cmd)?;
|
||||
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?;
|
||||
match l.source {
|
||||
LayerSource::Comp { item } if essential::group(l).is_some() => Ok((cid, lid, item)),
|
||||
_ => Err(bad(cmd, "the layer is not a precomp with Essential Properties")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The master property (instance child) of a control.
|
||||
fn master_uid(s: &Session, cid: ItemId, lid: LayerId, control: u64) -> Option<Uid> {
|
||||
let l = s.project.comp(cid)?.layer(lid)?;
|
||||
let g = essential::group(l)?;
|
||||
let m = essential::match_id(control);
|
||||
let mut found = None;
|
||||
g.walk("", &mut |_, pr| {
|
||||
if pr.match_id == m {
|
||||
found = Some(pr.uid);
|
||||
}
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
fn instance_json(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, lid, src) = instance(s, p, "essential.instance")?;
|
||||
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?;
|
||||
let over = essential::overridden(l);
|
||||
let eg = s.project.comp(src).and_then(|c| c.essential.clone()).unwrap_or_default();
|
||||
let t = s.time();
|
||||
let g = essential::group(l).cloned();
|
||||
let mut out = vec![];
|
||||
for c in eg.flat() {
|
||||
let m = essential::match_id(c.id);
|
||||
let mut pr = None;
|
||||
if let Some(g) = &g {
|
||||
g.walk("", &mut |_, x| {
|
||||
if x.match_id == m {
|
||||
pr = Some(x.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
let kind = match c.kind {
|
||||
EgKind::Property { .. } => "property",
|
||||
EgKind::Media { .. } => "media",
|
||||
EgKind::Comment { .. } => "comment",
|
||||
EgKind::Group { .. } => "group",
|
||||
};
|
||||
out.push(json!({
|
||||
"control": c.id, "name": c.name, "kind": kind,
|
||||
"uid": pr.as_ref().map(|x| x.uid),
|
||||
"path": pr.as_ref().and_then(|x| super::match_path_of(&l.props, x.uid)),
|
||||
"value": pr.as_ref().map(|x| x.value_at(l.layer_time(t)).to_json()),
|
||||
"type": pr.as_ref().and_then(essential::control_type).or((kind == "media").then_some(ControlType::Media)),
|
||||
"overridden": pr.as_ref().is_some_and(|x| over.contains(&x.uid)),
|
||||
}));
|
||||
}
|
||||
Ok(json!({"layer": lid.0, "comp": src.0, "name": eg.name, "controls": out}))
|
||||
}
|
||||
|
||||
/// Set an instance's value for a control (`value`, or `item` for Media Replacement).
|
||||
fn set_override(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "essential.set";
|
||||
let (cid, lid, _) = instance(s, p, C)?;
|
||||
let control = control_p(p, C)?;
|
||||
let uid = master_uid(s, cid, lid, control).ok_or_else(|| bad(C, format!("no control {control} on this instance")))?;
|
||||
if let Some(item) = p.get("item") {
|
||||
let item = match item {
|
||||
Value::Number(n) => ItemId(n.as_u64().unwrap_or(0)),
|
||||
Value::String(name) => s.project.find_by_name(name).map(|i| i.id).ok_or_else(|| bad(C, format!("no item `{name}`")))?,
|
||||
_ => return Err(bad(C, "`item` is an item id or name")),
|
||||
};
|
||||
if !matches!(s.project.item(item).map(|i| &i.kind), Some(ItemKind::Footage(f)) if f.has_video) {
|
||||
return Err(bad(C, "replacement media must be footage with video"));
|
||||
}
|
||||
s.edit("Replace Media", None, |proj, _| {
|
||||
let pr = super::layer_mut(proj, cid, lid)?.props.find_mut(uid).ok_or_else(|| bad(C, "no such property"))?;
|
||||
pr.value = KV::Scalar(item.0 as f64);
|
||||
Ok(())
|
||||
})?;
|
||||
return Ok(json!({"control": control, "item": item.0}));
|
||||
}
|
||||
let mut q = json!({"comp": cid.0, "layer": lid.0, "prop": uid, "value": p.get("value").cloned().ok_or_else(|| bad(C, "missing `value` (or `item`)"))?});
|
||||
if let Some(m) = p.get("merge") {
|
||||
q["merge"] = m.clone();
|
||||
}
|
||||
s.execute("prop.set", q)
|
||||
}
|
||||
|
||||
/// Controls of an instance to act on: `control` or every overridden one.
|
||||
fn targets(s: &Session, cid: ItemId, lid: LayerId, p: &Value) -> Vec<(u64, Uid)> {
|
||||
let Some(l) = s.project.comp(cid).and_then(|c| c.layer(lid)) else { return vec![] };
|
||||
let over = essential::overridden(l);
|
||||
let Some(g) = essential::group(l) else { return vec![] };
|
||||
let want = p.get("control").and_then(Value::as_u64);
|
||||
let mut out = vec![];
|
||||
g.walk("", &mut |_, pr| {
|
||||
if let Some(c) = essential::control_of(&pr.match_id)
|
||||
&& want.is_none_or(|w| w == c)
|
||||
&& (want.is_some() || over.contains(&pr.uid))
|
||||
{
|
||||
out.push((c, pr.uid));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn revert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "essential.revert";
|
||||
let (cid, lid, _) = instance(s, p, C)?;
|
||||
let ts = targets(s, cid, lid, p);
|
||||
if ts.is_empty() {
|
||||
return Ok(json!({"reverted": []}));
|
||||
}
|
||||
s.edit("Revert Essential Property", None, |proj, _| {
|
||||
let l = super::layer_mut(proj, cid, lid)?;
|
||||
let g = l.props.sub_mut(essential::GROUP).ok_or_else(|| bad(C, "no Essential Properties"))?;
|
||||
if let GroupKind::Essential { overridden } = &mut g.kind {
|
||||
overridden.retain(|u| !ts.iter().any(|(_, x)| x == u));
|
||||
}
|
||||
for (_, uid) in &ts {
|
||||
if let Some(pr) = g.find_mut(*uid) {
|
||||
// The sync below brings back the source value.
|
||||
pr.keys.clear();
|
||||
pr.expr = None;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
// Edits that only clear an override must not be taken for a new override: values are
|
||||
// refreshed by the sync inside `edit`, which ran after the override list was trimmed.
|
||||
Ok(json!({"reverted": ts.iter().map(|(c, _)| c).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
/// Push to Comp: write the instance's override values into the source comp's properties (and
|
||||
/// replaced media into the source layer), then drop the overrides.
|
||||
fn push_to_comp(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "essential.pushToComp";
|
||||
let (cid, lid, src) = instance(s, p, C)?;
|
||||
let ts = targets(s, cid, lid, p);
|
||||
let eg = s.project.comp(src).and_then(|c| c.essential.clone()).unwrap_or_default();
|
||||
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).cloned().ok_or(EngineError::NoComp)?;
|
||||
let mut writes = vec![];
|
||||
for (control, uid) in &ts {
|
||||
let (Some(ctl), Some(pr)) = (eg.find(*control), l.props.find(*uid)) else { continue };
|
||||
writes.push((ctl.kind.clone(), pr.clone()));
|
||||
}
|
||||
s.edit("Push Override Values to Source", None, |proj, _| {
|
||||
let sc = proj.comp_mut(src).ok_or(EngineError::NoComp)?;
|
||||
for (kind, pr) in &writes {
|
||||
match kind {
|
||||
EgKind::Property { layer, prop } => {
|
||||
let Some(inner) = sc.layer_mut(*layer) else { continue };
|
||||
// Instance keys are in the precomp layer's time (= the source comp's time);
|
||||
// the source property's keys are in the inner layer's time.
|
||||
let keys: Vec<_> = pr
|
||||
.keys
|
||||
.iter()
|
||||
.map(|k| {
|
||||
let mut k = k.clone();
|
||||
k.time = inner.layer_time(k.time);
|
||||
k
|
||||
})
|
||||
.collect();
|
||||
if let Some(target) = inner.props.find_mut(*prop) {
|
||||
target.value = pr.value.clone();
|
||||
target.keys = keys;
|
||||
}
|
||||
}
|
||||
EgKind::Media { layer } => {
|
||||
if let Some(inner) = sc.layer_mut(*layer) {
|
||||
inner.source = LayerSource::Footage { item: ItemId(pr.value.as_f64().max(0.0) as u64) };
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let g = super::layer_mut(proj, cid, lid)?.props.sub_mut(essential::GROUP).ok_or_else(|| bad(C, "no Essential Properties"))?;
|
||||
if let GroupKind::Essential { overridden } = &mut g.kind {
|
||||
overridden.retain(|u| !ts.iter().any(|(_, x)| x == u));
|
||||
}
|
||||
for (_, uid) in &ts {
|
||||
if let Some(pr) = g.find_mut(*uid) {
|
||||
pr.keys.clear();
|
||||
pr.expr = None;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"pushed": ts.iter().map(|(c, _)| c).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------ templates
|
||||
|
||||
fn file_name(path: &str) -> String {
|
||||
std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string())
|
||||
}
|
||||
|
||||
/// The manifest's control list (flattened, with the group each belongs to).
|
||||
fn manifest_controls(project: &Project, cid: ItemId, eg: &EssentialGraphics) -> Vec<Value> {
|
||||
fn go(project: &Project, cid: ItemId, v: &[EgControl], group: Option<u64>, out: &mut Vec<Value>) {
|
||||
for c in v {
|
||||
let mut j = control_json(project, cid, c);
|
||||
if let Some(o) = j.as_object_mut() {
|
||||
o.remove("children");
|
||||
o.insert("group".into(), json!(group));
|
||||
}
|
||||
out.push(j);
|
||||
if let EgKind::Group { children } = &c.kind {
|
||||
go(project, cid, children, Some(c.id), out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
go(project, cid, &eg.controls, None, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
fn export_template(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "essential.exportTemplate";
|
||||
let cid = eg_comp(s, p)?;
|
||||
let path = str_p(p, "path").ok_or_else(|| bad(C, "missing `path` (.ectemplate)"))?.to_string();
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
|
||||
let eg = comp.essential.clone().filter(|e| !e.controls.is_empty()).ok_or_else(|| bad(C, "the composition has no Essential Graphics controls"))?;
|
||||
let comp_name = s.project.item(cid).map(|i| i.name.clone()).unwrap_or_default();
|
||||
let name = str_p(p, "name").map(str::to_string).unwrap_or_else(|| if eg.name.is_empty() { comp_name.clone() } else { eg.name.clone() });
|
||||
// The project subset: the comp and everything it uses, at the root.
|
||||
let deps = essential::dependencies(&s.project, cid);
|
||||
let mut sub = Project { settings: s.project.settings.clone(), next_id: s.project.next_id, ..Project::default() };
|
||||
let mut entries: Vec<(String, Vec<u8>)> = vec![];
|
||||
let mut media = vec![];
|
||||
for id in &deps {
|
||||
let Some(mut it) = s.project.item(*id).cloned() else { continue };
|
||||
it.parent = None;
|
||||
it.proxy = None;
|
||||
if let ItemKind::Footage(f) = &mut it.kind
|
||||
&& f.data.is_none()
|
||||
{
|
||||
let files: Vec<String> = if f.sequence.is_empty() { vec![f.path.clone()] } else { f.sequence.clone() };
|
||||
let mut stored = vec![];
|
||||
for (k, file) in files.iter().enumerate() {
|
||||
if let Ok(bytes) = s.services.read_file(file) {
|
||||
let entry = format!("media/{}/{}", id.0, file_name(file));
|
||||
entries.push((entry.clone(), bytes));
|
||||
if k == 0 {
|
||||
f.path = entry.clone();
|
||||
}
|
||||
stored.push(entry);
|
||||
}
|
||||
}
|
||||
if !stored.is_empty() {
|
||||
if !f.sequence.is_empty() {
|
||||
f.sequence = stored.clone();
|
||||
}
|
||||
media.push(json!({"item": id.0, "files": stored}));
|
||||
}
|
||||
}
|
||||
sub.items.insert(*id, it);
|
||||
}
|
||||
let manifest = json!({
|
||||
"format": TEMPLATE_FORMAT,
|
||||
"version": TEMPLATE_VERSION,
|
||||
"generator": format!("EffectCraft {}", env!("CARGO_PKG_VERSION")),
|
||||
"name": name,
|
||||
"comp": cid.0,
|
||||
"compName": comp_name,
|
||||
"width": comp.width,
|
||||
"height": comp.height,
|
||||
"frameRate": comp.frame_rate.as_f64(),
|
||||
"duration": comp.duration.seconds(),
|
||||
"controls": manifest_controls(&s.project, cid, &eg),
|
||||
"media": media,
|
||||
"poster": "poster.png",
|
||||
});
|
||||
// A poster frame (longest side ≤ 320 px).
|
||||
if let Ok((w, h, rgba)) = s.render_rgba8(cid, comp.poster_time, 320)
|
||||
&& let Ok(png) = super::comp_more::encode_png(&rgba, w, h)
|
||||
{
|
||||
entries.push(("poster.png".into(), png));
|
||||
}
|
||||
entries.insert(0, ("project.ecproj".into(), sub.to_json().into_bytes()));
|
||||
entries.insert(0, ("manifest.json".into(), serde_json::to_vec_pretty(&manifest).unwrap_or_default()));
|
||||
let bytes = effectcraft_lottie::zip::store(&entries);
|
||||
s.services.write_file(&path, &bytes).map_err(|e| EngineError::Other(format!("cannot write {path}: {e}")))?;
|
||||
s.toast(format!("Exported template “{name}” to {path}"));
|
||||
Ok(json!({"path": path, "name": name, "bytes": bytes.len(), "controls": eg.flat().len(), "items": deps.len()}))
|
||||
}
|
||||
|
||||
/// Read a template's manifest and project (with media paths still archive-relative).
|
||||
pub fn read_template(bytes: &[u8]) -> std::result::Result<(Value, Project, Vec<(String, Vec<u8>)>), String> {
|
||||
let entries = effectcraft_lottie::zip::read_stored(bytes);
|
||||
let get = |n: &str| entries.iter().find(|(k, _)| k == n).map(|(_, v)| v.clone());
|
||||
let manifest: Value =
|
||||
serde_json::from_slice(&get("manifest.json").ok_or("not an EffectCraft template (no manifest.json)")?).map_err(|e| format!("manifest.json: {e}"))?;
|
||||
if manifest.get("format").and_then(Value::as_str) != Some(TEMPLATE_FORMAT) {
|
||||
return Err("not an EffectCraft template".into());
|
||||
}
|
||||
if manifest.get("version").and_then(Value::as_u64).unwrap_or(0) > TEMPLATE_VERSION as u64 {
|
||||
return Err("the template was made by a newer EffectCraft".into());
|
||||
}
|
||||
let text = String::from_utf8(get("project.ecproj").ok_or("template has no project.ecproj")?).map_err(|e| e.to_string())?;
|
||||
let project = Project::from_json(&text).map_err(|e| e.to_string())?;
|
||||
Ok((manifest, project, entries))
|
||||
}
|
||||
|
||||
fn import_template(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "essential.importTemplate";
|
||||
let path = str_p(p, "path").ok_or_else(|| bad(C, "missing `path` (.ectemplate)"))?.to_string();
|
||||
let bytes = s.services.read_file(&path).map_err(|e| EngineError::Other(format!("cannot read {path}: {e}")))?;
|
||||
let (manifest, mut sub, entries) = read_template(&bytes).map_err(|e| bad(C, e))?;
|
||||
let name = manifest.get("name").and_then(Value::as_str).unwrap_or("Template").to_string();
|
||||
let tcomp = manifest.get("comp").and_then(Value::as_u64).map(ItemId).ok_or_else(|| bad(C, "manifest has no `comp`"))?;
|
||||
// Media next to the template: `<dir>/<stem> Media/<item>/<file>`.
|
||||
let pp = std::path::Path::new(&path);
|
||||
let dir = pp.parent().map(|d| d.to_path_buf()).unwrap_or_default();
|
||||
let stem = pp.file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "Template".into());
|
||||
let media_dir = dir.join(format!("{stem} Media"));
|
||||
let mut written = std::collections::HashMap::new();
|
||||
for (k, v) in entries.iter().filter(|(k, _)| k.starts_with("media/")) {
|
||||
let rel = k.trim_start_matches("media/");
|
||||
let out = media_dir.join(rel);
|
||||
if let Some(parent) = out.parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
let out_s = out.to_string_lossy().to_string();
|
||||
if s.services.write_file(&out_s, v).is_ok() {
|
||||
written.insert(k.clone(), out_s);
|
||||
}
|
||||
}
|
||||
for it in sub.items.values_mut() {
|
||||
if let ItemKind::Footage(f) = &mut it.kind {
|
||||
if let Some(w) = written.get(&f.path) {
|
||||
f.path = w.clone();
|
||||
}
|
||||
for x in &mut f.sequence {
|
||||
if let Some(w) = written.get(x) {
|
||||
*x = w.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let target = if b_p(p, "addToComp") == Some(false) { None } else { comp_id(s, p).ok() };
|
||||
let base = s.project.next_id;
|
||||
essential::offset_ids(&mut sub, base);
|
||||
let new_comp = ItemId(tcomp.0 + base);
|
||||
let ids = s.edit("Import Template", None, |proj, st| {
|
||||
let folder = proj.add_item(&name, effectcraft_color::Label::Yellow, None, ItemKind::Folder);
|
||||
let mut ids = vec![];
|
||||
for (id, mut it) in std::mem::take(&mut sub.items) {
|
||||
if it.parent.is_none() {
|
||||
it.parent = Some(folder);
|
||||
}
|
||||
ids.push(id.0);
|
||||
proj.items.insert(id, it);
|
||||
}
|
||||
proj.next_id = proj.next_id.max(sub.next_id);
|
||||
proj.fix_next_id();
|
||||
st.project_selection = vec![new_comp];
|
||||
Ok(ids)
|
||||
})?;
|
||||
let mut layer = Value::Null;
|
||||
if let Some(cid) = target
|
||||
&& s.project.comp(cid).is_some()
|
||||
{
|
||||
let r = s.execute("layer.addItem", json!({"comp": cid.0, "item": new_comp.0, "time": 0.0}))?;
|
||||
layer = r["layer"].clone();
|
||||
}
|
||||
s.toast(format!("Imported template “{name}”"));
|
||||
Ok(json!({"comp": new_comp.0, "items": ids, "layer": layer, "name": name}))
|
||||
}
|
||||
|
||||
/// Read a template's manifest without importing it (Essential Graphics / agents).
|
||||
fn template_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_p(p, "path").ok_or_else(|| bad("essential.templateInfo", "missing `path`"))?;
|
||||
let bytes = s.services.read_file(path).map_err(|e| EngineError::Other(format!("cannot read {path}: {e}")))?;
|
||||
let (manifest, _, _) = read_template(&bytes).map_err(|e| bad("essential.templateInfo", e))?;
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
fn has_instance(s: &Session) -> std::result::Result<(), String> {
|
||||
has_comp(s)?;
|
||||
let ok = s.active_comp().is_some_and(|c| s.state.selected_layers.iter().any(|l| c.layer(*l).is_some_and(|l| essential::group(l).is_some())));
|
||||
if ok { Ok(()) } else { Err("select a precomp layer with Essential Properties".into()) }
|
||||
}
|
||||
|
||||
fn has_eg(s: &Session) -> std::result::Result<(), String> {
|
||||
let cid = s.state.essential_primary.or(s.state.active_comp).ok_or("no composition is open")?;
|
||||
if s.project.comp(cid).and_then(|c| c.essential.as_ref()).is_some_and(|e| !e.controls.is_empty()) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("add properties to Essential Graphics first".into())
|
||||
}
|
||||
}
|
||||
|
||||
fn has_selected_props(s: &Session) -> std::result::Result<(), String> {
|
||||
has_comp(s)?;
|
||||
if s.state.selected_props.is_empty() { Err("select a property in the timeline".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("essential.setPrimary", "Primary Composition", [], None, "{comp}", has_comp, set_primary),
|
||||
cmd!("essential.setName", "Essential Graphics Name", [], None, "{comp?, name}", has_comp, set_name),
|
||||
cmd!(
|
||||
"essential.addProperty",
|
||||
"Add Property to Essential Graphics",
|
||||
["Animation"],
|
||||
None,
|
||||
"{comp?, layer?, path?|prop?: uid (default: the selected properties), name?, group?: control id, index?}",
|
||||
has_selected_props,
|
||||
add_property
|
||||
),
|
||||
cmd!("essential.addMedia", "Add Media Replacement", [], None, "{layer, name?, group?}", has_comp, add_media),
|
||||
cmd!("essential.addGroup", "Add Group", [], None, "{comp?, name?, index?}", has_comp, add_group),
|
||||
cmd!("essential.addComment", "Add Comment", [], None, "{comp?, text?, group?}", has_comp, add_comment),
|
||||
cmd!("essential.rename", "Rename Control", [], None, "{comp?, control, name}", has_comp, rename),
|
||||
cmd!("essential.remove", "Remove Control", [], None, "{comp?, control}", has_comp, remove),
|
||||
cmd!("essential.move", "Move Control", [], None, "{comp?, control, group?: id (null = top level), index?}", has_comp, move_control),
|
||||
cmd!("essential.soloSupported", "Solo Supported Properties", [], None, "{on?}", has_comp, solo_supported),
|
||||
cmd!(
|
||||
"essential.exportTemplate",
|
||||
"Essential Graphics Template...",
|
||||
["File", "Export"],
|
||||
None,
|
||||
"{comp?, path (.ectemplate), name?}",
|
||||
has_eg,
|
||||
export_template
|
||||
),
|
||||
cmd!(
|
||||
"essential.importTemplate",
|
||||
"Essential Graphics Template...",
|
||||
["File", "Import"],
|
||||
None,
|
||||
"{path (.ectemplate), comp?, addToComp?: bool}",
|
||||
super::always,
|
||||
import_template
|
||||
),
|
||||
cmd!("essential.set", "Set Essential Property", [], None, "{layer, control, value | item (media)}", has_instance, set_override),
|
||||
cmd!("essential.pushToComp", "Push Override Values to Source", [], None, "{layer, control? (default: all overridden)}", has_instance, push_to_comp),
|
||||
cmd!("essential.revert", "Revert", [], None, "{layer, control? (default: all overridden)}", has_instance, revert),
|
||||
cmd!("effect.editDropdown", "Edit Dropdown Menu", [], None, "{layer, path?|prop?, items: [string]}", has_comp, edit_dropdown),
|
||||
query!("essential.list", "Essential Graphics controls", "{comp?, supported?: bool}", list),
|
||||
query!("essential.instance", "Essential Properties of a precomp layer", "{layer}", instance_json),
|
||||
query!("essential.templateInfo", "Read a template's manifest", "{path}", template_info),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
//! Expression tools: the error list behind the expression error bar, and the Expression
|
||||
//! Language menu (the ⓕ button next to an expression), written from the public Expression
|
||||
//! Language Reference.
|
||||
|
||||
use effectcraft_project::{ItemId, Layer, Property};
|
||||
use effectcraft_render::EvalCtx;
|
||||
use effectcraft_time::Tick;
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, comp_id, f_p};
|
||||
use crate::{EngineError, Result, Session, query};
|
||||
|
||||
/// One failing expression.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
pub struct ExprError {
|
||||
pub comp: u64,
|
||||
pub layer: u64,
|
||||
#[serde(rename = "layerIndex")]
|
||||
pub layer_index: usize,
|
||||
#[serde(rename = "layerName")]
|
||||
pub layer_name: String,
|
||||
pub prop: u64,
|
||||
/// Match path (`transform/opacity`).
|
||||
pub path: String,
|
||||
/// Property name path as shown in the timeline (`Transform/Opacity`).
|
||||
pub name: String,
|
||||
pub message: String,
|
||||
/// The expression is disabled (it failed to compile).
|
||||
pub disabled: bool,
|
||||
}
|
||||
|
||||
impl ExprError {
|
||||
/// The error bar's text: `Error at line 1 in property 'Opacity' of layer 1 ('Solid') in comp 'Main'. …`
|
||||
pub fn describe(&self, comp_name: &str) -> String {
|
||||
let prop = self.name.rsplit('/').next().unwrap_or(&self.name);
|
||||
format!("{} — property '{}' of layer {} ('{}') in comp '{}'", self.message, prop, self.layer_index, self.layer_name, comp_name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Every failing expression of comp `cid` at comp time `t`: evaluation errors of enabled
|
||||
/// expressions and the syntax errors that disabled others.
|
||||
pub fn errors(s: &Session, cid: ItemId, t: Tick) -> Vec<ExprError> {
|
||||
let Some(comp) = s.project.comp(cid) else { return vec![] };
|
||||
let ctx = EvalCtx { footage: Some(s.footage.as_ref()), expr: s.expr.as_deref(), ..EvalCtx::new(&s.project, cid, comp, t) };
|
||||
let mut out = vec![];
|
||||
for (i, l) in comp.layers.iter().enumerate() {
|
||||
let mut props: Vec<&Property> = vec![];
|
||||
l.props.walk("", &mut |_, p| {
|
||||
if p.expr.as_ref().is_some_and(|e| !e.text.trim().is_empty()) {
|
||||
props.push(p);
|
||||
}
|
||||
});
|
||||
for p in props {
|
||||
let e = p.expr.as_ref().expect("filtered");
|
||||
let msg = if e.enabled {
|
||||
match &ctx.expr {
|
||||
Some(h) => h.eval(&ctx, l, p, &p.value_at(l.layer_time(t))).err(),
|
||||
None => None,
|
||||
}
|
||||
} else {
|
||||
s.expr_check.and_then(|check| check(&e.text).err())
|
||||
};
|
||||
if let Some(message) = msg {
|
||||
out.push(error_of(cid, i, l, p, message, !e.enabled));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn error_of(cid: ItemId, i: usize, l: &Layer, p: &Property, message: String, disabled: bool) -> ExprError {
|
||||
ExprError {
|
||||
comp: cid.0,
|
||||
layer: l.id.0,
|
||||
layer_index: i + 1,
|
||||
layer_name: l.name.clone(),
|
||||
prop: p.uid,
|
||||
path: super::match_path_of(&l.props, p.uid).unwrap_or_default(),
|
||||
name: l.props.name_path_of(p.uid).unwrap_or_else(|| p.name.clone()),
|
||||
message,
|
||||
disabled,
|
||||
}
|
||||
}
|
||||
|
||||
fn errors_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = comp_id(s, p)?;
|
||||
let t = f_p(p, "time").map(Tick::from_seconds_f64).unwrap_or_else(|| s.time_of(cid));
|
||||
let name = s.project.item(cid).map(|i| i.name.clone()).ok_or(EngineError::NoComp)?;
|
||||
let list = errors(s, cid, t);
|
||||
let text: Vec<String> = list.iter().map(|e| e.describe(&name)).collect();
|
||||
Ok(json!({"comp": cid.0, "time": t.seconds(), "count": list.len(), "errors": list, "text": text}))
|
||||
}
|
||||
|
||||
/// The Expression Language menu: (category, [(label, inserted text)]). Submenus are nested
|
||||
/// with `▸` in the category name.
|
||||
pub fn language_menu() -> Vec<(&'static str, Vec<(&'static str, &'static str)>)> {
|
||||
vec![
|
||||
(
|
||||
"Global",
|
||||
vec![
|
||||
("comp(name)", "comp(\"name\")"),
|
||||
("footage(name)", "footage(\"name\")"),
|
||||
("thisComp", "thisComp"),
|
||||
("thisLayer", "thisLayer"),
|
||||
("thisProperty", "thisProperty"),
|
||||
("thisProject", "thisProject"),
|
||||
("time", "time"),
|
||||
("colorDepth", "colorDepth"),
|
||||
("posterizeTime(framesPerSecond)", "posterizeTime(framesPerSecond)"),
|
||||
("value", "value"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Vector Math",
|
||||
vec![
|
||||
("add(vec1, vec2)", "add(vec1, vec2)"),
|
||||
("sub(vec1, vec2)", "sub(vec1, vec2)"),
|
||||
("mul(vec, amount)", "mul(vec, amount)"),
|
||||
("div(vec, amount)", "div(vec, amount)"),
|
||||
("clamp(value, limit1, limit2)", "clamp(value, limit1, limit2)"),
|
||||
("dot(vec1, vec2)", "dot(vec1, vec2)"),
|
||||
("cross(vec1, vec2)", "cross(vec1, vec2)"),
|
||||
("normalize(vec)", "normalize(vec)"),
|
||||
("length(vec)", "length(vec)"),
|
||||
("length(point1, point2)", "length(point1, point2)"),
|
||||
("lookAt(fromPoint, atPoint)", "lookAt(fromPoint, atPoint)"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Random Numbers",
|
||||
vec![
|
||||
("seedRandom(offset, timeless=false)", "seedRandom(offset, timeless=false)"),
|
||||
("random()", "random()"),
|
||||
("random(maxValOrArray)", "random(maxValOrArray)"),
|
||||
("random(minValOrArray, maxValOrArray)", "random(minValOrArray, maxValOrArray)"),
|
||||
("gaussRandom()", "gaussRandom()"),
|
||||
("gaussRandom(maxValOrArray)", "gaussRandom(maxValOrArray)"),
|
||||
("gaussRandom(minValOrArray, maxValOrArray)", "gaussRandom(minValOrArray, maxValOrArray)"),
|
||||
("noise(valOrArray)", "noise(valOrArray)"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Interpolation",
|
||||
vec![
|
||||
("linear(t, value1, value2)", "linear(t, value1, value2)"),
|
||||
("linear(t, tMin, tMax, value1, value2)", "linear(t, tMin, tMax, value1, value2)"),
|
||||
("ease(t, value1, value2)", "ease(t, value1, value2)"),
|
||||
("ease(t, tMin, tMax, value1, value2)", "ease(t, tMin, tMax, value1, value2)"),
|
||||
("easeIn(t, value1, value2)", "easeIn(t, value1, value2)"),
|
||||
("easeIn(t, tMin, tMax, value1, value2)", "easeIn(t, tMin, tMax, value1, value2)"),
|
||||
("easeOut(t, value1, value2)", "easeOut(t, value1, value2)"),
|
||||
("easeOut(t, tMin, tMax, value1, value2)", "easeOut(t, tMin, tMax, value1, value2)"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Color Conversion",
|
||||
vec![
|
||||
("rgbToHsl(rgbaArray)", "rgbToHsl(rgbaArray)"),
|
||||
("hslToRgb(hslaArray)", "hslToRgb(hslaArray)"),
|
||||
("hexToRgb(hexString)", "hexToRgb(hexString)"),
|
||||
],
|
||||
),
|
||||
("Other Math", vec![("degreesToRadians(degrees)", "degreesToRadians(degrees)"), ("radiansToDegrees(radians)", "radiansToDegrees(radians)")]),
|
||||
(
|
||||
"JavaScript Math",
|
||||
vec![
|
||||
("Math.cos(value)", "Math.cos(value)"),
|
||||
("Math.sin(value)", "Math.sin(value)"),
|
||||
("Math.atan2(y, x)", "Math.atan2(y, x)"),
|
||||
("Math.sqrt(value)", "Math.sqrt(value)"),
|
||||
("Math.abs(value)", "Math.abs(value)"),
|
||||
("Math.round(value)", "Math.round(value)"),
|
||||
("Math.floor(value)", "Math.floor(value)"),
|
||||
("Math.min(value1, value2)", "Math.min(value1, value2)"),
|
||||
("Math.max(value1, value2)", "Math.max(value1, value2)"),
|
||||
("Math.PI", "Math.PI"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Comp",
|
||||
vec![
|
||||
("layer(index)", "layer(index)"),
|
||||
("layer(name)", "layer(\"name\")"),
|
||||
("layer(otherLayer, relIndex)", "layer(otherLayer, relIndex)"),
|
||||
("marker", "marker"),
|
||||
("numLayers", "numLayers"),
|
||||
("activeCamera", "activeCamera"),
|
||||
("width", "width"),
|
||||
("height", "height"),
|
||||
("duration", "duration"),
|
||||
("frameDuration", "frameDuration"),
|
||||
("pixelAspect", "pixelAspect"),
|
||||
("name", "name"),
|
||||
("bgColor", "bgColor"),
|
||||
("displayStartTime", "displayStartTime"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Footage",
|
||||
vec![
|
||||
("width", "width"),
|
||||
("height", "height"),
|
||||
("duration", "duration"),
|
||||
("frameDuration", "frameDuration"),
|
||||
("pixelAspect", "pixelAspect"),
|
||||
("name", "name"),
|
||||
("sourceText", "sourceText"),
|
||||
("sourceData", "sourceData"),
|
||||
("dataValue(dataPath)", "dataValue(dataPath)"),
|
||||
("dataKeyCount", "dataKeyCount"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Layer > Sub-objects",
|
||||
vec![
|
||||
("source", "source"),
|
||||
("effect(name)", "effect(\"name\")"),
|
||||
("effect(index)", "effect(index)"),
|
||||
("mask(name)", "mask(\"name\")"),
|
||||
("mask(index)", "mask(index)"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Layer > General",
|
||||
vec![
|
||||
("width", "width"),
|
||||
("height", "height"),
|
||||
("index", "index"),
|
||||
("parent", "parent"),
|
||||
("hasParent", "hasParent"),
|
||||
("inPoint", "inPoint"),
|
||||
("outPoint", "outPoint"),
|
||||
("startTime", "startTime"),
|
||||
("hasVideo", "hasVideo"),
|
||||
("enabled", "enabled"),
|
||||
("active", "active"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Layer > Properties",
|
||||
vec![
|
||||
("anchorPoint", "anchorPoint"),
|
||||
("position", "position"),
|
||||
("scale", "scale"),
|
||||
("rotation", "rotation"),
|
||||
("opacity", "opacity"),
|
||||
("marker", "marker"),
|
||||
("name", "name"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Layer > Space Transforms",
|
||||
vec![
|
||||
("toComp(point, t = time)", "toComp(point, t = time)"),
|
||||
("fromComp(point, t = time)", "fromComp(point, t = time)"),
|
||||
("toWorld(point, t = time)", "toWorld(point, t = time)"),
|
||||
("fromWorld(point, t = time)", "fromWorld(point, t = time)"),
|
||||
("toCompVec(vec, t = time)", "toCompVec(vec, t = time)"),
|
||||
("fromCompVec(vec, t = time)", "fromCompVec(vec, t = time)"),
|
||||
("toWorldVec(vec, t = time)", "toWorldVec(vec, t = time)"),
|
||||
("fromWorldVec(vec, t = time)", "fromWorldVec(vec, t = time)"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Layer > Other",
|
||||
vec![
|
||||
("sourceRectAtTime(t = time, includeExtents = false)", "sourceRectAtTime(t = time, includeExtents = false)"),
|
||||
("sampleImage(point, radius = [.5, .5], postEffect = true, t = time)", "sampleImage(point, radius = [.5, .5], postEffect = true, t = time)"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Property",
|
||||
vec![
|
||||
("value", "value"),
|
||||
("valueAtTime(t)", "valueAtTime(t)"),
|
||||
("velocity", "velocity"),
|
||||
("velocityAtTime(t)", "velocityAtTime(t)"),
|
||||
("speed", "speed"),
|
||||
("speedAtTime(t)", "speedAtTime(t)"),
|
||||
("wiggle(freq, amp, octaves = 1, amp_mult = .5, t = time)", "wiggle(freq, amp, octaves = 1, amp_mult = .5, t = time)"),
|
||||
("temporalWiggle(freq, amp, octaves = 1, amp_mult = .5, t = time)", "temporalWiggle(freq, amp, octaves = 1, amp_mult = .5, t = time)"),
|
||||
("smooth(width = .2, samples = 5, t = time)", "smooth(width = .2, samples = 5, t = time)"),
|
||||
("loopIn(type = \"cycle\", numKeyframes = 0)", "loopIn(type = \"cycle\", numKeyframes = 0)"),
|
||||
("loopOut(type = \"cycle\", numKeyframes = 0)", "loopOut(type = \"cycle\", numKeyframes = 0)"),
|
||||
("loopInDuration(type = \"cycle\", duration = 0)", "loopInDuration(type = \"cycle\", duration = 0)"),
|
||||
("loopOutDuration(type = \"cycle\", duration = 0)", "loopOutDuration(type = \"cycle\", duration = 0)"),
|
||||
("key(index)", "key(index)"),
|
||||
("key(markerName)", "key(markerName)"),
|
||||
("nearestKey(t)", "nearestKey(t)"),
|
||||
("numKeys", "numKeys"),
|
||||
("name", "name"),
|
||||
("propertyIndex", "propertyIndex"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Path Property",
|
||||
vec![
|
||||
("points(t = time)", "points(t = time)"),
|
||||
("inTangents(t = time)", "inTangents(t = time)"),
|
||||
("outTangents(t = time)", "outTangents(t = time)"),
|
||||
("isClosed()", "isClosed()"),
|
||||
(
|
||||
"createPath(points, inTangents = [], outTangents = [], is_closed = true)",
|
||||
"createPath(points, inTangents = [], outTangents = [], is_closed = true)",
|
||||
),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Text > Style",
|
||||
vec![
|
||||
("text.sourceText.style", "text.sourceText.style"),
|
||||
("getStyleAt(charIndex, t = time)", "getStyleAt(charIndex, t = time)"),
|
||||
("createStyle()", "createStyle()"),
|
||||
("setFontSize(value)", "setFontSize(value)"),
|
||||
("setFillColor(value)", "setFillColor(value)"),
|
||||
("setText(value)", "setText(value)"),
|
||||
],
|
||||
),
|
||||
("Text > Expression Selector", vec![("textIndex", "textIndex"), ("textTotal", "textTotal"), ("selectorValue", "selectorValue")]),
|
||||
("Key", vec![("value", "value"), ("time", "time"), ("index", "index")]),
|
||||
(
|
||||
"Marker Key",
|
||||
vec![
|
||||
("duration", "duration"),
|
||||
("comment", "comment"),
|
||||
("chapter", "chapter"),
|
||||
("url", "url"),
|
||||
("frameTarget", "frameTarget"),
|
||||
("eventCuePoint", "eventCuePoint"),
|
||||
("cuePointName", "cuePointName"),
|
||||
("parameters", "parameters"),
|
||||
("protectedRegion", "protectedRegion"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Time Conversion",
|
||||
vec![
|
||||
(
|
||||
"timeToFrames(t = time + thisComp.displayStartTime, fps = 1.0 / thisComp.frameDuration, isDuration = false)",
|
||||
"timeToFrames(t = time + thisComp.displayStartTime, fps = 1.0 / thisComp.frameDuration, isDuration = false)",
|
||||
),
|
||||
("framesToTime(frames, fps = 1.0 / thisComp.frameDuration)", "framesToTime(frames, fps = 1.0 / thisComp.frameDuration)"),
|
||||
(
|
||||
"timeToTimecode(t = time + thisComp.displayStartTime, timecodeBase = 30, isDuration = false)",
|
||||
"timeToTimecode(t = time + thisComp.displayStartTime, timecodeBase = 30, isDuration = false)",
|
||||
),
|
||||
(
|
||||
"timeToFeetAndFrames(t = time + thisComp.displayStartTime, fps = 1.0 / thisComp.frameDuration, framesPerFoot = 16, isDuration = false)",
|
||||
"timeToFeetAndFrames(t = time + thisComp.displayStartTime, fps = 1.0 / thisComp.frameDuration, framesPerFoot = 16, isDuration = false)",
|
||||
),
|
||||
(
|
||||
"timeToCurrentFormat(t = time + thisComp.displayStartTime, fps = 1.0 / thisComp.frameDuration, isDuration = false)",
|
||||
"timeToCurrentFormat(t = time + thisComp.displayStartTime, fps = 1.0 / thisComp.frameDuration, isDuration = false)",
|
||||
),
|
||||
],
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn menu_cmd(_s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
Ok(json!(
|
||||
language_menu()
|
||||
.into_iter()
|
||||
.map(|(c, items)| json!({"category": c, "items": items.into_iter().map(|(l, t)| json!({"label": l, "text": t})).collect::<Vec<_>>()}))
|
||||
.collect::<Vec<_>>()
|
||||
))
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
query!("expr.errors", "Expression errors (the error bar)", "{comp?, time? (s)}", errors_cmd),
|
||||
query!("expr.languageMenu", "Expression Language menu", "{}", menu_cmd),
|
||||
]
|
||||
}
|
||||
@@ -73,7 +73,7 @@ fn save_as(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn increment_save(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let cur = s.path.clone().ok_or_else(|| bad("file.incrementAndSave", "save the project first"))?;
|
||||
// After Effects: `Intro.aep` → `Intro 2.aep` → `Intro 3.aep`.
|
||||
let next = crate::autosave::increment_path(&cur, |p| std::path::Path::new(p).exists());
|
||||
let next = crate::autosave::increment_path(&cur, |p| s.file_ops().is_file(std::path::Path::new(p)));
|
||||
save_to(s, &next)
|
||||
}
|
||||
|
||||
@@ -133,13 +133,24 @@ pub(crate) fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(json!({"items": ids, "comps": out_comps, "errors": errors}));
|
||||
}
|
||||
}
|
||||
let importer = s.importer.clone().ok_or_else(|| EngineError::Other("media import is not available in this build".into()))?;
|
||||
let mut probed = vec![];
|
||||
let psd_layer = p.get("layer").cloned();
|
||||
let seq_rate = effectcraft_time::FrameRate::from_f64(s.prefs.import.sequence_fps);
|
||||
let mut ask_alpha = vec![];
|
||||
let mut warnings = vec![];
|
||||
for path in &paths {
|
||||
// Data files (JSON, CSV, TSV) for data-driven animation: kept as text in the project.
|
||||
if let Some(f) = data_footage(s, path) {
|
||||
match f {
|
||||
Ok(f) => probed.push((path.clone(), f)),
|
||||
Err(e) => errors.push(format!("{path}: {e}")),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(importer) = s.importer.clone() else {
|
||||
errors.push(format!("{path}: media import is not available in this build"));
|
||||
continue;
|
||||
};
|
||||
match importer.probe(path) {
|
||||
Ok(mut f) => {
|
||||
// Settings ▸ Import ▸ Report Missing Frames.
|
||||
@@ -192,6 +203,7 @@ pub(crate) fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
FootageKind::Still | FootageKind::Sequence => Label::Lavender,
|
||||
FootageKind::Audio => Label::SeaFoam,
|
||||
FootageKind::Video | FootageKind::Model => Label::Aqua,
|
||||
FootageKind::Data => Label::Sandstone,
|
||||
};
|
||||
let ask = ask_alpha.contains(&paths.iter().position(|x| *x == path).unwrap_or(usize::MAX));
|
||||
let id = proj.add_item(&name, label, None, ItemKind::Footage(f));
|
||||
@@ -273,6 +285,25 @@ pub(crate) fn import_psd_comp(s: &mut Session, path: &str, bytes: Vec<u8>, retai
|
||||
Ok((r.comp.0, items, r.warnings))
|
||||
}
|
||||
|
||||
/// Extensions imported as data footage.
|
||||
pub const DATA_EXTENSIONS: &[&str] = &["json", "csv", "tsv"];
|
||||
|
||||
/// A data footage item for `path` (JSON / CSV / TSV), `None` for other files.
|
||||
pub(crate) fn data_footage(s: &Session, path: &str) -> Option<std::result::Result<effectcraft_project::Footage, String>> {
|
||||
let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
|
||||
if !DATA_EXTENSIONS.contains(&ext.as_str()) {
|
||||
return None;
|
||||
}
|
||||
Some((|| {
|
||||
let bytes = s.services.read_file(path).map_err(|e| e.to_string())?;
|
||||
let text = String::from_utf8(bytes).map_err(|_| "data files must be UTF-8 text".to_string())?;
|
||||
if ext == "json" {
|
||||
serde_json::from_str::<Value>(text.trim_start_matches('\u{feff}')).map_err(|e| format!("invalid JSON: {e}"))?;
|
||||
}
|
||||
Ok(effectcraft_project::Footage { path: path.to_string(), kind: FootageKind::Data, codec: ext.to_uppercase(), data: Some(text), ..Default::default() })
|
||||
})())
|
||||
}
|
||||
|
||||
fn project_settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.edit("Project Settings", None, |proj, _| {
|
||||
if let Some(b) = str_p(p, "bitDepth") {
|
||||
|
||||
@@ -107,7 +107,7 @@ fn placeholder_footage(p: &Value) -> Footage {
|
||||
missing: true,
|
||||
sequence: vec![],
|
||||
color_profile: None,
|
||||
layer: None,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -443,56 +443,179 @@ fn script_run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
// ---------------------------------------------------------------- footage
|
||||
|
||||
/// Interpret Footage settings parsed from command parameters (every field optional).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct Interpretation {
|
||||
rate: Option<FrameRate>,
|
||||
/// Back to the file's own rate (Use frame rate from file).
|
||||
native: bool,
|
||||
alpha: Option<AlphaMode>,
|
||||
/// Alpha ▸ Guess: decide Straight / Premultiplied (and the matte colour) from a frame.
|
||||
guess: bool,
|
||||
matte: Option<[f32; 3]>,
|
||||
invert_alpha: Option<bool>,
|
||||
loops: Option<u32>,
|
||||
par: Option<f64>,
|
||||
fields: Option<effectcraft_project::FieldOrder>,
|
||||
profile: Option<Option<effectcraft_project::ColorSpace>>,
|
||||
linear: Option<bool>,
|
||||
}
|
||||
|
||||
impl Interpretation {
|
||||
pub(crate) fn parse(p: &Value, cmd: &str) -> Result<Interpretation> {
|
||||
let mut it = Interpretation { rate: f_p(p, "frameRate").map(FrameRate::from_f64), ..Default::default() };
|
||||
if str_p(p, "frameRate") == Some("file") {
|
||||
it.native = true;
|
||||
}
|
||||
match str_p(p, "alpha") {
|
||||
Some("straight") => it.alpha = Some(AlphaMode::Straight),
|
||||
Some("premultiplied") => it.alpha = Some(AlphaMode::Premultiplied),
|
||||
Some("ignore") => it.alpha = Some(AlphaMode::Ignore),
|
||||
Some("guess") => it.guess = true,
|
||||
Some(a) => return Err(bad(cmd, format!("alpha: straight|premultiplied|ignore|guess, not `{a}`"))),
|
||||
None => {}
|
||||
}
|
||||
it.guess |= super::b_p(p, "guessAlpha").unwrap_or(false);
|
||||
it.matte = match p.get("matteColor").or(p.get("premulColor")) {
|
||||
None => None,
|
||||
Some(v) => Some(
|
||||
effectcraft_keyframe::Value::Color([0.0, 0.0, 0.0, 1.0])
|
||||
.coerce_json(v)
|
||||
.map(|c| {
|
||||
let c = c.as_color();
|
||||
[c[0], c[1], c[2]]
|
||||
})
|
||||
.ok_or_else(|| bad(cmd, "matteColor: #hex or [r, g, b] (0..1)"))?,
|
||||
),
|
||||
};
|
||||
it.invert_alpha = super::b_p(p, "invertAlpha");
|
||||
it.loops = p.get("loop").and_then(Value::as_u64).map(|v| v.clamp(1, 9999) as u32);
|
||||
it.par = f_p(p, "pixelAspect").filter(|x| *x > 0.0);
|
||||
it.fields = match str_p(p, "fields") {
|
||||
Some(f) => Some(effectcraft_project::FieldOrder::parse(f).ok_or_else(|| bad(cmd, "fields: off|upper|lower"))?),
|
||||
None => None,
|
||||
};
|
||||
// Color ▸ Assign Profile: a colour space id, or "auto"/"none" for the file's own (sRGB).
|
||||
it.profile = match str_p(p, "colorProfile") {
|
||||
Some("auto" | "none" | "") => Some(None),
|
||||
Some(c) => match effectcraft_project::ColorSpace::parse(c) {
|
||||
Some(cs) => Some(Some(cs)),
|
||||
None => return Err(bad(cmd, format!("colorProfile: srgb|rec709|rec2020|p3|auto, not `{c}`"))),
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
it.linear = super::b_p(p, "linearLight");
|
||||
Ok(it)
|
||||
}
|
||||
|
||||
pub(crate) fn apply(&self, f: &mut Footage, guessed: Option<(AlphaMode, [f32; 3])>) {
|
||||
if self.native {
|
||||
if let Some(n) = f.native_rate.take() {
|
||||
f.frame_rate = n;
|
||||
}
|
||||
} else if let Some(r) = self.rate {
|
||||
if f.native_rate.is_none() {
|
||||
f.native_rate = Some(f.frame_rate);
|
||||
}
|
||||
f.frame_rate = r;
|
||||
}
|
||||
if let Some(a) = self.alpha {
|
||||
f.alpha = a;
|
||||
}
|
||||
if let Some((a, m)) = guessed {
|
||||
f.alpha = a;
|
||||
f.premul_color = m;
|
||||
}
|
||||
if let Some(m) = self.matte {
|
||||
f.premul_color = m;
|
||||
}
|
||||
if let Some(v) = self.invert_alpha {
|
||||
f.invert_alpha = v;
|
||||
}
|
||||
if let Some(l) = self.loops {
|
||||
f.loop_count = l;
|
||||
}
|
||||
if let Some(x) = self.par {
|
||||
f.pixel_aspect = x;
|
||||
}
|
||||
if let Some(x) = self.fields {
|
||||
f.fields = x;
|
||||
}
|
||||
if let Some(c) = self.profile {
|
||||
f.color_profile = c;
|
||||
}
|
||||
if let Some(v) = self.linear {
|
||||
f.linear_light = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Interpret Footage ▸ Alpha ▸ Guess: read the first frame as straight colour and decide
|
||||
/// whether the file is premultiplied (every partly transparent pixel's colour within its alpha
|
||||
/// of a black or white matte) or straight. `None` when the frame has no partial alpha.
|
||||
pub(crate) fn guess_alpha(s: &Session, item: ItemId, f: &Footage) -> Option<(AlphaMode, [f32; 3])> {
|
||||
let probe = Footage { alpha: AlphaMode::Straight, invert_alpha: false, ..f.clone() };
|
||||
let img = s.footage.frame(item, &probe, Tick::ZERO)?;
|
||||
let (mut partial, mut black, mut white) = (0usize, true, true);
|
||||
let eps = 1.5 / 255.0;
|
||||
for px in img.data.iter() {
|
||||
let a = px[3];
|
||||
if a <= eps || a >= 1.0 - eps {
|
||||
continue;
|
||||
}
|
||||
partial += 1;
|
||||
for c in &px[..3] {
|
||||
// The file's colour (the decoder premultiplied it as straight).
|
||||
let file = c / a;
|
||||
black &= file <= a + eps;
|
||||
white &= file >= 1.0 - a - eps;
|
||||
}
|
||||
}
|
||||
if partial == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(if black {
|
||||
(AlphaMode::Premultiplied, [0.0; 3])
|
||||
} else if white {
|
||||
(AlphaMode::Premultiplied, [1.0; 3])
|
||||
} else {
|
||||
(AlphaMode::Straight, f.premul_color)
|
||||
})
|
||||
}
|
||||
|
||||
fn interpret(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let items = items_p(s, p);
|
||||
if items.is_empty() {
|
||||
return Err(bad("file.interpretFootage", "select footage"));
|
||||
}
|
||||
let rate = f_p(p, "frameRate").map(FrameRate::from_f64);
|
||||
let alpha = match str_p(p, "alpha") {
|
||||
Some("straight") => Some(AlphaMode::Straight),
|
||||
Some("premultiplied") => Some(AlphaMode::Premultiplied),
|
||||
Some("ignore") => Some(AlphaMode::Ignore),
|
||||
Some(a) => return Err(bad("file.interpretFootage", format!("alpha: straight|premultiplied|ignore, not `{a}`"))),
|
||||
None => None,
|
||||
};
|
||||
let loops = p.get("loop").and_then(Value::as_u64).map(|v| v.max(1) as u32);
|
||||
let par = f_p(p, "pixelAspect");
|
||||
// Color ▸ Assign Profile: a colour space id, or "auto"/"none" for the file's own (sRGB).
|
||||
let profile = match str_p(p, "colorProfile") {
|
||||
Some("auto" | "none" | "") => Some(None),
|
||||
Some(c) => match effectcraft_project::ColorSpace::parse(c) {
|
||||
Some(cs) => Some(Some(cs)),
|
||||
None => return Err(bad("file.interpretFootage", format!("colorProfile: srgb|rec709|rec2020|p3|auto, not `{c}`"))),
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let it = Interpretation::parse(p, "file.interpretFootage")?;
|
||||
let guesses: Vec<Option<(AlphaMode, [f32; 3])>> = items
|
||||
.iter()
|
||||
.map(|i| match (it.guess, s.project.item(*i).map(|x| &x.kind)) {
|
||||
(true, Some(ItemKind::Footage(f))) => guess_alpha(s, *i, f),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
s.edit("Interpret Footage", None, |proj, _| {
|
||||
for i in &items {
|
||||
for (i, g) in items.iter().zip(&guesses) {
|
||||
if let Some(ItemKind::Footage(f)) = proj.item_mut(*i).map(|x| &mut x.kind) {
|
||||
if let Some(r) = rate {
|
||||
if f.native_rate.is_none() {
|
||||
f.native_rate = Some(f.frame_rate);
|
||||
}
|
||||
f.frame_rate = r;
|
||||
}
|
||||
if let Some(a) = alpha {
|
||||
f.alpha = a;
|
||||
}
|
||||
if let Some(l) = loops {
|
||||
f.loop_count = l;
|
||||
}
|
||||
if let Some(x) = par {
|
||||
f.pixel_aspect = x;
|
||||
}
|
||||
if let Some(c) = profile {
|
||||
f.color_profile = c;
|
||||
}
|
||||
it.apply(f, *g);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
let out: Vec<Value> = items
|
||||
.iter()
|
||||
.filter_map(|i| match s.project.item(*i).map(|x| &x.kind) {
|
||||
Some(ItemKind::Footage(f)) => Some(json!({
|
||||
"item": i.0, "alpha": format!("{:?}", f.alpha), "matteColor": f.premul_color, "invertAlpha": f.invert_alpha,
|
||||
"fields": f.fields.label(), "pixelAspect": f.pixel_aspect, "loop": f.loop_count, "frameRate": f.frame_rate.as_f64(),
|
||||
"linearLight": f.linear_light,
|
||||
})),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({"items": out}))
|
||||
}
|
||||
|
||||
fn remember_interpretation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -513,6 +636,10 @@ fn apply_interpretation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
f.premul_color = src.premul_color;
|
||||
f.pixel_aspect = src.pixel_aspect;
|
||||
f.loop_count = src.loop_count;
|
||||
f.fields = src.fields;
|
||||
f.invert_alpha = src.invert_alpha;
|
||||
f.linear_light = src.linear_light;
|
||||
f.color_profile = src.color_profile;
|
||||
if src.native_rate.is_some() {
|
||||
if f.native_rate.is_none() {
|
||||
f.native_rate = Some(f.frame_rate);
|
||||
@@ -700,7 +827,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Main...",
|
||||
["File", "Interpret Footage"],
|
||||
Some("Cmd+Alt+G"),
|
||||
"{items?, frameRate?, alpha?: straight|premultiplied|ignore, loop?, pixelAspect?, colorProfile?: srgb|rec709|rec2020|p3|auto}",
|
||||
"{items?, frameRate?: fps|\"file\", alpha?: straight|premultiplied|ignore|guess, guessAlpha?, matteColor?, invertAlpha?, loop?, pixelAspect?, fields?: off|upper|lower, colorProfile?: srgb|rec709|rec2020|p3|auto, linearLight?}",
|
||||
has_footage_selection,
|
||||
interpret
|
||||
),
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! Layer ▸ Camera focus commands: Link Focus Distance to Point of Interest, Link Focus Distance to
|
||||
//! Layer (both add an expression to Focus Distance, as After Effects does) and Set Focus Distance
|
||||
//! to Layer (a one-off value).
|
||||
|
||||
use effectcraft_geom::vec3;
|
||||
use effectcraft_keyframe::Value as KV;
|
||||
use effectcraft_project::{Comp, Expression, ItemId, LayerId};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, bad, comp_id, layer_mut, resolve_layer};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
/// (comp, camera, target?) from `{camera?, layer?}` or the selection (a camera plus another layer).
|
||||
fn refs(s: &Session, p: &Value, cmd: &str, need_target: bool) -> Result<(ItemId, LayerId, Option<LayerId>)> {
|
||||
let cid = comp_id(s, p)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let sel: Vec<LayerId> = s.state.selected_layers.iter().copied().filter(|l| comp.layer(*l).is_some()).collect();
|
||||
let is_cam = |c: &Comp, l: LayerId| c.layer(l).is_some_and(|l| l.is_camera());
|
||||
let cam = match p.get("camera") {
|
||||
Some(v) => resolve_layer(comp, v).ok_or_else(|| bad(cmd, format!("no layer {v}")))?,
|
||||
None => sel.iter().copied().find(|l| is_cam(comp, *l)).ok_or_else(|| bad(cmd, "select a camera layer"))?,
|
||||
};
|
||||
if !is_cam(comp, cam) {
|
||||
return Err(bad(cmd, "`camera` is not a camera layer"));
|
||||
}
|
||||
let target = match p.get("layer") {
|
||||
Some(v) => Some(resolve_layer(comp, v).ok_or_else(|| bad(cmd, format!("no layer {v}")))?),
|
||||
None => sel.iter().copied().find(|l| *l != cam),
|
||||
};
|
||||
if need_target && target.is_none() {
|
||||
return Err(bad(cmd, "select the camera and the layer to focus on"));
|
||||
}
|
||||
Ok((cid, cam, target))
|
||||
}
|
||||
|
||||
fn set_focus_expr(s: &mut Session, cid: ItemId, cam: LayerId, label: &str, text: String) -> Result<Value> {
|
||||
s.edit(label, None, |proj, _| {
|
||||
let l = layer_mut(proj, cid, cam)?;
|
||||
let pr = l.props.prop_mut("cameraOptions/focusDistance").ok_or_else(|| bad("camera", "the camera has no Focus Distance"))?;
|
||||
pr.expr = Some(Expression { text: text.clone(), enabled: true });
|
||||
Ok(json!({"expression": text}))
|
||||
})
|
||||
}
|
||||
|
||||
fn link_poi(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, cam, _) = refs(s, p, "camera.linkFocusToPoi", false)?;
|
||||
set_focus_expr(s, cid, cam, "Link Focus Distance to Point of Interest", "length(transform.pointOfInterest, transform.position)".into())
|
||||
}
|
||||
|
||||
/// The focus expression for a target layer: its anchor point's distance along the camera's view
|
||||
/// axis.
|
||||
fn layer_expr(name: &str) -> String {
|
||||
let n = serde_json::to_string(name).unwrap_or_else(|_| "\"\"".into());
|
||||
format!(
|
||||
"var m = thisComp.layer({n});\nvar c = toWorld([0, 0, 0]);\nvar f = normalize(sub(toWorld([0, 0, 1]), c));\ndot(sub(m.toWorld(m.transform.anchorPoint), c), f)"
|
||||
)
|
||||
}
|
||||
|
||||
fn link_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (cid, cam, target) = refs(s, p, "camera.linkFocusToLayer", true)?;
|
||||
let name = s.project.comp(cid).and_then(|c| c.layer(target?)).map(|l| l.name.clone()).ok_or(EngineError::NoComp)?;
|
||||
set_focus_expr(s, cid, cam, "Link Focus Distance to Layer", layer_expr(&name))
|
||||
}
|
||||
|
||||
/// Camera depth of `target`'s anchor point at the current time.
|
||||
pub(crate) fn focus_depth(s: &Session, cid: ItemId, cam: LayerId, target: LayerId) -> Option<f64> {
|
||||
let comp = s.project.comp(cid)?;
|
||||
let mut ctx = effectcraft_render::EvalCtx::new(&s.project, cid, comp, s.time_of(cid));
|
||||
ctx.expr = s.expr.as_deref();
|
||||
let c = ctx.comp.layer(cam)?;
|
||||
let t = ctx.comp.layer(target)?;
|
||||
let cs = effectcraft_render::three_d::camera::layer_camera(&ctx, c);
|
||||
let a = t.transform().map(|tr| ctx.v3(t, tr, "anchor", [0.0; 3])).unwrap_or([0.0; 3]);
|
||||
Some(cs.depth(ctx.world_matrix(t).apply(vec3(a[0], a[1], a[2]))))
|
||||
}
|
||||
|
||||
fn set_to_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "camera.setFocusToLayer";
|
||||
let (cid, cam, target) = refs(s, p, c, true)?;
|
||||
let d = focus_depth(s, cid, cam, target.ok_or_else(|| bad(c, "no layer"))?).ok_or_else(|| bad(c, "can't evaluate the layers"))?;
|
||||
if d <= 0.0 {
|
||||
return Err(bad(c, "the layer is behind the camera"));
|
||||
}
|
||||
let t = s.time();
|
||||
s.edit("Set Focus Distance to Layer", None, |proj, _| {
|
||||
let l = layer_mut(proj, cid, cam)?;
|
||||
let lt = l.layer_time(t);
|
||||
let pr = l.props.prop_mut("cameraOptions/focusDistance").ok_or_else(|| bad(c, "the camera has no Focus Distance"))?;
|
||||
pr.set_value_at(lt, KV::Scalar(d));
|
||||
Ok(json!({"focusDistance": d}))
|
||||
})
|
||||
}
|
||||
|
||||
fn camera_selected(s: &Session) -> std::result::Result<(), String> {
|
||||
let c = s.active_comp().ok_or("no composition is open")?;
|
||||
if s.state.selected_layers.iter().any(|l| c.layer(*l).is_some_and(|l| l.is_camera())) { Ok(()) } else { Err("select a camera layer".into()) }
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("camera.linkFocusToPoi", "Link Focus Distance to Point of Interest", ["Layer", "Camera"], None, "{comp?, camera?}", camera_selected, link_poi),
|
||||
cmd!("camera.linkFocusToLayer", "Link Focus Distance to Layer", ["Layer", "Camera"], None, "{comp?, camera?, layer?}", camera_selected, link_layer),
|
||||
cmd!("camera.setFocusToLayer", "Set Focus Distance to Layer", ["Layer", "Camera"], None, "{comp?, camera?, layer?}", camera_selected, set_to_layer),
|
||||
]
|
||||
}
|
||||
@@ -16,6 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
// Application.
|
||||
fe!("app.about", "About EffectCraft...", [], None, "{}", always),
|
||||
fe!("layer.style.options", "Layer Style Options...", ["Layer", "Layer Styles"], None, "{layer?, style?: blendingOptions|dropShadow|…}", has_layers),
|
||||
fe!(
|
||||
"app.settings",
|
||||
"Settings...",
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
//! Keyframe color labels: Label a keyframe (Keyframe ▸ Label ▸ colour) and Edit ▸ Select Keyframe
|
||||
//! Label Group (On Selected Layers / On All Layers / Visible Keyframes on …).
|
||||
|
||||
use effectcraft_color::Label;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, bad, has_comp, has_keys, str_p};
|
||||
use crate::{EngineError, KeyRef, Result, Session, cmd};
|
||||
|
||||
fn label_p(p: &Value, c: &str) -> Result<u8> {
|
||||
match p.get("label") {
|
||||
Some(Value::String(s)) => {
|
||||
let l = if s.eq_ignore_ascii_case("none") { Some(Label::None) } else { Label::from_name(s) };
|
||||
let l = l.ok_or_else(|| bad(c, format!("unknown label `{s}`")))?;
|
||||
Ok(Label::ALL.iter().position(|x| *x == l).unwrap_or(0) as u8)
|
||||
}
|
||||
Some(Value::Number(n)) => Ok(n.as_u64().filter(|i| (*i as usize) < Label::ALL.len()).ok_or_else(|| bad(c, "label index 0–16"))? as u8),
|
||||
_ => Err(bad(c, "missing `label` (name or 0–16)")),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_label(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "keys.setLabel";
|
||||
let label = label_p(p, c)?;
|
||||
let n = super::prop::edit_keys(s, "Keyframe Label", None, |keys, i, _| {
|
||||
keys[i].label = label;
|
||||
true
|
||||
})?;
|
||||
Ok(json!({"label": Label::ALL[label as usize].name(), "keys": n}))
|
||||
}
|
||||
|
||||
/// Select every keyframe that shares a label with a selected keyframe, on the selected or all
|
||||
/// layers. `visible` (property uids revealed in the Timeline) limits the "Visible Keyframes"
|
||||
/// scopes; without it every property counts as visible.
|
||||
fn select_label_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "keys.selectLabelGroup";
|
||||
let scope = str_p(p, "scope").unwrap_or("selected");
|
||||
let comp = s.active_comp().ok_or(EngineError::NoComp)?;
|
||||
let labels: Vec<u8> =
|
||||
s.state.selected_keys.iter().filter_map(|k| comp.layer(k.layer)?.props.find(k.prop)?.keys.iter().find(|x| x.time == k.time).map(|x| x.label)).collect();
|
||||
if labels.is_empty() {
|
||||
return Err(bad(c, "select a keyframe first"));
|
||||
}
|
||||
let only_selected = match scope {
|
||||
"selected" | "visibleSelected" => true,
|
||||
"all" | "visibleAll" => false,
|
||||
_ => return Err(bad(c, "scope: selected|all|visibleSelected|visibleAll")),
|
||||
};
|
||||
let visible: Option<Vec<u64>> =
|
||||
(scope.starts_with("visible")).then(|| p.get("visible").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect())).flatten();
|
||||
let key_layers: Vec<_> = s.state.selected_keys.iter().map(|k| k.layer).collect();
|
||||
let mut sel = Vec::new();
|
||||
for l in &comp.layers {
|
||||
if only_selected && !s.state.selected_layers.contains(&l.id) && !key_layers.contains(&l.id) {
|
||||
continue;
|
||||
}
|
||||
l.props.walk("", &mut |_, pr| {
|
||||
if visible.as_ref().is_some_and(|v| !v.contains(&pr.uid)) {
|
||||
return;
|
||||
}
|
||||
for k in &pr.keys {
|
||||
if labels.contains(&k.label) {
|
||||
sel.push(KeyRef { layer: l.id, prop: pr.uid, time: k.time });
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
s.state.selected_keys = sel;
|
||||
Ok(json!({"keys": s.state.selected_keys.len()}))
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("keys.setLabel", "Keyframe Label", [], None, "{label: name|none|0–16}", has_keys, set_label),
|
||||
cmd!(
|
||||
"keys.selectLabelGroup",
|
||||
"Select Keyframe Label Group",
|
||||
[],
|
||||
None,
|
||||
"{scope: selected|all|visibleSelected|visibleAll, visible?: [prop uid]}",
|
||||
has_comp,
|
||||
select_label_group
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -1,16 +1,15 @@
|
||||
//! Keyframe features of M14.5: Animation ▸ Keyframe Assistant ▸ Convert Audio to Keyframes and
|
||||
//! RPF Camera Import, keyframe colour labels (Edit ▸ Label on selected keyframes) and Edit ▸
|
||||
//! Select Keyframe Label Group.
|
||||
//! RPF Camera Import, and Edit ▸ Label on selected keyframes.
|
||||
|
||||
use effectcraft_color::Label;
|
||||
use effectcraft_keyframe::{Keyframe, Value as KV};
|
||||
use effectcraft_project::LayerId;
|
||||
use effectcraft_project::build::Ids;
|
||||
use effectcraft_project::{LayerId, Uid};
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::app_more::grouped;
|
||||
use super::{CommandSpec, bad, comp_id, has_comp, has_keys, layer_mut, str_p};
|
||||
use super::{CommandSpec, bad, comp_id, has_comp, layer_mut, str_p};
|
||||
use crate::{EngineError, KeyRef, Result, Session, cmd};
|
||||
|
||||
// ---------------------------------------------------------------- keyframe labels
|
||||
@@ -28,7 +27,8 @@ fn keys_p(s: &Session, p: &Value) -> Vec<KeyRef> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Edit ▸ Label on keyframes: colour the selected (or given) keyframes.
|
||||
/// Edit ▸ Label on keyframes: colour the selected (or given) keyframes (label names as renamed
|
||||
/// in Settings ▸ Labels; `keys.setLabel` is the Timeline context menu's command).
|
||||
pub(crate) fn label_keys(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = str_p(p, "label").unwrap_or("Red");
|
||||
let idx = label_index(s, name).ok_or_else(|| bad("keys.label", format!("unknown label `{name}`")))?;
|
||||
@@ -52,43 +52,6 @@ pub(crate) fn label_keys(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"keys": n, "label": idx}))
|
||||
}
|
||||
|
||||
/// Edit ▸ Select Keyframe Label Group: select every keyframe with the label of a selected
|
||||
/// keyframe. `scope`: `selected` (selected layers), `all` (all layers), `visibleSelected` /
|
||||
/// `visibleAll` (only properties the frontend shows, given as `props`: [uid]; agents without a
|
||||
/// timeline may omit it, then every property counts).
|
||||
fn select_label_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let scope = str_p(p, "scope").unwrap_or("selected");
|
||||
if !matches!(scope, "selected" | "all" | "visibleSelected" | "visibleAll") {
|
||||
return Err(bad("keys.selectLabelGroup", "scope: selected|all|visibleSelected|visibleAll"));
|
||||
}
|
||||
let comp = s.active_comp().ok_or(EngineError::NoComp)?;
|
||||
let labels: Vec<u8> = s
|
||||
.state
|
||||
.selected_keys
|
||||
.iter()
|
||||
.filter_map(|k| comp.layer(k.layer).and_then(|l| l.props.find(k.prop)).and_then(|pr| pr.keys.iter().find(|x| x.time == k.time)).map(|x| x.label))
|
||||
.collect();
|
||||
if labels.is_empty() {
|
||||
return Err(bad("keys.selectLabelGroup", "select a keyframe first"));
|
||||
}
|
||||
let visible: Option<Vec<Uid>> = p.get("props").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect());
|
||||
let layers: Vec<LayerId> =
|
||||
if scope == "all" || scope == "visibleAll" { comp.layers.iter().map(|l| l.id).collect() } else { s.state.selected_layers.clone() };
|
||||
let mut sel = vec![];
|
||||
for l in comp.layers.iter().filter(|l| layers.contains(&l.id)) {
|
||||
l.props.walk("", &mut |_, pr| {
|
||||
if scope.starts_with("visible") && visible.as_ref().is_some_and(|v| !v.contains(&pr.uid)) {
|
||||
return;
|
||||
}
|
||||
for k in pr.keys.iter().filter(|k| labels.contains(&k.label)) {
|
||||
sel.push(KeyRef { layer: l.id, prop: pr.uid, time: k.time });
|
||||
}
|
||||
});
|
||||
}
|
||||
s.state.selected_keys = sel;
|
||||
Ok(json!({"keys": s.state.selected_keys.len()}))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Convert Audio to Keyframes
|
||||
|
||||
/// Per-frame amplitude of interleaved stereo: (left, right, both), mean absolute sample × 100.
|
||||
@@ -284,15 +247,5 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_comp,
|
||||
rpf_camera_import
|
||||
),
|
||||
cmd!(
|
||||
"keys.selectLabelGroup",
|
||||
"Select Keyframe Label Group",
|
||||
[],
|
||||
None,
|
||||
"{scope: selected|all|visibleSelected|visibleAll, props?: [uid]}",
|
||||
has_keys,
|
||||
select_label_group
|
||||
),
|
||||
cmd!("keys.label", "Keyframe Label", [], None, "{label, keys?: [{layer, prop, time}]}", has_keys, label_keys),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ fn new_solid_like(s: &mut Session, p: &Value, adjustment: bool) -> Result<Value>
|
||||
let name = str_p(p, "name").map(str::to_string).unwrap_or(default_name);
|
||||
let id = s.edit(if adjustment { "New Adjustment Layer" } else { "New Solid" }, None, |proj, st| {
|
||||
let folder = solids_folder(proj);
|
||||
let sid = proj.add_item(&name, Label::Red, Some(folder), ItemKind::Solid(Solid { color, width: w, height: h, pixel_aspect: 1.0 }));
|
||||
let sid = proj.add_item(&name, Label::Red, Some(folder), ItemKind::Solid(Solid { color, width: w, height: h, pixel_aspect: comp.pixel_aspect }));
|
||||
let mut l = build::layer(proj, &comp, &name, LayerSource::Solid { item: sid }, (w, h), None);
|
||||
if adjustment {
|
||||
l.switches.adjustment = true;
|
||||
@@ -239,6 +239,9 @@ fn add_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = (s.prefs.import.still_footage == "seconds").then(|| Tick::from_seconds_f64(s.prefs.import.still_seconds));
|
||||
(LayerSource::Footage { item }, (f.width, f.height), d)
|
||||
}
|
||||
ItemKind::Footage(f) if f.kind == effectcraft_project::FootageKind::Data => {
|
||||
return Err(bad("layer.addItem", "data files can't be layers; read them in expressions with footage(\"name\").sourceData"));
|
||||
}
|
||||
ItemKind::Footage(f) if f.kind == effectcraft_project::FootageKind::Model => {
|
||||
return super::model3d::new_model(s, &serde_json::json!({"comp": cid.0, "item": item.0, "time": f_p(p, "time")}));
|
||||
}
|
||||
@@ -519,7 +522,8 @@ fn set_parent(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Like AE's pick-whip, parenting keeps the layer where it is: its transform is re-expressed
|
||||
// in the new parent's space (Position, Rotation, Scale), unless `compensate: false`.
|
||||
let compensate = b_p(p, "compensate").unwrap_or(true);
|
||||
let ectx = effectcraft_render::EvalCtx { project: &s.project, comp_id: cid, comp, time: s.time(), expr: s.expr.as_deref() };
|
||||
let ectx =
|
||||
effectcraft_render::EvalCtx { project: &s.project, comp_id: cid, comp, time: s.time(), expr: s.expr.as_deref(), footage: Some(s.footage.as_ref()) };
|
||||
let space = |id: Option<LayerId>| -> effectcraft_geom::Mat3 {
|
||||
id.and_then(|i| comp.layer(i)).filter(|l| !l.is_3d()).map(|l| ectx.layer_to_comp(l).0).unwrap_or(effectcraft_geom::Mat3::IDENTITY)
|
||||
};
|
||||
|
||||
@@ -126,7 +126,7 @@ fn freeze(s: &mut Session, p: &Value, last: bool) -> Result<Value> {
|
||||
return Err(bad("layer.freezeFrame", "freezing needs a footage or composition layer"));
|
||||
}
|
||||
// What each layer shows now (honouring an existing remap) — evaluated before the edit.
|
||||
let ectx = effectcraft_render::EvalCtx { project: &s.project, comp_id: cid, comp, time: cti, expr: s.expr.as_deref() };
|
||||
let ectx = effectcraft_render::EvalCtx { project: &s.project, comp_id: cid, comp, time: cti, expr: s.expr.as_deref(), footage: Some(s.footage.as_ref()) };
|
||||
let now: Vec<(effectcraft_project::LayerId, f64)> = comp
|
||||
.layers
|
||||
.iter()
|
||||
|
||||
@@ -156,7 +156,7 @@ fn new_mask(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut outs = pts(p.get("outTangents"));
|
||||
ins.resize(n, [0.0; 2]);
|
||||
outs.resize(n, [0.0; 2]);
|
||||
let path = ShapePath { vertices: v, in_tangents: ins, out_tangents: outs, closed: b_p(p, "closed").unwrap_or(false) };
|
||||
let path = ShapePath { vertices: v, in_tangents: ins, out_tangents: outs, closed: b_p(p, "closed").unwrap_or(false), feather: Vec::new() };
|
||||
let mode = str_p(p, "mode").and_then(MaskMode::from_name).unwrap_or(MaskMode::Add);
|
||||
let cycle = s.prefs.appearance.cycle_mask_colors;
|
||||
let uid = s.edit("New Mask", None, |proj, st| {
|
||||
@@ -185,6 +185,7 @@ fn add_vertex(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
sp.vertices.insert(i, point);
|
||||
sp.in_tangents.insert(i, tin);
|
||||
sp.out_tangents.insert(i, tout);
|
||||
sp.feather_after_insert(i, None);
|
||||
Ok((i, Some(CountOp::Insert(i))))
|
||||
})?;
|
||||
s.state.selected_vertices = vec![VertexRef { layer: lid, mask: uid, index: i }];
|
||||
@@ -322,6 +323,7 @@ fn delete_vertices(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
sp.vertices.remove(i);
|
||||
sp.in_tangents.remove(i);
|
||||
sp.out_tangents.remove(i);
|
||||
sp.feather_after_remove(i);
|
||||
}
|
||||
}
|
||||
if sp.vertices.len() < 3 {
|
||||
@@ -405,9 +407,199 @@ pub(crate) fn split_segment(sp: &mut ShapePath, seg: usize, t: f64) -> Option<us
|
||||
sp.vertices.insert(at, m);
|
||||
sp.in_tangents.insert(at, [d[0] - m[0], d[1] - m[1]]);
|
||||
sp.out_tangents.insert(at, [e[0] - m[0], e[1] - m[1]]);
|
||||
sp.feather_after_insert(at, Some(t));
|
||||
Some(at)
|
||||
}
|
||||
|
||||
/// Nearest (segment, t, distance) of a path to a point (layer space), sampled per segment.
|
||||
pub(crate) fn nearest_on_path(sp: &ShapePath, q: [f64; 2]) -> Option<(usize, f64, f64)> {
|
||||
let n = sp.vertices.len();
|
||||
let mut best: Option<(usize, f64, f64)> = None;
|
||||
for seg in 0..sp.segment_count() {
|
||||
let j = (seg + 1) % n;
|
||||
let p0 = sp.vertices[seg];
|
||||
let p3 = sp.vertices[j];
|
||||
let o = sp.out_tangents.get(seg).copied().unwrap_or([0.0; 2]);
|
||||
let i = sp.in_tangents.get(j).copied().unwrap_or([0.0; 2]);
|
||||
let (p1, p2) = ([p0[0] + o[0], p0[1] + o[1]], [p3[0] + i[0], p3[1] + i[1]]);
|
||||
let at = |t: f64| {
|
||||
let u = 1.0 - t;
|
||||
let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
|
||||
[a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0], a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1]]
|
||||
};
|
||||
let dist = |t: f64| {
|
||||
let p = at(t);
|
||||
(p[0] - q[0]).hypot(p[1] - q[1])
|
||||
};
|
||||
let (mut bt, mut bd) = (0.0, f64::INFINITY);
|
||||
for k in 0..=64 {
|
||||
let t = k as f64 / 64.0;
|
||||
let d = dist(t);
|
||||
if d < bd {
|
||||
(bt, bd) = (t, d);
|
||||
}
|
||||
}
|
||||
// Refine by bisection-style narrowing.
|
||||
let mut step = 1.0 / 64.0;
|
||||
for _ in 0..20 {
|
||||
step *= 0.5;
|
||||
for t in [bt - step, bt + step] {
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
let d = dist(t);
|
||||
if d < bd {
|
||||
(bt, bd) = (t, d);
|
||||
}
|
||||
}
|
||||
}
|
||||
if best.is_none_or(|b| bd < b.2) {
|
||||
best = Some((seg, bt, bd));
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Whether a layer-space point is inside a closed path.
|
||||
fn inside_path(sp: &ShapePath, q: [f64; 2]) -> bool {
|
||||
sp.closed && {
|
||||
let cov = effectcraft_path::fill_coverage(
|
||||
&[effectcraft_path::to_kurbo(sp)],
|
||||
&effectcraft_geom::Mat3::translate(effectcraft_geom::vec2(-q[0] + 0.5, -q[1] + 0.5)),
|
||||
1,
|
||||
1,
|
||||
effectcraft_path::FillRule::NonZero,
|
||||
);
|
||||
cov.data[0] >= 0.5
|
||||
}
|
||||
}
|
||||
|
||||
/// Point of segment `seg` at parameter `t`.
|
||||
fn point_on(sp: &ShapePath, seg: usize, t: f64) -> Option<[f64; 2]> {
|
||||
let n = sp.vertices.len();
|
||||
if seg >= sp.segment_count() {
|
||||
return None;
|
||||
}
|
||||
let j = (seg + 1) % n;
|
||||
let (p0, p3) = (sp.vertices[seg], sp.vertices[j]);
|
||||
let o = sp.out_tangents.get(seg).copied().unwrap_or([0.0; 2]);
|
||||
let i = sp.in_tangents.get(j).copied().unwrap_or([0.0; 2]);
|
||||
let (p1, p2) = ([p0[0] + o[0], p0[1] + o[1]], [p3[0] + i[0], p3[1] + i[1]]);
|
||||
let u = 1.0 - t;
|
||||
let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
|
||||
Some([a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0], a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1]])
|
||||
}
|
||||
|
||||
fn feather_index(p: &Value, sp: &ShapePath, c: &str) -> Result<usize> {
|
||||
let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad(c, "missing `index` (feather point, 0-based)"))? as usize;
|
||||
if i >= sp.feather.len() {
|
||||
return Err(bad(c, format!("no feather point {i} (the mask has {})", sp.feather.len())));
|
||||
}
|
||||
Ok(i)
|
||||
}
|
||||
|
||||
/// Mask Feather tool: add a feather point on the path, by `segment`/`t` or at the path position
|
||||
/// nearest `point` (layer space). Without `radius`, a `point` off the path sets it from its
|
||||
/// distance (outside the mask = outer feather, inside = inner).
|
||||
fn feather_add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "mask.featherPoint.add";
|
||||
let seg = p.get("segment").and_then(Value::as_u64).map(|v| v as usize);
|
||||
let t = super::f_p(p, "t").map(|v| v.clamp(0.0, 1.0));
|
||||
let q = pt(p.get("point"));
|
||||
let radius = super::f_p(p, "radius");
|
||||
let tension = super::f_p(p, "tension").unwrap_or(0.0).clamp(0.0, 100.0) / 100.0;
|
||||
let (uid, i) = edit_path(s, p, c, |sp| {
|
||||
let (seg, t, r) = match (seg, q) {
|
||||
(Some(seg), _) => {
|
||||
if seg >= sp.segment_count() {
|
||||
return Err(bad(c, format!("no segment {seg}")));
|
||||
}
|
||||
(seg, t.unwrap_or(0.5), radius.unwrap_or(0.0))
|
||||
}
|
||||
(None, Some(q)) => {
|
||||
let (seg, t, d) = nearest_on_path(sp, q).ok_or_else(|| bad(c, "the path has no segments"))?;
|
||||
(seg, t, radius.unwrap_or(if inside_path(sp, q) { -d } else { d }))
|
||||
}
|
||||
(None, None) => return Err(bad(c, "give `segment` (and `t`) or `point`")),
|
||||
};
|
||||
sp.feather.push(effectcraft_keyframe::FeatherPoint { segment: seg, t, radius: r, tension });
|
||||
Ok(sp.feather.len() - 1)
|
||||
})?;
|
||||
Ok(json!({"mask": uid, "index": i}))
|
||||
}
|
||||
|
||||
/// Drag a feather point: move it along the path (`segment`/`t`, or nearest `point`) and/or set
|
||||
/// its `radius` (signed: negative = inner) and `tension` (%).
|
||||
fn feather_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "mask.featherPoint.set";
|
||||
let seg = p.get("segment").and_then(Value::as_u64).map(|v| v as usize);
|
||||
let t = super::f_p(p, "t").map(|v| v.clamp(0.0, 1.0));
|
||||
let q = pt(p.get("point"));
|
||||
let radius = super::f_p(p, "radius");
|
||||
let tension = super::f_p(p, "tension").map(|v| v.clamp(0.0, 100.0) / 100.0);
|
||||
let toward = pt(p.get("toward"));
|
||||
let (_, out) = edit_path(s, p, c, |sp| {
|
||||
let i = feather_index(p, sp, c)?;
|
||||
if let Some(q) = q {
|
||||
let (sg, tt, _) = nearest_on_path(sp, q).ok_or_else(|| bad(c, "the path has no segments"))?;
|
||||
sp.feather[i].segment = sg;
|
||||
sp.feather[i].t = tt;
|
||||
}
|
||||
if let Some(sg) = seg {
|
||||
if sg >= sp.segment_count() {
|
||||
return Err(bad(c, format!("no segment {sg}")));
|
||||
}
|
||||
sp.feather[i].segment = sg;
|
||||
}
|
||||
if let Some(t) = t {
|
||||
sp.feather[i].t = t;
|
||||
}
|
||||
if let Some(r) = radius {
|
||||
sp.feather[i].radius = r;
|
||||
}
|
||||
// Dragging the radius handle: the distance from the point's path position to `toward`,
|
||||
// outer outside the mask, inner inside.
|
||||
if let Some(w) = toward {
|
||||
let f = sp.feather[i];
|
||||
let at = point_on(sp, f.segment, f.t).ok_or_else(|| bad(c, "the feather point is off the path"))?;
|
||||
let d = (w[0] - at[0]).hypot(w[1] - at[1]);
|
||||
sp.feather[i].radius = if inside_path(sp, w) { -d } else { d };
|
||||
}
|
||||
if let Some(k) = tension {
|
||||
sp.feather[i].tension = k;
|
||||
}
|
||||
Ok(serde_json::to_value(sp.feather[i]).unwrap_or(Value::Null))
|
||||
})?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn feather_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "mask.featherPoint.remove";
|
||||
let all = super::b_p(p, "all").unwrap_or(false);
|
||||
let (_, n) = edit_path(s, p, c, |sp| {
|
||||
if all {
|
||||
sp.feather.clear();
|
||||
} else {
|
||||
let i = feather_index(p, sp, c)?;
|
||||
sp.feather.remove(i);
|
||||
}
|
||||
Ok(sp.feather.len())
|
||||
})?;
|
||||
Ok(json!({"remaining": n}))
|
||||
}
|
||||
|
||||
fn feather_list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "mask.featherPoint.list";
|
||||
let (cid, lid) = layer_p(s, p, c)?;
|
||||
let key = p.get("mask").cloned().ok_or_else(|| bad(c, "missing `mask`"))?;
|
||||
let t = s.time();
|
||||
let mut props = s.project.comp(cid).and_then(|cc| cc.layer(lid)).ok_or(EngineError::NoComp)?.props.clone();
|
||||
let lt = s.project.comp(cid).and_then(|cc| cc.layer(lid)).map(|l| l.layer_time(t)).unwrap_or(t);
|
||||
let g = path_group(&mut props, &key).ok_or_else(|| bad(c, "no such mask"))?;
|
||||
let Some(KV::Path(sp)) = g.get("path").map(|pr| pr.value_at(lt)) else { return Err(bad(c, "mask has no path")) };
|
||||
Ok(
|
||||
json!({"points": sp.feather.iter().map(|f| json!({"segment": f.segment, "t": f.t, "radius": f.radius, "tension": f.tension * 100.0})).collect::<Vec<_>>()}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Add Vertex tool: insert a vertex on segment `segment` at parameter `t` (default 0.5).
|
||||
fn insert_vertex(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let seg =
|
||||
@@ -454,6 +646,26 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("mask.deleteVertices", "Delete Mask Vertices", [], None, "{vertices?}", has_vertices, delete_vertices),
|
||||
cmd!("mask.convertVertex", "Convert Vertex", [], None, "{layer?, mask: uid (mask or shape Path item), index, smooth?}", has_comp, convert_vertex),
|
||||
cmd!("mask.insertVertex", "Add Vertex", [], None, "{layer?, mask: uid (mask or shape Path item), segment, t?: 0..1}", has_comp, insert_vertex),
|
||||
cmd!(
|
||||
"mask.featherPoint.add",
|
||||
"Add Mask Feather Point",
|
||||
[],
|
||||
None,
|
||||
"{layer?, mask, segment?, t?: 0..1, point?: [x,y] (layer space), radius? (px, negative = inner), tension? (%)} → {index}",
|
||||
has_comp,
|
||||
feather_add
|
||||
),
|
||||
cmd!(
|
||||
"mask.featherPoint.set",
|
||||
"Move Mask Feather Point",
|
||||
[],
|
||||
None,
|
||||
"{layer?, mask, index, segment?, t?, point? (slide along the path), radius?, toward?: [x,y] (radius from the drag point, layer space), tension? (%), merge?}",
|
||||
has_comp,
|
||||
feather_set
|
||||
),
|
||||
cmd!("mask.featherPoint.remove", "Delete Mask Feather Point", [], None, "{layer?, mask, index? | all?}", has_comp, feather_remove),
|
||||
crate::query!("mask.featherPoint.list", "Mask Feather Points", "{layer?, mask}", feather_list),
|
||||
cmd!("mask.remove", "Remove Mask", [], None, "{layer?, mask}", has_layers, |s, p| remove_masks(s, p, false)),
|
||||
cmd!("mask.removeAll", "Remove All Masks", [], None, "{layer?}", has_layers, |s, p| remove_masks(s, p, true)),
|
||||
]
|
||||
|
||||
@@ -11,10 +11,14 @@ mod comp_more;
|
||||
mod create;
|
||||
mod edit;
|
||||
mod effect;
|
||||
pub mod essential;
|
||||
pub mod expr_tools;
|
||||
mod file;
|
||||
mod file_more;
|
||||
pub(crate) mod file_more;
|
||||
mod focus;
|
||||
mod frontend;
|
||||
mod help;
|
||||
mod key_labels;
|
||||
mod key_transform;
|
||||
mod keys_more;
|
||||
mod layer;
|
||||
@@ -32,11 +36,13 @@ mod paths;
|
||||
mod project_items;
|
||||
mod prop;
|
||||
mod prop_groups;
|
||||
mod proxy;
|
||||
pub mod puppet;
|
||||
mod query;
|
||||
mod render_queue;
|
||||
pub mod roto_cmds;
|
||||
mod settings;
|
||||
mod shape_stroke;
|
||||
mod stubs;
|
||||
mod styles;
|
||||
mod text_anim;
|
||||
@@ -139,6 +145,9 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(animation::specs());
|
||||
v.extend(view::specs());
|
||||
v.extend(viewer_cmds::specs());
|
||||
v.extend(shape_stroke::specs());
|
||||
v.extend(focus::specs());
|
||||
v.extend(key_labels::specs());
|
||||
v.extend(key_transform::specs());
|
||||
v.extend(file_more::specs());
|
||||
v.extend(lottie::specs());
|
||||
@@ -155,11 +164,19 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(settings::specs());
|
||||
v.extend(app_more::specs());
|
||||
v.extend(keys_more::specs());
|
||||
v.extend(essential::specs());
|
||||
v.extend(expr_tools::specs());
|
||||
v.extend(proxy::specs());
|
||||
v.extend(stubs::specs());
|
||||
v
|
||||
})
|
||||
}
|
||||
|
||||
/// Set `footage` as the proxy of `item` (File ▸ Create Proxy's post-render action).
|
||||
pub(crate) fn proxy_set(s: &mut Session, item: ItemId, footage: effectcraft_project::Footage) -> Result<()> {
|
||||
proxy::set_proxy_footage(s, &[item], footage)
|
||||
}
|
||||
|
||||
/// (id, name) of the text animation presets.
|
||||
pub fn text_preset_list() -> Vec<(String, String)> {
|
||||
text_anim::preset_names()
|
||||
|
||||
@@ -557,7 +557,8 @@ fn convert_expr_to_keys(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let fd = comp.frame_duration();
|
||||
let mut t = layer.in_point;
|
||||
while t < layer.out_point {
|
||||
let ctx = effectcraft_render::EvalCtx { project: &s.project, comp_id: cid, comp: &comp, time: t, expr: s.expr.as_deref() };
|
||||
let ctx =
|
||||
effectcraft_render::EvalCtx { project: &s.project, comp_id: cid, comp: &comp, time: t, expr: s.expr.as_deref(), footage: Some(s.footage.as_ref()) };
|
||||
keys.push(Keyframe::new(layer.layer_time(t), ctx.value(&layer, &pr)));
|
||||
t += fd;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
//! Proxies (File ▸ Create Proxy / Set Proxy / Interpret Footage ▸ Proxy): a stand-in file for
|
||||
//! a footage item or a composition. The Project panel's proxy switch (`file.useProxy`) turns
|
||||
//! it on or off per item; renders follow Render Settings ▸ Proxy Use (the viewer uses each
|
||||
//! item's switch).
|
||||
|
||||
use effectcraft_project::render_queue::{Channels, OutputFormat, OutputModule, PostRenderAction, ProResProfile, RenderQuality, RenderQueueItem, TimeSpan};
|
||||
use effectcraft_project::{Footage, ItemId, ItemKind, Proxy};
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, b_p, bad, has_project_selection, str_p};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
/// Footage items and comps a proxy command acts on: `items`/`item`, else the Project panel
|
||||
/// selection.
|
||||
fn targets(s: &Session, p: &Value) -> Vec<ItemId> {
|
||||
let ids: Vec<ItemId> = match p.get("items").or(p.get("item")) {
|
||||
Some(Value::Array(a)) => a.iter().filter_map(Value::as_u64).map(ItemId).collect(),
|
||||
Some(Value::Number(n)) => n.as_u64().map(ItemId).into_iter().collect(),
|
||||
Some(Value::String(name)) => s.project.find_by_name(name).map(|i| i.id).into_iter().collect(),
|
||||
_ => s.state.project_selection.clone(),
|
||||
};
|
||||
ids.into_iter().filter(|i| matches!(s.project.item(*i).map(|x| &x.kind), Some(ItemKind::Footage(_) | ItemKind::Comp(_)))).collect()
|
||||
}
|
||||
|
||||
fn has_targets(s: &Session) -> std::result::Result<(), String> {
|
||||
has_project_selection(s)?;
|
||||
if targets(s, &Value::Null).is_empty() { Err("select footage or a composition in the Project panel".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
fn has_proxy(s: &Session) -> std::result::Result<(), String> {
|
||||
has_targets(s)?;
|
||||
if targets(s, &Value::Null).iter().any(|i| s.project.item(*i).is_some_and(|x| x.proxy.is_some())) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("the selected items have no proxy".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Probe a proxy file through the importer.
|
||||
fn probe(s: &Session, path: &str, cmd: &str) -> Result<Footage> {
|
||||
let importer = s.importer.clone().ok_or_else(|| EngineError::Other("media import is not available in this build".into()))?;
|
||||
let f = importer.probe(path).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
if !f.has_video {
|
||||
return Err(bad(cmd, format!("{path} has no video to use as a proxy")));
|
||||
}
|
||||
Ok(f)
|
||||
}
|
||||
|
||||
/// Attach `footage` as the proxy of `items` (Use Proxy on). One undo step.
|
||||
pub(crate) fn set_proxy_footage(s: &mut Session, items: &[ItemId], footage: Footage) -> Result<()> {
|
||||
s.edit("Set Proxy", None, |proj, _| {
|
||||
for i in items {
|
||||
if let Some(it) = proj.item_mut(*i) {
|
||||
it.proxy = Some(Box::new(Proxy { footage: footage.clone(), enabled: true }));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn set_proxy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "file.setProxy";
|
||||
let items = targets(s, p);
|
||||
if items.is_empty() {
|
||||
return Err(bad(C, "select footage or a composition"));
|
||||
}
|
||||
let path = str_p(p, "path").ok_or_else(|| bad(C, "missing `path`"))?.to_string();
|
||||
let f = probe(s, &path, C)?;
|
||||
let (w, h) = (f.width, f.height);
|
||||
set_proxy_footage(s, &items, f)?;
|
||||
Ok(json!({"items": items.iter().map(|i| i.0).collect::<Vec<_>>(), "path": path, "width": w, "height": h}))
|
||||
}
|
||||
|
||||
fn set_proxy_none(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let items = targets(s, p);
|
||||
s.edit("Set Proxy None", None, |proj, _| {
|
||||
for i in &items {
|
||||
if let Some(it) = proj.item_mut(*i) {
|
||||
it.proxy = None;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"items": items.iter().map(|i| i.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
/// The Project panel's proxy switch: use the proxy (filled box) or the full-resolution source.
|
||||
fn use_proxy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "file.useProxy";
|
||||
let items: Vec<ItemId> = targets(s, p).into_iter().filter(|i| s.project.item(*i).is_some_and(|x| x.proxy.is_some())).collect();
|
||||
if items.is_empty() {
|
||||
return Err(bad(C, "the selected items have no proxy"));
|
||||
}
|
||||
let first = s.project.item(items[0]).and_then(|x| x.proxy.as_ref()).is_some_and(|px| px.enabled);
|
||||
let on = b_p(p, "on").unwrap_or(!first);
|
||||
s.edit(if on { "Use Proxy" } else { "Use Full Resolution" }, None, |proj, _| {
|
||||
for i in &items {
|
||||
if let Some(px) = proj.item_mut(*i).and_then(|x| x.proxy.as_mut()) {
|
||||
px.enabled = on;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"items": items.iter().map(|i| i.0).collect::<Vec<_>>(), "on": on}))
|
||||
}
|
||||
|
||||
/// File ▸ Interpret Footage ▸ Proxy: Interpret Footage settings for the proxy file.
|
||||
fn interpret_proxy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "file.interpretProxy";
|
||||
let items: Vec<ItemId> = targets(s, p).into_iter().filter(|i| s.project.item(*i).is_some_and(|x| x.proxy.is_some())).collect();
|
||||
if items.is_empty() {
|
||||
return Err(bad(C, "the selected items have no proxy"));
|
||||
}
|
||||
let it = super::file_more::Interpretation::parse(p, C)?;
|
||||
let guesses: Vec<_> = items
|
||||
.iter()
|
||||
.map(|i| {
|
||||
let px = s.project.item(*i).and_then(|x| x.proxy.as_ref());
|
||||
match (p.get("alpha").and_then(Value::as_str) == Some("guess") || b_p(p, "guessAlpha") == Some(true), px) {
|
||||
(true, Some(px)) => super::file_more::guess_alpha(s, *i, &px.footage),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
s.edit("Interpret Proxy", None, |proj, _| {
|
||||
for (i, g) in items.iter().zip(&guesses) {
|
||||
if let Some(px) = proj.item_mut(*i).and_then(|x| x.proxy.as_mut()) {
|
||||
it.apply(&mut px.footage, *g);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"items": items.iter().map(|i| i.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
/// File ▸ Create Proxy ▸ Still / Movie: queue a half-resolution render of the composition whose
|
||||
/// post-render action sets the result as its proxy.
|
||||
fn create_proxy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "file.createProxy";
|
||||
let cid = match p.get("comp").or(p.get("item")) {
|
||||
Some(_) => {
|
||||
let q = json!({"comp": p.get("comp").or(p.get("item")).cloned()});
|
||||
super::comp_id(s, &q)?
|
||||
}
|
||||
None => s
|
||||
.state
|
||||
.project_selection
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|i| s.project.comp(*i).is_some())
|
||||
.or(s.active_comp_id())
|
||||
.ok_or_else(|| bad(C, "select a composition"))?,
|
||||
};
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
|
||||
let still = match str_p(p, "kind").unwrap_or("movie") {
|
||||
"still" => true,
|
||||
"movie" => false,
|
||||
k => return Err(bad(C, format!("kind: still|movie, not `{k}`"))),
|
||||
};
|
||||
let mut it = RenderQueueItem::new(0, cid);
|
||||
it.settings.quality = RenderQuality::Draft;
|
||||
it.settings.resolution = p.get("resolution").and_then(Value::as_f64).unwrap_or(0.5).clamp(0.05, 1.0);
|
||||
if still {
|
||||
// One frame at the current time (the comp's poster frame when not the active comp).
|
||||
let t = if s.active_comp_id() == Some(cid) { s.time() } else { comp.poster_time };
|
||||
it.settings.time_span = TimeSpan::Custom { start: t, end: t + comp.frame_duration() };
|
||||
it.output = OutputModule::for_format(OutputFormat::PngSequence);
|
||||
it.output.output = "[compName]_proxy_[#####].png".into();
|
||||
} else {
|
||||
it.settings.time_span = TimeSpan::LengthOfComp;
|
||||
it.output = OutputModule::for_format(OutputFormat::ProRes);
|
||||
it.output.prores_profile = ProResProfile::P4444;
|
||||
it.output.output = "[compName]_proxy.[fileExtension]".into();
|
||||
}
|
||||
it.output.channels = Channels::Rgba;
|
||||
if let Some(o) = str_p(p, "path").or(str_p(p, "output")) {
|
||||
it.output.output = o.to_string();
|
||||
}
|
||||
it.post_render = PostRenderAction::SetProxy;
|
||||
let id = s.edit("Create Proxy", None, |proj, _| {
|
||||
it.id = proj.render_queue.iter().map(|i| i.id).max().unwrap_or(0) + 1;
|
||||
let id = it.id;
|
||||
proj.render_queue.push(it);
|
||||
Ok(id)
|
||||
})?;
|
||||
let path = s.project.render_queue.last().and_then(|i| s.resolve_output(i));
|
||||
Ok(json!({"item": id, "comp": cid.0, "kind": if still { "still" } else { "movie" }, "output": path, "time": Tick::ZERO.seconds()}))
|
||||
}
|
||||
|
||||
fn has_comp_selection(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.state.project_selection.iter().any(|i| s.project.comp(*i).is_some()) || s.active_comp_id().is_some() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("select a composition".into())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"file.createProxy",
|
||||
"Create Proxy",
|
||||
[],
|
||||
None,
|
||||
"{kind: still|movie, comp?|item?, path?|output? (template), resolution? (default 0.5)}",
|
||||
has_comp_selection,
|
||||
create_proxy
|
||||
),
|
||||
cmd!("file.setProxy", "File...", ["File", "Set Proxy"], None, "{path, items?|item?}", has_targets, set_proxy),
|
||||
cmd!("file.setProxyNone", "None", ["File", "Set Proxy"], None, "{items?|item?}", has_proxy, set_proxy_none),
|
||||
cmd!("file.useProxy", "Use Proxy", [], None, "{items?|item?, on?}", has_proxy, use_proxy),
|
||||
cmd!(
|
||||
"file.interpretProxy",
|
||||
"Proxy...",
|
||||
["File", "Interpret Footage"],
|
||||
None,
|
||||
"{items?|item?, alpha?, matteColor?, invertAlpha?, frameRate?, loop?, pixelAspect?, fields?, colorProfile?, linearLight?}",
|
||||
has_proxy,
|
||||
interpret_proxy
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -29,7 +29,7 @@ pub fn puppet_eval(s: &Session, cid: ItemId, lid: LayerId, fx_uid: Uid, t: Tick)
|
||||
let fx = layer.effects()?;
|
||||
let index = fx.groups().position(|g| g.uid == fx_uid)?;
|
||||
let g = fx.groups().nth(index)?;
|
||||
let ctx = EvalCtx { project: &s.project, comp_id: cid, comp, time: t, expr: s.expr.as_deref() };
|
||||
let ctx = EvalCtx { project: &s.project, comp_id: cid, comp, time: t, expr: s.expr.as_deref(), footage: None };
|
||||
let mut r = Renderer::new(&s.project, &*s.footage, RenderOpts::default());
|
||||
r.expr = s.expr.as_deref();
|
||||
r.cache = Some(&s.layer_cache);
|
||||
|
||||
@@ -104,6 +104,10 @@ fn apply_settings(rs: &mut RenderSettings, p: &Value, cmd: &str) -> Result<bool>
|
||||
{
|
||||
return Err(bad(cmd, "end must be after start"));
|
||||
}
|
||||
if let Some(u) = str_p(p, "proxyUse") {
|
||||
rs.proxy_use = effectcraft_project::render_queue::ProxyUse::parse(u).ok_or_else(|| bad(cmd, "proxyUse: current|all|comp|none"))?;
|
||||
any = true;
|
||||
}
|
||||
match p.get("frameRate") {
|
||||
Some(Value::Null) => {
|
||||
rs.frame_rate = None;
|
||||
@@ -516,7 +520,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add to Render Queue",
|
||||
["Composition"],
|
||||
Some("Cmd+M"),
|
||||
"{comp?: id|name, format?: h264|prores|webm|png|jpeg|tiff|exr|gif|wav|aiff, output?: path|template, quality?: best|draft|1-100 (jpeg, webm), resolution?: full|half|third|quarter|scale, timeSpan?: workArea|comp|custom, start?: s, end?: s, frameRate?: fps|null, motionBlur?: bool, skipExisting?: bool, channels?: rgb|rgba, bitrate?: kbps, proresProfile?: proxy|lt|standard|hq|4444|4444xq, audio?: auto|on|off, sampleRate?, loop?: bool}",
|
||||
"{comp?: id|name, format?: h264|prores|webm|png|jpeg|tiff|exr|gif|wav|aiff, output?: path|template, quality?: best|draft|1-100 (jpeg, webm), resolution?: full|half|third|quarter|scale, timeSpan?: workArea|comp|custom, start?: s, end?: s, frameRate?: fps|null, motionBlur?: bool, skipExisting?: bool, proxyUse?: current|all|comp|none, channels?: rgb|rgba, bitrate?: kbps, proresProfile?: proxy|lt|standard|hq|4444|4444xq, audio?: auto|on|off, sampleRate?, loop?: bool}",
|
||||
can_add,
|
||||
add
|
||||
),
|
||||
@@ -527,7 +531,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Render Settings...",
|
||||
[],
|
||||
None,
|
||||
"{item?|index?, quality?: best|draft, resolution?: full|half|third|quarter|scale, timeSpan?: workArea|comp|custom, start?: s, end?: s, frameRate?: fps|null, motionBlur?: bool, skipExisting?: bool}",
|
||||
"{item?|index?, quality?: best|draft, resolution?: full|half|third|quarter|scale, timeSpan?: workArea|comp|custom, start?: s, end?: s, frameRate?: fps|null, motionBlur?: bool, skipExisting?: bool, proxyUse?: current|all|comp|none}",
|
||||
has_items,
|
||||
set_render_settings
|
||||
),
|
||||
|
||||
@@ -239,7 +239,7 @@ fn auto_save(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
fn recovery_info(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let root = s.default_autosave_root();
|
||||
let latest = crate::autosave::latest(&s.prefs, s.path.as_deref(), root.as_deref()).map(|p| p.to_string_lossy().to_string());
|
||||
let latest = crate::autosave::latest_in(s.file_ops(), &s.prefs, s.path.as_deref(), root.as_deref()).map(|p| p.to_string_lossy().to_string());
|
||||
Ok(json!({
|
||||
"lastAutoSave": s.autosave.last_path,
|
||||
"latestOnDisk": latest,
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
//! Shape Stroke options: the Dashes "+" / "−" buttons (Dash 2 / Gap 2, Dash 3 / Gap 3), Taper and
|
||||
//! Wave. Taper and Wave are ordinary properties of the stroke (`…/stroke/taper/startLength`); the
|
||||
//! commands here set several of them in one undo step and add the groups to strokes saved before
|
||||
//! they existed.
|
||||
|
||||
use effectcraft_keyframe::Value as KV;
|
||||
use effectcraft_project::build::{self, EXTRA_DASHES, Ids};
|
||||
use effectcraft_project::{ItemId, LayerId, PropGroup, Uid};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, bad, has_layers, layer_mut, layer_p, merge_p};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
fn is_stroke(g: &PropGroup) -> bool {
|
||||
matches!(g.match_id.as_str(), "stroke" | "gstroke")
|
||||
}
|
||||
|
||||
/// `{layer?, prop?: stroke uid}` → the stroke; without `prop`, the first stroke of the layer (a
|
||||
/// selected stroke property wins).
|
||||
fn stroke_ref(s: &Session, p: &Value, cmd: &str) -> Result<(ItemId, LayerId, Uid)> {
|
||||
let (cid, lid) = layer_p(s, p, cmd)?;
|
||||
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?;
|
||||
if let Some(uid) = p.get("prop").and_then(Value::as_u64) {
|
||||
let g = l.props.find_group(uid).ok_or_else(|| bad(cmd, format!("no property group @{uid}")))?;
|
||||
if !is_stroke(g) {
|
||||
return Err(bad(cmd, format!("`{}` is not a Stroke or Gradient Stroke", g.name)));
|
||||
}
|
||||
return Ok((cid, lid, uid));
|
||||
}
|
||||
let contents = l.props.sub("contents").ok_or_else(|| bad(cmd, "not a shape layer"))?;
|
||||
// A selected stroke (or a property inside one), else the first stroke in the contents.
|
||||
let mut found = None;
|
||||
for (sl, su) in &s.state.selected_props {
|
||||
if *sl == lid
|
||||
&& let Some(g) = find_stroke_containing(contents, *su)
|
||||
{
|
||||
found = Some(g);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if found.is_none() {
|
||||
let mut first = None;
|
||||
walk_groups(contents, &mut |g| {
|
||||
if first.is_none() && is_stroke(g) {
|
||||
first = Some(g.uid);
|
||||
}
|
||||
});
|
||||
found = first;
|
||||
}
|
||||
found.map(|u| (cid, lid, u)).ok_or_else(|| bad(cmd, "the layer has no stroke"))
|
||||
}
|
||||
|
||||
fn walk_groups(g: &PropGroup, f: &mut impl FnMut(&PropGroup)) {
|
||||
for sub in g.groups() {
|
||||
f(sub);
|
||||
walk_groups(sub, f);
|
||||
}
|
||||
}
|
||||
|
||||
fn find_stroke_containing(contents: &PropGroup, uid: Uid) -> Option<Uid> {
|
||||
let mut out = None;
|
||||
walk_groups(contents, &mut |g| {
|
||||
if out.is_none() && is_stroke(g) && (g.uid == uid || g.find(uid).is_some() || g.find_group(uid).is_some()) {
|
||||
out = Some(g.uid);
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn dashes_add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "shape.dashes.add";
|
||||
let (cid, lid, uid) = stroke_ref(s, p, c)?;
|
||||
s.edit("Add Dash", None, |proj, _| {
|
||||
let mut next = proj.next_id;
|
||||
let g = layer_mut(proj, cid, lid)?.props.find_group_mut(uid).ok_or_else(|| bad(c, "stroke vanished"))?;
|
||||
let d = g.sub_mut("dashes").ok_or_else(|| bad(c, "the stroke has no Dashes group"))?;
|
||||
// Before the first "+", Dash is 0 (no dashes): the first "+" turns it on.
|
||||
let dash = d.get("dash").map(|p| p.value.as_f64()).unwrap_or(0.0);
|
||||
let mut ids = Ids(&mut next);
|
||||
let added = if dash <= 0.0 {
|
||||
if let Some(p) = d.get_mut("dash") {
|
||||
p.value = KV::Scalar(10.0);
|
||||
}
|
||||
"dash"
|
||||
} else {
|
||||
let Some((dm, gm)) = EXTRA_DASHES.iter().find(|(dm, _)| d.get(dm).is_none()) else {
|
||||
return Err(bad(c, "a stroke has at most three dash/gap pairs"));
|
||||
};
|
||||
let k = if *dm == "dash2" { 2 } else { 3 };
|
||||
// Insert before Offset, which stays last.
|
||||
let at = d.children.iter().position(|n| n.match_id() == "offset").unwrap_or(d.children.len());
|
||||
let dv = d.get("dash").map(|p| p.value.as_f64()).unwrap_or(10.0);
|
||||
let gv = d.get("gap").map(|p| p.value.as_f64()).filter(|g| *g > 0.0).unwrap_or(dv);
|
||||
d.children.insert(at, ids.prop(gm, &format!("Gap {k}"), KV::Scalar(gv)).with_ui(effectcraft_project::ParamUi::Pixels).into());
|
||||
d.children.insert(at, ids.prop(dm, &format!("Dash {k}"), KV::Scalar(dv)).with_ui(effectcraft_project::ParamUi::Pixels).into());
|
||||
dm
|
||||
};
|
||||
proj.next_id = next;
|
||||
Ok(json!({"added": added}))
|
||||
})
|
||||
}
|
||||
|
||||
fn dashes_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = "shape.dashes.remove";
|
||||
let (cid, lid, uid) = stroke_ref(s, p, c)?;
|
||||
s.edit("Remove Dash", None, |proj, _| {
|
||||
let g = layer_mut(proj, cid, lid)?.props.find_group_mut(uid).ok_or_else(|| bad(c, "stroke vanished"))?;
|
||||
let d = g.sub_mut("dashes").ok_or_else(|| bad(c, "the stroke has no Dashes group"))?;
|
||||
for (dm, gm) in EXTRA_DASHES.iter().rev() {
|
||||
if d.get(dm).is_some() {
|
||||
d.children.retain(|n| n.match_id() != *dm && n.match_id() != *gm);
|
||||
return Ok(json!({"removed": dm}));
|
||||
}
|
||||
}
|
||||
// The last "−" turns dashes off.
|
||||
if let Some(p) = d.get_mut("dash") {
|
||||
p.value = KV::Scalar(0.0);
|
||||
p.keys.clear();
|
||||
}
|
||||
Ok(json!({"removed": "dash"}))
|
||||
})
|
||||
}
|
||||
|
||||
/// Set `fields` (`param name → (match id, kind)`) of the stroke's `group`, creating the group.
|
||||
fn set_group(s: &mut Session, p: &Value, c: &str, group: &str, fields: &[(&str, &str, bool)]) -> Result<Value> {
|
||||
let (cid, lid, uid) = stroke_ref(s, p, c)?;
|
||||
let t = s.time();
|
||||
let label = if group == "taper" { "Stroke Taper" } else { "Stroke Wave" };
|
||||
s.edit(label, merge_p(p), |proj, _| {
|
||||
let mut next = proj.next_id;
|
||||
{
|
||||
let g = layer_mut(proj, cid, lid)?.props.find_group_mut(uid).ok_or_else(|| bad(c, "stroke vanished"))?;
|
||||
if g.sub(group).is_none() {
|
||||
let mut ids = Ids(&mut next);
|
||||
let ng = if group == "taper" { build::stroke_taper(&mut ids) } else { build::stroke_wave(&mut ids) };
|
||||
g.children.push(ng.into());
|
||||
}
|
||||
}
|
||||
proj.next_id = next;
|
||||
let l = layer_mut(proj, cid, lid)?;
|
||||
let lt = l.layer_time(t);
|
||||
let g = l.props.find_group_mut(uid).ok_or_else(|| bad(c, "stroke vanished"))?;
|
||||
let sub = g.sub_mut(group).ok_or_else(|| bad(c, "group vanished"))?;
|
||||
let mut out = serde_json::Map::new();
|
||||
for (param, m, is_enum) in fields {
|
||||
let Some(v) = p.get(*param) else { continue };
|
||||
let pr = sub.get_mut(m).ok_or_else(|| bad(c, format!("no {m}")))?;
|
||||
let nv = if *is_enum {
|
||||
let opts: &[&str] = if *m == "units" && group == "taper" { &["pixels", "percent"] } else { &["pixels", "cycles"] };
|
||||
let i = match v {
|
||||
Value::String(s) => {
|
||||
opts.iter().position(|o| o.eq_ignore_ascii_case(s)).ok_or_else(|| bad(c, format!("`{param}` is one of {opts:?}")))? as u32
|
||||
}
|
||||
Value::Number(n) => n.as_u64().unwrap_or(0).min(opts.len() as u64 - 1) as u32,
|
||||
_ => return Err(bad(c, format!("bad `{param}`"))),
|
||||
};
|
||||
KV::Enum(i)
|
||||
} else {
|
||||
let x = v.as_f64().ok_or_else(|| bad(c, format!("`{param}` must be a number")))?;
|
||||
let x = if let effectcraft_project::ParamUi::Slider { min, max, .. } = pr.ui { x.clamp(min, max) } else { x.max(0.0) };
|
||||
KV::Scalar(x)
|
||||
};
|
||||
pr.set_value_at(lt, nv.clone());
|
||||
out.insert(param.to_string(), nv.to_json());
|
||||
}
|
||||
Ok(json!({"stroke": uid, group: Value::Object(out)}))
|
||||
})
|
||||
}
|
||||
|
||||
fn taper(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
set_group(
|
||||
s,
|
||||
p,
|
||||
"shape.stroke.taper",
|
||||
"taper",
|
||||
&[
|
||||
("units", "units", true),
|
||||
("startLength", "startLength", false),
|
||||
("endLength", "endLength", false),
|
||||
("startWidth", "startWidth", false),
|
||||
("endWidth", "endWidth", false),
|
||||
("startEase", "startEase", false),
|
||||
("endEase", "endEase", false),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn wave(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
set_group(
|
||||
s,
|
||||
p,
|
||||
"shape.stroke.wave",
|
||||
"wave",
|
||||
&[("amount", "amount", false), ("units", "units", true), ("wavelength", "wavelength", false), ("cycles", "cycles", false), ("phase", "phase", false)],
|
||||
)
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("shape.dashes.add", "Add Dash or Gap", [], None, "{layer?, prop?: stroke uid}", has_layers, dashes_add),
|
||||
cmd!("shape.dashes.remove", "Remove Dash or Gap", [], None, "{layer?, prop?: stroke uid}", has_layers, dashes_remove),
|
||||
cmd!(
|
||||
"shape.stroke.taper",
|
||||
"Stroke Taper",
|
||||
[],
|
||||
None,
|
||||
"{layer?, prop?: stroke uid, units?: pixels|percent, startLength?, endLength?, startWidth? (%), endWidth? (%), startEase? (%), endEase? (%)}",
|
||||
has_layers,
|
||||
taper
|
||||
),
|
||||
cmd!(
|
||||
"shape.stroke.wave",
|
||||
"Stroke Wave",
|
||||
[],
|
||||
None,
|
||||
"{layer?, prop?: stroke uid, amount? (%), units?: pixels|cycles, wavelength?, cycles?, phase? (°)}",
|
||||
has_layers,
|
||||
wave
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -17,12 +17,6 @@ macro_rules! stub {
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
// Render queue / export (export milestone).
|
||||
stub!("file.createProxy", "Create Proxy", [], "{kind: still|movie}"),
|
||||
// Proxies (no proxy model yet).
|
||||
stub!("file.setProxy", "File...", ["File", "Set Proxy"], "{path}"),
|
||||
stub!("file.setProxyNone", "None", ["File", "Set Proxy"], "{}"),
|
||||
stub!("file.interpretProxy", "Proxy...", ["File", "Interpret Footage"], "{}"),
|
||||
// Layer ▸ New (3D / content-aware fill).
|
||||
stub!("layer.newContentAwareFill", "Content-Aware Fill Layer...", ["Layer", "New"], "{}"),
|
||||
// Mask options not in the mask model yet; pen / vertex editing (timeline milestone).
|
||||
@@ -34,9 +28,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
stub!("camera.stereoRig", "Create Stereo 3D Rig", ["Layer", "Camera"], "{}"),
|
||||
stub!("camera.orbitNull", "Create Orbit Null", ["Layer", "Camera"], "{}"),
|
||||
stub!("camera.fromModel", "Create Cameras from 3D Model", ["Layer", "Camera"], "{}"),
|
||||
stub!("camera.linkFocusToPoi", "Link Focus Distance to Point of Interest", ["Layer", "Camera"], "{}"),
|
||||
stub!("camera.linkFocusToLayer", "Link Focus Distance to Layer", ["Layer", "Camera"], "{}"),
|
||||
stub!("camera.setFocusToLayer", "Set Focus Distance to Layer", ["Layer", "Camera"], "{}"),
|
||||
stub!("light.fromModel", "Create Lights from 3D Model", ["Layer", "Light"], "{}"),
|
||||
stub!("light.controlWithCamera", "Control Light with Camera", ["Layer", "Light"], "{}"),
|
||||
stub!("light.environmentBackground", "Create Environment Light Background Layer", ["Layer", "Light"], "{}"),
|
||||
@@ -46,7 +37,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
stub!("view.displayColorManagement", "Use Display Color Management", ["View"], "{}"),
|
||||
stub!("view.simulateOutput", "Simulate Output", [], "{profile}"),
|
||||
// Keyframes / text / tracking.
|
||||
stub!("text.animatorFontAxes", "Variable Font Axes", ["Animation", "Animate Text"], "{}"),
|
||||
// Workspaces and panels that don't exist yet.
|
||||
stub!("window.unavailablePanel", "Panel", [], "{panel}"),
|
||||
]
|
||||
|
||||
@@ -372,6 +372,60 @@ fn list_presets(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(Value::Array(presets().iter().map(|p| json!({"id": p.get("id"), "name": p.get("name"), "description": p.get("description")})).collect()))
|
||||
}
|
||||
|
||||
/// Animation ▸ Animate Text ▸ Variable Font Axes: the axes of the layer's font, or (with `axis`)
|
||||
/// a new animator — or a property on `animator` — that offsets that axis (user units, weighted
|
||||
/// by the selectors, added to the axis default).
|
||||
fn font_axes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.animatorFontAxes";
|
||||
let (cid, lid) = layer_p(s, p, C)?;
|
||||
let layer = s.project.comp(cid).and_then(|c| c.layer(lid)).cloned().ok_or_else(|| bad(C, "no layer"))?;
|
||||
let Some(KV::Text(doc)) = layer.props.prop("text/sourceText").map(|pr| pr.value_at(layer.layer_time(s.time()))) else {
|
||||
return Err(bad(C, "not a text layer"));
|
||||
};
|
||||
let face = effectcraft_text::layout_doc(&doc).glyphs.first().map(|g| g.face).unwrap_or_else(|| effectcraft_text::resolve(&doc.font, &doc.style).face);
|
||||
let axes = effectcraft_text::variable::font_axes(face);
|
||||
let list = || json!(axes.iter().map(|a| json!({"tag": a.tag, "name": a.name, "min": a.min, "default": a.default, "max": a.max})).collect::<Vec<_>>());
|
||||
let Some(want) = str_p(p, "axis") else { return Ok(json!({"font": doc.font, "axes": list()})) };
|
||||
if axes.is_empty() {
|
||||
return Err(bad(C, format!("{} {} has no variation axes (not a variable font)", doc.font, doc.style)));
|
||||
}
|
||||
let axis = axes
|
||||
.iter()
|
||||
.find(|a| a.tag == want || a.name.eq_ignore_ascii_case(want))
|
||||
.ok_or_else(|| bad(C, format!("no axis `{want}`; the font has {}", list())))?
|
||||
.clone();
|
||||
let target = match p.get("animator") {
|
||||
Some(_) => Some(animator_uid(s, &layer, p, C)?),
|
||||
None => None,
|
||||
};
|
||||
let uid = s.edit("Add Variable Font Axis", None, |proj, _| {
|
||||
let mut next = proj.next_id;
|
||||
let mut ids = Ids(&mut next);
|
||||
let prop = ids
|
||||
.prop(&format!("{}{}", effectcraft_render::text::AXIS_PREFIX, axis.tag.trim_end()), &axis.name, KV::Scalar(0.0))
|
||||
.with_ui(effectcraft_project::ParamUi::Number);
|
||||
let l = layer_mut(proj, cid, lid)?;
|
||||
let uid = match target {
|
||||
Some(a) => {
|
||||
let g = l.props.find_group_mut(a).and_then(|g| g.sub_mut("properties")).ok_or_else(|| bad(C, "no such animator"))?;
|
||||
g.children.push(prop.into());
|
||||
a
|
||||
}
|
||||
None => {
|
||||
let anims = l.props.group_mut("text/animators").ok_or_else(|| bad(C, "not a text layer"))?;
|
||||
let name = format!("Animator {}", anims.children.len() + 1);
|
||||
let g = build::text_animator(&mut ids, &name, vec![prop]);
|
||||
let uid = g.uid;
|
||||
anims.children.push(g.into());
|
||||
uid
|
||||
}
|
||||
};
|
||||
proj.next_id = next;
|
||||
Ok(uid)
|
||||
})?;
|
||||
Ok(json!({"animator": uid, "axis": axis.tag}))
|
||||
}
|
||||
|
||||
fn list_kinds(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(Value::Array(build::TEXT_ANIMATOR_KINDS.iter().filter(|(k, _)| *k != "-").map(|(k, l)| json!({"property": k, "label": l})).collect()))
|
||||
}
|
||||
@@ -415,6 +469,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_text_layer,
|
||||
apply_preset
|
||||
),
|
||||
cmd!(
|
||||
"text.animatorFontAxes",
|
||||
"Variable Font Axes",
|
||||
["Animation", "Animate Text"],
|
||||
None,
|
||||
"{layer?, axis?: tag|name (omit to list the font's axes), animator?: uid|index}",
|
||||
has_text_layer,
|
||||
font_axes
|
||||
),
|
||||
query!("text.presets", "Text Animation Presets", "{}", list_presets),
|
||||
query!("text.animatorProperties", "Text Animator Properties", "{}", list_kinds),
|
||||
]
|
||||
|
||||
@@ -393,7 +393,7 @@ fn get_3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (w, h) = (comp.width as f64, comp.height as f64);
|
||||
let vs = s.state.views3d.get(&cid).cloned().unwrap_or_default();
|
||||
let t = s.state.times.get(&cid).copied().unwrap_or(Tick::ZERO);
|
||||
let ctx = EvalCtx { project: &s.project, comp_id: cid, comp, time: t, expr: s.expr.as_deref() };
|
||||
let ctx = EvalCtx { project: &s.project, comp_id: cid, comp, time: t, expr: s.expr.as_deref(), footage: None };
|
||||
let cam = vs.override_camera(w, h).unwrap_or_else(|| camera::active_camera(&ctx));
|
||||
let f = cam.forward();
|
||||
let lights: Vec<Value> = comp
|
||||
@@ -535,7 +535,7 @@ fn auto_orient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// through each layer's world matrix; cameras and lights contribute their position).
|
||||
fn layer_points(s: &Session, cid: ItemId, ids: &[LayerId], t: Tick) -> Vec<Vec3> {
|
||||
let Some(comp) = s.project.comp(cid) else { return vec![] };
|
||||
let ctx = EvalCtx { project: &s.project, comp_id: cid, comp, time: t, expr: s.expr.as_deref() };
|
||||
let ctx = EvalCtx { project: &s.project, comp_id: cid, comp, time: t, expr: s.expr.as_deref(), footage: None };
|
||||
let mut out = vec![];
|
||||
for l in comp.layers.iter().filter(|l| ids.contains(&l.id)) {
|
||||
let m = ctx.world_matrix(l);
|
||||
|
||||
@@ -224,7 +224,7 @@ fn new_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
*t = [r.x, r.y];
|
||||
}
|
||||
}
|
||||
let path = ShapePath { vertices: v, in_tangents: ins, out_tangents: outs, closed: b_p(p, "closed").unwrap_or(false) };
|
||||
let path = ShapePath { vertices: v, in_tangents: ins, out_tangents: outs, closed: b_p(p, "closed").unwrap_or(false), feather: Vec::new() };
|
||||
let fill = (!matches!(p.get("fill"), Some(Value::Null) | Some(Value::Bool(false)))).then(|| rgba(p.get("fill"), [0.25, 0.55, 1.0, 1.0]));
|
||||
let width = f_p(p, "strokeWidth").unwrap_or(2.0);
|
||||
let stroke = (width > 0.0).then(|| rgba(p.get("stroke"), [1.0, 1.0, 1.0, 1.0]));
|
||||
|
||||
Reference in New Issue
Block a user