Skip to content

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

Merge main into CMP-7/ANM-5/PRJ-8/PRJ-3 work

Brandon Thomasdbcda2eba920
diff --cc crates/engine/src/commands/file.rs
index 972e00eac,6999ac9d3..48285a33c
--- a/crates/engine/src/commands/file.rs
+++ b/crates/engine/src/commands/file.rs
@@@ -84,23 -84,50 +84,61 @@@ fn import(s: &mut Session, p: &Value) -
Some(Value::String(x)) => vec![x.clone()],
_ => return Err(bad("file.import", "missing `paths`")),
};
+ // Photoshop documents as compositions (Import As: Composition / – Retain Layer Sizes).
+ let import_as = str_p(p, "importAs").unwrap_or("footage");
+ let retain = match import_as {
+ "footage" => None,
+ "composition" | "comp" => Some(false),
+ "compositionLayerSizes" | "compositionRetainLayerSizes" | "layerSizes" => Some(true),
+ other => return Err(bad("file.import", format!("importAs: footage|composition|compositionLayerSizes, not `{other}`"))),
+ };
+ let mut paths = paths;
+ let mut out_comps = vec![];
let mut ids = vec![];
let mut errors = vec![];
+ if let Some(retain) = retain {
+ let mut rest = vec![];
+ for path in paths {
+ let bytes = match s.services.read_file(&path) {
+ Ok(b) if effectcraft_psd::is_psd(&b) => b,
+ _ => {
+ rest.push(path);
+ continue;
+ }
+ };
+ match import_psd_comp(s, &path, bytes, retain) {
+ Ok((comp, items, warnings)) => {
+ out_comps.push(comp);
+ ids.extend(items);
+ errors.extend(warnings);
+ }
+ Err(e) => errors.push(format!("{path}: {e}")),
+ }
+ }
+ paths = rest;
+ if paths.is_empty() {
+ if let Some(c) = out_comps.first() {
+ s.open_comp(effectcraft_project::ItemId(*c));
+ }
+ 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);
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 ▸ Sequence Footage frames per second.
@@@ -130,28 -172,39 +184,58 @@@
}
Ok(())
})?;
- Ok(json!({"items": ids, "errors": errors}))
+ if let Some(c) = out_comps.first() {
+ s.open_comp(effectcraft_project::ItemId(*c));
+ }
+ Ok(json!({"items": ids, "comps": out_comps, "errors": errors}))
+ }
+
+ /// A Photoshop layer by index or name (pixel layers only).
+ fn find_psd_layer(d: &effectcraft_psd::Psd, sel: &Value) -> Option<(usize, String)> {
+ let l = match sel {
+ Value::Number(n) => d.layers.get(n.as_u64()? as usize)?,
+ Value::String(name) => d.layers.iter().find(|l| &l.name == name)?,
+ _ => return None,
+ };
+ Some((l.index, l.name.clone()))
+ }
+
+ /// Import a Photoshop document as a composition (one undo step). Returns (comp, items, warnings).
+ fn import_psd_comp(s: &mut Session, path: &str, bytes: Vec<u8>, retain: bool) -> Result<(u64, Vec<u64>, Vec<String>)> {
+ let psd = effectcraft_psd::Psd::parse(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
+ let name = std::path::Path::new(path).file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "Photoshop".into());
+ let rate = effectcraft_time::FrameRate::FPS_29_97;
+ let secs = if s.prefs.import.still_footage == "seconds" { s.prefs.import.still_seconds } else { 10.0 };
+ let duration = rate.snap_nearest(effectcraft_time::Tick::from_seconds_f64(secs));
+ let r = s.edit("Import", None, |proj, st| {
+ let r = crate::psd_import::import(proj, &psd, path, &name, retain, rate, duration);
+ st.project_selection = vec![r.comp];
+ Ok(r)
+ })?;
+ let mut items = vec![r.folder.0];
+ items.extend(r.items.iter().map(|i| i.0));
+ 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") {
diff --cc crates/engine/src/commands/file_more.rs
index 45e6865ae,0b27d069d..6908bcd56
--- a/crates/engine/src/commands/file_more.rs
+++ b/crates/engine/src/commands/file_more.rs
@@@ -398,148 -419,30 +419,170 @@@ fn run_script(s: &mut Session, p: &Valu
Ok(json!({"steps": results.len(), "results": results}))
}
+ /// `.jsx` / `.js` (and `.jsxbin`, rejected) are JavaScript; `.json` / `.jsonl` / other files are
+ /// command scripts.
+ fn is_js_script(path: &str) -> bool {
+ let l = path.to_ascii_lowercase();
+ l.ends_with(".jsx") || l.ends_with(".js") || l.ends_with(".jsxbin")
+ }
+
+ /// Run JavaScript through the session's scripting engine.
+ fn run_js(s: &mut Session, code: &str, name: &str, console: bool) -> Result<Value> {
+ let runner = s.script.ok_or_else(|| EngineError::Other("JavaScript scripting is not available in this build".into()))?;
+ Ok(runner(s, &crate::ScriptRequest { code, name, console }))
+ }
+
+ /// `script.run`: run JavaScript (the After Effects scripting object model: `app.project`, comps,
+ /// layers, properties…) and report `{ok, result, output, error}`; script errors are reported in
+ /// `error` (with line and column), not as a command failure.
+ fn script_run(s: &mut Session, p: &Value) -> Result<Value> {
+ let code = str_p(p, "code").ok_or_else(|| bad("script.run", "missing `code` (JavaScript)"))?.to_string();
+ let name = str_p(p, "name").unwrap_or("script").to_string();
+ run_js(s, &code, &name, super::b_p(p, "console").unwrap_or(false))
+ }
+
// ---------------------------------------------------------------- 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() {
diff --cc crates/engine/src/commands/mod.rs
index 7d44f5e52,2e2d2782c..56a585dd6
--- a/crates/engine/src/commands/mod.rs
+++ b/crates/engine/src/commands/mod.rs
@@@ -4,14 -4,14 +4,16 @@@
mod anim;
pub mod anim_tools;
mod animation;
+ mod camera_cmds;
mod comp;
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 frontend;
mod help;
mod key_transform;
@@@ -29,7 -29,7 +31,8 @@@ pub mod paint
mod paths;
mod project_items;
mod prop;
+ mod prop_groups;
+mod proxy;
pub mod puppet;
mod query;
mod render_queue;
diff --cc crates/engine/src/commands/render_queue.rs
index acdf49127,be6cebfb7..91467ea52
--- a/crates/engine/src/commands/render_queue.rs
+++ b/crates/engine/src/commands/render_queue.rs
@@@ -513,7 -509,7 +513,7 @@@ pub fn specs() -> Vec<CommandSpec>
"Add to Render Queue",
["Composition"],
Some("Cmd+M"),
- "{comp?: id|name, format?: h264|prores|png|jpeg|tiff|exr|gif, output?: path|template, quality?: best|draft|1-100 (jpeg), 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}",
- "{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
),
diff --cc crates/engine/src/commands/stubs.rs
index b62f36546,27cbc5d47..764d6d99f
--- a/crates/engine/src/commands/stubs.rs
+++ b/crates/engine/src/commands/stubs.rs
@@@ -17,9 -17,12 +17,6 @@@ macro_rules! stub
pub fn specs() -> Vec<CommandSpec> {
vec![
- // macOS application menu items handled by the OS.
- stub!("app.hideOthers", "Hide Others", [], "{}"),
- stub!("app.showAll", "Show All", [], "{}"),
- // 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"], "{}"),
stub!("keys.selectLabelGroup", "Select Keyframe Label Group", [], "{scope}"),
// Layer ▸ New (3D / content-aware fill).
stub!("layer.newContentAwareFill", "Content-Aware Fill Layer...", ["Layer", "New"], "{}"),
diff --cc crates/engine/src/lib.rs
index b2c4d342e,a6dbe2c4b..2d5beb792
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -584,10 -639,12 +649,14 @@@ mod tests_3d
#[cfg(test)]
mod tests_anim_tools;
#[cfg(test)]
+ mod tests_camera_track;
+ #[cfg(test)]
+ mod tests_disk_cache;
+ #[cfg(test)]
mod tests_effects;
#[cfg(test)]
+mod tests_essential;
+#[cfg(test)]
mod tests_fidelity;
#[cfg(test)]
mod tests_lottie;
diff --cc crates/engine/src/menus.rs
index 6177e637d,0191c6eaa..66d198948
--- a/crates/engine/src/menus.rs
+++ b/crates/engine/src/menus.rs
@@@ -17,8 -17,8 +17,9 @@@
//!
//! An entry's shortcut is the command's default shortcut unless the line gives one (needed for
//! entries with bound parameters). Adobe-service entries (Team Projects, Libraries, Bridge, Media
- //! Encoder, Behance, Creative Cloud…) are intentionally absent; Essential Graphics templates use
- //! EffectCraft's own open `.ectemplate` format.
+ //! Encoder, Behance, Creative Cloud…) are intentionally absent; the Essential Graphics workspace
-//! uses the Properties panel.
++//! uses the Properties panel and the Essential Graphics panel, whose templates use EffectCraft's
++//! own open `.ectemplate` format.
use std::sync::OnceLock;
diff --cc crates/engine/src/psd_import.rs
index 000000000,c14888ea1..7a0a79626
mode 000000,100644..100644
--- a/crates/engine/src/psd_import.rs
+++ b/crates/engine/src/psd_import.rs
@@@ -1,0 -1,634 +1,635 @@@
+ //! Photoshop import as a composition (File ▸ Import ▸ File… with Import As: Composition or
+ //! Composition – Retain Layer Sizes), and Layer ▸ Create ▸ Convert to Editable Text.
+ //!
+ //! Every pixel layer becomes a footage item that names its layer (`Footage::layer`), placed in
+ //! a composition the size of the document. Groups become precomps (pass-through groups collapse
+ //! so their blend modes act on the layers below, like Photoshop); type layers become editable
+ //! text layers; layer masks are baked into the layer's alpha and vector masks become masks;
+ //! layer effects map to Layer Styles; adjustment layers become adjustment layers with the
+ //! matching effect (best effort); clipped layers preserve the transparency underneath.
+
+ use std::sync::Arc;
+
+ use effectcraft_color::BlendMode;
+ use effectcraft_color::Label;
+ use effectcraft_keyframe::{Gradient, Justify, ShapePath, TextDoc, Value};
+ use effectcraft_project::build::{self, Ids};
+ use effectcraft_project::styles::{self, STYLE_BLEND_MODES};
+ use effectcraft_project::{AlphaMode, Comp, Footage, FootageKind, ItemId, ItemKind, Layer, LayerSource, MaskMode, Project, PropGroup, Solid, SourceLayer};
+ use effectcraft_psd::{Adjustment, DValue, Descriptor, Node, Psd};
+ use effectcraft_time::{FrameRate, Tick};
+
+ /// Photoshop blend mode key → compositor mode (`pass` = pass through, handled by collapsing).
+ pub fn blend_mode(key: &str) -> BlendMode {
+ match key {
+ "diss" => BlendMode::Dissolve,
+ "dark" => BlendMode::Darken,
+ "mul " => BlendMode::Multiply,
+ "idiv" => BlendMode::ColorBurn,
+ "lbrn" => BlendMode::LinearBurn,
+ "dkCl" => BlendMode::DarkerColor,
+ "lite" => BlendMode::Lighten,
+ "scrn" => BlendMode::Screen,
+ "div " => BlendMode::ColorDodge,
+ "lddg" => BlendMode::LinearDodge,
+ "lgCl" => BlendMode::LighterColor,
+ "over" => BlendMode::Overlay,
+ "sLit" => BlendMode::SoftLight,
+ "hLit" => BlendMode::HardLight,
+ "vLit" => BlendMode::VividLight,
+ "lLit" => BlendMode::LinearLight,
+ "pLit" => BlendMode::PinLight,
+ "hMix" => BlendMode::HardMix,
+ "diff" => BlendMode::Difference,
+ "smud" => BlendMode::Exclusion,
+ "fsub" => BlendMode::Subtract,
+ "fdiv" => BlendMode::Divide,
+ "hue " => BlendMode::Hue,
+ "sat " => BlendMode::Saturation,
+ "colr" => BlendMode::Color,
+ "lum " => BlendMode::Luminosity,
+ _ => BlendMode::Normal,
+ }
+ }
+
+ /// Descriptor blend mode enum (`BlnM`) → compositor mode.
+ fn desc_blend(v: Option<&str>) -> Option<BlendMode> {
+ Some(match v? {
+ "Nrml" => BlendMode::Normal,
+ "Dslv" => BlendMode::Dissolve,
+ "Drkn" => BlendMode::Darken,
+ "Mltp" => BlendMode::Multiply,
+ "CBrn" => BlendMode::ColorBurn,
+ "linearBurn" => BlendMode::LinearBurn,
+ "darkerColor" => BlendMode::DarkerColor,
+ "Lghn" => BlendMode::Lighten,
+ "Scrn" => BlendMode::Screen,
+ "CDdg" => BlendMode::ColorDodge,
+ "linearDodge" => BlendMode::LinearDodge,
+ "lighterColor" => BlendMode::LighterColor,
+ "Ovrl" => BlendMode::Overlay,
+ "SftL" => BlendMode::SoftLight,
+ "HrdL" => BlendMode::HardLight,
+ "vividLight" => BlendMode::VividLight,
+ "linearLight" => BlendMode::LinearLight,
+ "pinLight" => BlendMode::PinLight,
+ "hardMix" => BlendMode::HardMix,
+ "Dfrn" => BlendMode::Difference,
+ "Xclu" => BlendMode::Exclusion,
+ "blendSubtraction" => BlendMode::Subtract,
+ "blendDivide" => BlendMode::Divide,
+ "H " => BlendMode::Hue,
+ "Strt" => BlendMode::Saturation,
+ "Clr " => BlendMode::Color,
+ "Lmns" => BlendMode::Luminosity,
+ _ => return None,
+ })
+ }
+
+ /// What the import created.
+ pub struct PsdImport {
+ pub comp: ItemId,
+ pub folder: ItemId,
+ pub items: Vec<ItemId>,
+ pub warnings: Vec<String>,
+ }
+
+ struct Ctx<'a> {
+ psd: &'a Psd,
+ path: &'a str,
+ retain: bool,
+ folder: ItemId,
+ rate: FrameRate,
+ duration: Tick,
+ items: Vec<ItemId>,
+ warnings: Vec<String>,
+ }
+
+ /// Import `psd` (read from `path`) as a composition named `name`.
+ pub fn import(proj: &mut Project, psd: &Psd, path: &str, name: &str, retain: bool, rate: FrameRate, duration: Tick) -> PsdImport {
+ let folder = proj.add_item(&format!("{name} Layers"), Label::Yellow, None, ItemKind::Folder);
+ let mut cx = Ctx { psd, path, retain, folder, rate, duration, items: vec![], warnings: vec![] };
+ let comp = build_comp(proj, &mut cx, name, &psd.tree(), None);
+ PsdImport { comp, folder, items: cx.items, warnings: cx.warnings }
+ }
+
+ fn new_comp(cx: &Ctx) -> Comp {
+ Comp::new(cx.psd.width, cx.psd.height, cx.rate, cx.duration)
+ }
+
+ fn build_comp(proj: &mut Project, cx: &mut Ctx, name: &str, nodes: &[Node], parent: Option<ItemId>) -> ItemId {
+ let cid = proj.add_item(name, Label::Sandstone, parent, ItemKind::Comp(Arc::new(new_comp(cx))));
+ cx.items.push(cid);
+ let mut comp = new_comp(cx);
+ for n in nodes {
+ if let Some(l) = build_layer(proj, cx, &comp, n) {
+ comp.layers.push(l);
+ }
+ }
+ styles::sync_comp(&mut comp);
+ if let Some(item) = proj.item_mut(cid) {
+ item.kind = ItemKind::Comp(Arc::new(comp));
+ }
+ cid
+ }
+
+ fn footage_item(proj: &mut Project, cx: &mut Ctx, index: usize, name: &str) -> (ItemId, (u32, u32)) {
+ let l = &cx.psd.layers[index];
+ let retain = cx.retain;
+ let (w, h) = if retain && !l.rect.is_empty() { (l.rect.width(), l.rect.height()) } else { (cx.psd.width, cx.psd.height) };
+ let file = std::path::Path::new(cx.path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
+ let f = Footage {
+ path: cx.path.to_string(),
+ kind: FootageKind::Still,
+ width: w,
+ height: h,
+ pixel_aspect: 1.0,
+ frame_rate: cx.rate,
+ native_rate: None,
+ duration: Tick::ZERO,
+ has_video: true,
+ has_audio: false,
+ alpha: AlphaMode::Straight,
+ premul_color: [0.0; 3],
+ loop_count: 1,
+ codec: "PSD".into(),
+ missing: false,
+ sequence: vec![],
+ color_profile: None,
+ layer: Some(SourceLayer { index: index as u32, name: name.to_string(), layer_size: retain && !l.rect.is_empty() }),
++ ..Default::default()
+ };
+ let id = proj.add_item(&format!("{name}/{file}"), Label::Lavender, Some(cx.folder), ItemKind::Footage(f));
+ cx.items.push(id);
+ (id, (w, h))
+ }
+
+ fn build_layer(proj: &mut Project, cx: &mut Ctx, comp: &Comp, n: &Node) -> Option<Layer> {
+ let (index, children) = match n {
+ Node::Layer(i) => (*i, None),
+ Node::Group { layer, children } => (*layer, Some(children)),
+ };
+ let pl = cx.psd.layers[index].clone();
+ let name = if pl.name.is_empty() { format!("Layer {}", index + 1) } else { pl.name.clone() };
+ let mut layer = if let Some(children) = children {
+ let sub = build_comp(proj, cx, &name, children, Some(cx.folder));
+ let mut l = build::layer(proj, comp, &name, LayerSource::Comp { item: sub }, (comp.width, comp.height), None);
+ // Pass-through groups composite their layers straight into the parent.
+ l.switches.collapse = pl.blend_key() == "pass";
+ l
+ } else if let Some(t) = &pl.text {
+ text_layer(proj, comp, &name, t)
+ } else if let Some(adj) = &pl.adjustment {
+ let mut l = adjustment_layer(proj, comp, &name);
+ add_adjustment_effect(proj, &mut l, adj, comp, &mut cx.warnings, &name);
+ l
+ } else if pl.has_pixels() || pl.fill.is_some() {
+ let (item, size) = footage_item(proj, cx, index, &name);
+ let mut l = build::layer(proj, comp, &name, LayerSource::Footage { item }, size, None);
+ if cx.retain && !pl.rect.is_empty() {
+ set_vec2(&mut l, "transform/position", [pl.rect.left as f64 + size.0 as f64 / 2.0, pl.rect.top as f64 + size.1 as f64 / 2.0]);
+ }
+ l
+ } else {
+ // Empty layers have nothing to show.
+ return None;
+ };
+ layer.name = comp.unique_layer_name(&name);
+ layer.blend_mode = blend_mode(pl.blend_key());
+ layer.switches.video = !pl.hidden;
+ layer.preserve_transparency = pl.clipping;
+ set_scalar(&mut layer, "transform/opacity", pl.opacity as f64 / 255.0 * 100.0);
+ // Vector mask → a mask in layer space.
+ let origin = layer_origin(&pl, cx.retain, &layer);
+ if let Some(vm) = pl.vector_mask.as_ref().filter(|v| !v.disabled)
+ && let Some(masks) = layer.props.sub_mut("masks")
+ {
+ let mut ids = Ids(&mut proj.next_id);
+ for (k, sp) in vm.subpaths.iter().enumerate() {
+ let n = sp.knots.len();
+ let mut path = ShapePath { vertices: vec![], in_tangents: vec![], out_tangents: vec![], closed: sp.closed };
+ for kn in &sp.knots {
+ let v = [kn[1][0] - origin[0], kn[1][1] - origin[1]];
+ path.vertices.push(v);
+ path.in_tangents.push([kn[0][0] - kn[1][0], kn[0][1] - kn[1][1]]);
+ path.out_tangents.push([kn[2][0] - kn[1][0], kn[2][1] - kn[1][1]]);
+ }
+ if n == 0 {
+ continue;
+ }
+ let mode = if vm.inverted { MaskMode::Subtract } else { MaskMode::Add };
+ masks.children.push(build::mask(&mut ids, &format!("Mask {}", k + 1), path, mode, [255, 255, 0]).into());
+ }
+ }
+ // Layer effects → Layer Styles; Fill Opacity → Advanced Blending.
+ let gl = comp.global_light.clone();
+ if let Some(fx) = &pl.effects
+ && fx.bool("masterFXSwitch") != Some(false)
+ && layer.can_have_styles()
+ {
+ apply_effects(proj, &mut layer, fx, &gl);
+ }
+ if pl.fill_opacity < 255 && layer.can_have_styles() {
+ let mut ids = Ids(&mut proj.next_id);
+ if layer.props.sub(styles::GROUP).is_none() {
+ let g = styles::layer_styles(&mut ids, &gl);
+ let at = layer.props.children.iter().position(|c| c.match_id() == "transform").map(|i| i + 1).unwrap_or(layer.props.children.len());
+ layer.props.children.insert(at, g.into());
+ }
+ if let Some(p) = layer.props.prop_mut("layerStyles/blendingOptions/advancedBlending/fillOpacity") {
+ p.value = Value::Scalar(pl.fill_opacity as f64 / 255.0 * 100.0);
+ }
+ }
+ Some(layer)
+ }
+
+ /// Where layer space's origin sits in document pixels.
+ fn layer_origin(pl: &effectcraft_psd::Layer, retain: bool, layer: &Layer) -> [f64; 2] {
+ if let Some(t) = &pl.text {
+ return [t.transform[4], t.transform[5]];
+ }
+ if matches!(layer.source, LayerSource::Footage { .. }) && retain && !pl.rect.is_empty() {
+ return [pl.rect.left as f64, pl.rect.top as f64];
+ }
+ [0.0, 0.0]
+ }
+
+ fn set_scalar(l: &mut Layer, path: &str, v: f64) {
+ if let Some(p) = l.props.prop_mut(path) {
+ p.value = Value::Scalar(v);
+ }
+ }
+
+ fn set_vec2(l: &mut Layer, path: &str, v: [f64; 2]) {
+ if let Some(p) = l.props.prop_mut(path) {
+ p.value = match p.value {
+ Value::Vec3(o) => Value::Vec3([v[0], v[1], o[2]]),
+ _ => Value::Vec2(v),
+ };
+ }
+ }
+
+ /// Split a PostScript font name into family and style (`Inter-Bold` → `Inter`, `Bold`).
+ fn font_names(ps: &str) -> (String, String) {
+ match ps.split_once('-') {
+ Some((fam, style)) => (fam.to_string(), style.to_string()),
+ None => (ps.to_string(), "Regular".to_string()),
+ }
+ }
+
+ fn text_doc(t: &effectcraft_psd::TextInfo) -> TextDoc {
+ let mut d = TextDoc::default();
+ d.set_text(&t.text);
+ let [xx, xy, yx, yy, _, _] = t.transform;
+ let scale = (xx * yy - xy * yx).abs().sqrt().max(1e-6);
+ if let Some(s) = t.style.size {
+ d.size = s * scale;
+ }
+ if let Some(f) = &t.style.font {
+ let (fam, style) = font_names(f);
+ d.font = fam;
+ d.style = style;
+ }
+ if let Some(c) = t.style.color {
+ d.fill = [c[0] as f32, c[1] as f32, c[2] as f32, 1.0];
+ }
+ d.justify = match t.style.justification {
+ Some(1) => Justify::Right,
+ Some(2) => Justify::Center,
+ Some(3) => Justify::JustifyLastLeft,
+ Some(4) => Justify::JustifyLastRight,
+ Some(5) => Justify::JustifyLastCenter,
+ Some(6) => Justify::JustifyAll,
+ _ => Justify::Left,
+ };
+ if let Some(tr) = t.style.tracking {
+ d.tracking = tr;
+ }
+ if let Some(l) = t.style.leading {
+ d.leading = Some(l * scale);
+ }
+ d.faux_bold = t.style.faux_bold;
+ d.faux_italic = t.style.faux_italic;
+ if t.style.box_text
+ && let Some([l, top, r, b]) = t.bounds
+ {
+ d.box_size = Some([(r - l) * scale, (b - top) * scale]);
+ d.box_pos = [l * scale, top * scale];
+ }
+ d
+ }
+
+ fn text_layer(proj: &mut Project, comp: &Comp, name: &str, t: &effectcraft_psd::TextInfo) -> Layer {
+ let mut l = build::layer(proj, comp, name, LayerSource::Text, (0, 0), None);
+ if let Some(p) = l.props.prop_mut("text/sourceText") {
+ p.value = Value::Text(Box::new(text_doc(t)));
+ }
+ set_vec2(&mut l, "transform/position", [t.transform[4], t.transform[5]]);
+ let [xx, xy, _, _, _, _] = t.transform;
+ let rot = xy.atan2(xx).to_degrees();
+ if rot.abs() > 1e-6 {
+ set_scalar(&mut l, "transform/rotation", rot);
+ }
+ l
+ }
+
+ fn adjustment_layer(proj: &mut Project, comp: &Comp, name: &str) -> Layer {
+ let folder = proj.folder_named("Solids").unwrap_or_else(|| proj.add_item("Solids", Label::Yellow, None, ItemKind::Folder));
+ let sid = proj.add_item(
+ name,
+ Label::Red,
+ Some(folder),
+ ItemKind::Solid(Solid { color: [1.0, 1.0, 1.0], width: comp.width, height: comp.height, pixel_aspect: 1.0 }),
+ );
+ let mut l = build::layer(proj, comp, name, LayerSource::Solid { item: sid }, (comp.width, comp.height), None);
+ l.switches.adjustment = true;
+ l.label = Label::Purple;
+ l
+ }
+
+ fn add_effect(proj: &mut Project, l: &mut Layer, effect: &str, comp: &Comp, params: &[(&str, Value)]) {
+ let Some(spec) = effectcraft_effects::lookup(effect) else { return };
+ let mut ids = Ids(&mut proj.next_id);
+ let mut g = effectcraft_effects::instantiate(spec, &mut ids, spec.name, [comp.width as f64, comp.height as f64]);
+ for (k, v) in params {
+ if let Some(p) = g.get_mut(k) {
+ p.value = v.clone();
+ }
+ }
+ if let Some(fx) = l.props.sub_mut("effects") {
+ fx.children.push(g.into());
+ }
+ }
+
+ fn add_adjustment_effect(proj: &mut Project, l: &mut Layer, adj: &Adjustment, comp: &Comp, warnings: &mut Vec<String>, name: &str) {
+ match adj {
+ Adjustment::Invert => add_effect(proj, l, "Invert", comp, &[]),
+ Adjustment::BrightnessContrast { brightness, contrast, .. } => {
+ add_effect(proj, l, "Brightness & Contrast", comp, &[("brightness", Value::Scalar(*brightness)), ("contrast", Value::Scalar(*contrast))])
+ }
+ Adjustment::HueSaturation { hue, saturation, lightness, colorize } => {
+ let mut p = vec![("hue", Value::Scalar(*hue)), ("saturation", Value::Scalar(*saturation)), ("lightness", Value::Scalar(*lightness))];
+ if *colorize {
+ p = vec![
+ ("colorize", Value::Bool(true)),
+ ("colorizeHue", Value::Scalar(*hue)),
+ ("colorizeSaturation", Value::Scalar(*saturation)),
+ ("colorizeLightness", Value::Scalar(*lightness)),
+ ];
+ }
+ add_effect(proj, l, "Hue/Saturation", comp, &p)
+ }
+ Adjustment::Levels { in_black, in_white, gamma, out_black, out_white } => add_effect(
+ proj,
+ l,
+ "Levels",
+ comp,
+ &[
+ ("inBlack", Value::Scalar(in_black / 255.0)),
+ ("inWhite", Value::Scalar(in_white / 255.0)),
+ ("gamma", Value::Scalar(*gamma)),
+ ("outBlack", Value::Scalar(out_black / 255.0)),
+ ("outWhite", Value::Scalar(out_white / 255.0)),
+ ],
+ ),
+ Adjustment::Exposure { exposure, offset, gamma } => add_effect(
+ proj,
+ l,
+ "Exposure",
+ comp,
+ &[("exposure", Value::Scalar(*exposure)), ("offset", Value::Scalar(*offset)), ("gamma", Value::Scalar(*gamma))],
+ ),
+ Adjustment::Other(k) => warnings.push(format!("{name}: adjustment `{k}` is not converted (layer kept as an empty adjustment layer)")),
+ }
+ }
+
+ // ---------------------------------------------------------------- layer effects → styles
+
+ fn style_mode(m: BlendMode) -> Value {
+ Value::Enum(STYLE_BLEND_MODES.iter().position(|x| x.1 == m).unwrap_or(0) as u32)
+ }
+
+ fn set(g: &mut PropGroup, k: &str, v: Value) {
+ if let Some(p) = g.get_mut(k) {
+ p.value = v;
+ }
+ }
+
+ fn color4(c: [f64; 3]) -> Value {
+ Value::Color([c[0], c[1], c[2], 1.0])
+ }
+
+ /// Copy the common style settings (`Md `, `Clr `, `Opct`, angle, distance, size…).
+ fn common(g: &mut PropGroup, d: &Descriptor) {
+ if let Some(m) = desc_blend(d.enum_value("Md ")) {
+ set(g, "blendMode", style_mode(m));
+ }
+ if let Some(c) = d.color("Clr ") {
+ set(g, "color", color4(c));
+ }
+ for (k, prop) in [("Opct", "opacity"), ("Nose", "noise"), ("Dstn", "distance"), ("blur", "size"), ("lagl", "angle"), ("ShdN", "jitter"), ("Inpr", "range")]
+ {
+ if let Some(v) = d.num(k) {
+ set(g, prop, Value::Scalar(v));
+ }
+ }
+ if let Some(b) = d.bool("uglg") {
+ set(g, "useGlobalLight", Value::Bool(b));
+ }
+ }
+
+ fn gradient_of(d: &Descriptor) -> Option<Gradient> {
+ let g = d.obj("Grad")?;
+ let list = |k: &str| match g.get(k) {
+ Some(DValue::List(v)) => v.clone(),
+ _ => vec![],
+ };
+ let colors: Vec<(f64, [f32; 4])> = list("Clrs")
+ .iter()
+ .filter_map(|c| match c {
+ DValue::Descriptor(s) => {
+ let col = s.color("Clr ")?;
+ Some((s.num("Lctn").unwrap_or(0.0) / 4096.0, [col[0] as f32, col[1] as f32, col[2] as f32, 1.0]))
+ }
+ _ => None,
+ })
+ .collect();
+ let opacities: Vec<(f64, f32)> = list("Trns")
+ .iter()
+ .filter_map(|c| match c {
+ DValue::Descriptor(s) => Some((s.num("Lctn").unwrap_or(0.0) / 4096.0, (s.num("Opct").unwrap_or(100.0) / 100.0) as f32)),
+ _ => None,
+ })
+ .collect();
+ (!colors.is_empty()).then(|| Gradient { colors, opacities: if opacities.is_empty() { vec![(0.0, 1.0), (1.0, 1.0)] } else { opacities } })
+ }
+
+ /// The effect descriptor for `key`, or the first enabled one of its `…Multi` list.
+ fn effect<'a>(fx: &'a Descriptor, key: &str, multi: &str) -> Option<&'a Descriptor> {
+ fx.obj(key).or_else(|| match fx.get(multi) {
+ Some(DValue::List(v)) => v.iter().find_map(|x| match x {
+ DValue::Descriptor(d) if d.bool("enab") != Some(false) => Some(d),
+ _ => None,
+ }),
+ _ => None,
+ })
+ }
+
+ fn apply_effects(proj: &mut Project, layer: &mut Layer, fx: &Descriptor, gl: &styles::GlobalLight) {
+ const MAP: &[(&str, &str, &str)] = &[
+ ("DrSh", "dropShadowMulti", "dropShadow"),
+ ("IrSh", "innerShadowMulti", "innerShadow"),
+ ("OrGl", "outerGlowMulti", "outerGlow"),
+ ("IrGl", "innerGlowMulti", "innerGlow"),
+ ("ebbl", "bevelEmbossMulti", "bevelEmboss"),
+ ("ChFX", "satinMulti", "satin"),
+ ("SoFi", "solidFillMulti", "colorOverlay"),
+ ("GrFl", "gradientFillMulti", "gradientOverlay"),
+ ("FrFX", "frameFXMulti", "stroke"),
+ ];
+ for (key, multi, id) in MAP {
+ let Some(d) = effect(fx, key, multi) else { continue };
+ let enabled = d.bool("enab").unwrap_or(true);
+ let mut ids = Ids(&mut proj.next_id);
+ let Some(uid) = styles::add_style(layer, &mut ids, id, gl, enabled) else { continue };
+ let Some(g) = layer.props.find_group_mut(uid) else { continue };
+ common(g, d);
+ match *id {
+ "dropShadow" => {
+ if let Some(v) = d.num("Ckmt") {
+ set(g, "spread", Value::Scalar(v));
+ }
+ if let Some(b) = d.bool("layerConceals") {
+ set(g, "knocksOut", Value::Bool(b));
+ }
+ }
+ "innerShadow" | "innerGlow" => {
+ if let Some(v) = d.num("Ckmt") {
+ set(g, "choke", Value::Scalar(v));
+ }
+ if d.enum_value("glwS") == Some("SrcC") {
+ set(g, "source", Value::Enum(0));
+ }
+ }
+ "outerGlow" => {
+ if let Some(v) = d.num("Ckmt") {
+ set(g, "spread", Value::Scalar(v));
+ }
+ }
+ "bevelEmboss" => {
+ let style = match d.enum_value("bvlS") {
+ Some("OtrB") => 0,
+ Some("Embs") => 2,
+ Some("PlEb") => 3,
+ Some("strokeEmboss") => 4,
+ _ => 1,
+ };
+ set(g, "style", Value::Enum(style));
+ let tech = match d.enum_value("bvlT") {
+ Some("PrBL") => 1,
+ Some("Slmt") => 2,
+ _ => 0,
+ };
+ set(g, "technique", Value::Enum(tech));
+ if let Some(v) = d.num("srgR") {
+ set(g, "depth", Value::Scalar(v));
+ }
+ set(g, "direction", Value::Enum(u32::from(d.enum_value("bvlD") == Some("Out "))));
+ if let Some(v) = d.num("Sftn") {
+ set(g, "soften", Value::Scalar(v));
+ }
+ if let Some(v) = d.num("Lald") {
+ set(g, "altitude", Value::Scalar(v));
+ }
+ for (k, p) in [("hglM", "highlightMode"), ("sdwM", "shadowMode")] {
+ if let Some(m) = desc_blend(d.enum_value(k)) {
+ set(g, p, style_mode(m));
+ }
+ }
+ for (k, p) in [("hglC", "highlightColor"), ("sdwC", "shadowColor")] {
+ if let Some(c) = d.color(k) {
+ set(g, p, color4(c));
+ }
+ }
+ for (k, p) in [("hglO", "highlightOpacity"), ("sdwO", "shadowOpacity")] {
+ if let Some(v) = d.num(k) {
+ set(g, p, Value::Scalar(v));
+ }
+ }
+ }
+ "satin" => {
+ if let Some(b) = d.bool("Invr") {
+ set(g, "invert", Value::Bool(b));
+ }
+ }
+ "gradientOverlay" => {
+ if let Some(gr) = gradient_of(d) {
+ set(g, "colors", Value::Gradient(gr));
+ }
+ if let Some(a) = d.num("Angl") {
+ set(g, "angle", Value::Scalar(a));
+ }
+ let st = match d.enum_value("Type") {
+ Some("Rdl ") => 1,
+ Some("Angl") => 2,
+ Some("Rflc") => 3,
+ Some("Dmnd") => 4,
+ _ => 0,
+ };
+ set(g, "style", Value::Enum(st));
+ if let Some(b) = d.bool("Rvrs") {
+ set(g, "reverse", Value::Bool(b));
+ }
+ if let Some(b) = d.bool("Algn") {
+ set(g, "alignWithLayer", Value::Bool(b));
+ }
+ if let Some(v) = d.num("Scl ") {
+ set(g, "scale", Value::Scalar(v));
+ }
+ }
+ "stroke" => {
+ if let Some(v) = d.num("Sz ") {
+ set(g, "size", Value::Scalar(v));
+ }
+ let pos = match d.enum_value("Styl") {
+ Some("InsF") => 1,
+ Some("CtrF") => 2,
+ _ => 0,
+ };
+ set(g, "position", Value::Enum(pos));
+ }
+ _ => {}
+ }
+ }
+ }
+
+ /// Layer ▸ Create ▸ Convert to Editable Text: a footage layer showing a Photoshop type layer
+ /// becomes a text layer (`None` when the layer's source has no text data).
+ pub fn editable_text(proj: &mut Project, comp: &Comp, layer: &Layer, psd: &Psd, index: usize) -> Option<Layer> {
+ let t = psd.layers.get(index)?.text.as_ref()?;
+ let mut l = text_layer(proj, comp, &layer.name, t);
+ l.name = layer.name.clone();
+ l.blend_mode = layer.blend_mode;
+ l.switches.video = layer.switches.video;
+ l.in_point = layer.in_point;
+ l.out_point = layer.out_point;
+ l.start_time = layer.start_time;
+ if let (Some(o), Some(p)) = (layer.props.prop("transform/opacity"), l.props.prop_mut("transform/opacity")) {
+ *p = effectcraft_project::Property { uid: p.uid, ..o.clone() };
+ }
+ Some(l)
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ #[test]
+ fn blend_keys() {
+ assert_eq!(blend_mode("mul "), BlendMode::Multiply);
+ assert_eq!(blend_mode("smud"), BlendMode::Exclusion);
+ assert_eq!(blend_mode("pass"), BlendMode::Normal);
+ assert_eq!(desc_blend(Some("linearDodge")), Some(BlendMode::LinearDodge));
+ assert_eq!(font_names("Inter-Bold"), ("Inter".into(), "Bold".into()));
+ }
+ }
diff --cc crates/engine/src/tests_disk_cache.rs
index 000000000,65180ba8a..beaeeadab
mode 000000,100644..100644
--- a/crates/engine/src/tests_disk_cache.rs
+++ b/crates/engine/src/tests_disk_cache.rs
@@@ -1,0 -1,121 +1,122 @@@
+ //! The persistent disk cache (PRV-2) through the session: settings, layer cache persistence
+ //! across restarts, invalidation on edits, purging.
+
+ use serde_json::json;
+
+ use crate::Session;
+ use crate::render::RenderOpts;
+
+ fn folder(name: &str) -> String {
+ let d = std::env::temp_dir().join(format!("effectcraft-session-disk-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ d.to_string_lossy().to_string()
+ }
+
+ fn session(dir: &str) -> Session {
+ let mut s = Session::default();
+ s.execute_checked("prefs.set", json!({"values": {"disk.diskCacheFolder": dir, "disk.diskCacheEnabled": true}})).unwrap();
+ // Write every layer buffer, however quick to render.
+ s.disk_cache.as_ref().unwrap().set_min_layer_ms(0);
+ s
+ }
+
+ fn project(s: &mut Session) -> effectcraft_project::ItemId {
+ s.execute("comp.new", json!({"name": "D", "width": 160, "height": 90, "frameRate": 30, "duration": 1})).unwrap();
+ s.execute("layer.newSolid", json!({"color": "#3080ff", "width": 80, "height": 40})).unwrap();
+ s.execute("effect.apply", json!({"layer": "#1", "effect": "Gaussian Blur"})).unwrap();
+ s.execute("prop.set", json!({"layer": "#1", "path": "effects/#1/blurriness", "value": 12})).unwrap();
+ s.active_comp_id().unwrap()
+ }
+
+ #[test]
+ fn disk_cache_settings_persistence_and_invalidation() {
+ let dir = folder("persist");
+ let mut s = session(&dir);
+ let st = s.execute_checked("cache.diskStats", json!({})).unwrap();
+ assert_eq!(st["enabled"], json!(true));
+ assert_eq!(st["maxBytes"], json!(100u64 << 30));
+ let cid = project(&mut s);
+ let t = s.time();
+ let first = s.render(cid, t, RenderOpts::default());
+ let dc = s.disk_cache.clone().unwrap();
+ dc.flush();
+ let written = dc.stats().entries;
+ assert!(written > 0, "layer buffers written");
+ // "Restart": a new session on the same folder and project renders from disk.
+ let saved = s.project.clone();
+ drop(s);
+ let mut s2 = session(&dir);
+ s2.project = saved;
+ s2.bump();
+ s2.open_comp(cid);
+ let dc2 = s2.disk_cache.clone().unwrap();
+ assert_eq!(dc2.stats().entries, written);
+ let again = s2.render(cid, t, RenderOpts::default());
+ assert!(dc2.stats().hits > 0, "{:?}", dc2.stats());
+ assert_eq!(again.data, first.data, "disk-cached pixels are exact");
+ // An edit changes the keys: a miss, and new entries.
+ let hits = dc2.stats().hits;
+ s2.execute("prop.set", json!({"layer": "#1", "path": "effects/#1/blurriness", "value": 20})).unwrap();
+ let edited = s2.render(cid, t, RenderOpts::default());
+ assert_ne!(edited.data, first.data);
+ assert_eq!(dc2.stats().hits, hits);
+ dc2.flush();
+ assert!(dc2.stats().entries > written);
+ // Purge ▸ All Disk Cache empties it; memory purge leaves the disk alone.
+ let r = s2.execute_checked("edit.purge", json!({"what": "memory"})).unwrap();
+ assert_eq!(r["diskEntries"], json!(0));
+ assert!(dc2.stats().entries > 0);
+ let r = s2.execute_checked("edit.purge", json!({"what": "disk"})).unwrap();
+ assert!(r["diskEntries"].as_u64().unwrap() > 0);
+ assert_eq!(dc2.stats().entries, 0);
+ // Disabling detaches it.
+ s2.execute_checked("prefs.set", json!({"key": "disk.diskCacheEnabled", "value": false})).unwrap();
+ assert!(s2.disk_cache.is_none());
+ assert!(s2.layer_cache.disk().is_none());
+ }
+
+ #[test]
+ fn footage_changes_change_the_salt() {
+ let dir = folder("salt");
+ let mut s = session(&dir);
+ let foot = std::env::temp_dir().join(format!("effectcraft-salt-{}.png", std::process::id()));
+ std::fs::write(&foot, b"one").unwrap();
+ s.edit("add", None, |p, _| {
+ let f = effectcraft_project::Footage {
+ path: foot.to_string_lossy().to_string(),
+ kind: effectcraft_project::FootageKind::Still,
+ width: 1,
+ height: 1,
+ pixel_aspect: 1.0,
+ frame_rate: effectcraft_time::FrameRate::FPS_30,
+ native_rate: None,
+ duration: effectcraft_time::Tick::ZERO,
+ has_video: true,
+ has_audio: false,
+ alpha: effectcraft_project::AlphaMode::Ignore,
+ premul_color: [0.0; 3],
+ loop_count: 1,
+ codec: "PNG".into(),
+ missing: false,
+ sequence: vec![],
+ color_profile: None,
+ layer: None,
++ ..Default::default()
+ };
+ p.add_item("f.png", effectcraft_color::Label::Lavender, None, effectcraft_project::ItemKind::Footage(f));
+ Ok(())
+ })
+ .unwrap();
+ let a = effectcraft_render::disk_cache::footage_salt(&s.project);
+ std::fs::write(&foot, b"two, longer").unwrap();
+ let b = effectcraft_render::disk_cache::footage_salt(&s.project);
+ assert_ne!(a, b);
+ let cid = project(&mut s);
+ let k1 = effectcraft_render::disk_cache::comp_content_key(&s.project, cid);
+ s.execute("prop.set", json!({"layer": "#1", "path": "transform/opacity", "value": 50})).unwrap();
+ let k2 = effectcraft_render::disk_cache::comp_content_key(&s.project, cid);
+ assert_ne!(k1, k2);
+ // Unrelated comps do not change it.
+ s.execute("comp.new", json!({"name": "Other", "width": 10, "height": 10, "frameRate": 30, "duration": 1})).unwrap();
+ assert_eq!(effectcraft_render::disk_cache::comp_content_key(&s.project, cid), k2);
+ }
diff --cc crates/engine/src/tests_stubs.rs
index 924fb5793,725cf6009..b15259692
--- a/crates/engine/src/tests_stubs.rs
+++ b/crates/engine/src/tests_stubs.rs
@@@ -332,7 -332,7 +332,7 @@@ fn implemented_stubs_are_enabled_and_wo
assert!(s.drain_events().iter().any(|e| matches!(e, Event::Frontend { command, .. } if command == id)));
}
// What remains a stub is still disabled.
- for id in ["view.displayColorManagement", "keys.audioToKeyframes", "track.camera"] {
- for id in ["view.displayColorManagement", "file.createProxy"] {
++ for id in ["view.displayColorManagement", "keys.audioToKeyframes"] {
assert!(!s.is_enabled(id), "{id}");
}
}
diff --cc crates/host/src/lib.rs
index b90a42f0b,aa94b5589..d7668fcc5
--- a/crates/host/src/lib.rs
+++ b/crates/host/src/lib.rs
@@@ -222,134 -224,64 +225,192 @@@ mod tests
assert_eq!(value(&s, a, "transform/rotation").as_f64(), 12.0);
}
+ /// The expression error bar's list: evaluation errors and syntax errors, with the layer and
+ /// property they belong to.
+ #[test]
+ fn expression_errors_are_collected() {
+ let mut s = super::session();
+ s.execute("comp.new", json!({"name": "C", "width": 100, "height": 100, "frameRate": 30, "duration": 2})).unwrap();
+ let a = s.execute("layer.newSolid", json!({"name": "Box", "color": "#ffffff"})).unwrap()["layer"].as_u64().unwrap();
+ s.execute("prop.setExpression", json!({"layer": a, "path": "transform/opacity", "expression": "50"})).unwrap();
+ assert_eq!(s.execute("expr.errors", json!({})).unwrap()["count"], 0);
+ s.execute("prop.setExpression", json!({"layer": a, "path": "transform/rotation", "expression": "thisComp.layer(\"Nope\").rotation"})).unwrap();
+ s.execute("prop.setExpression", json!({"layer": a, "path": "transform/opacity", "expression": "1 +* ("})).unwrap();
+ let r = s.execute("expr.errors", json!({})).unwrap();
+ assert_eq!(r["count"], 2, "{r}");
+ let errs = r["errors"].as_array().unwrap();
+ let rot = errs.iter().find(|e| e["path"] == "transform/rotation").unwrap();
+ assert!(rot["message"].as_str().unwrap().contains("Nope"), "{rot}");
+ assert_eq!(rot["layerIndex"], 1);
+ assert_eq!(rot["layerName"], "Box");
+ assert_eq!(rot["disabled"], false);
+ let op = errs.iter().find(|e| e["path"] == "transform/opacity").unwrap();
+ assert_eq!(op["disabled"], true);
+ assert!(r["text"][0].as_str().unwrap().contains("of layer 1 ('Box') in comp 'C'"), "{r}");
+ // A user-disabled (but valid) expression is not an error.
+ s.execute("prop.setExpression", json!({"layer": a, "path": "transform/rotation", "expression": "45"})).unwrap();
+ s.execute("prop.setExpression", json!({"layer": a, "path": "transform/rotation", "enabled": false})).unwrap();
+ assert_eq!(s.execute("expr.errors", json!({})).unwrap()["count"], 1);
+ // The Expression Language menu is categorised.
+ let m = s.execute("expr.languageMenu", json!({})).unwrap();
+ assert!(m.as_array().unwrap().iter().any(|c| c["category"] == "Footage" && c["items"].as_array().unwrap().iter().any(|i| i["text"] == "sourceData")));
+ }
+
+ /// File ▸ Import of JSON/CSV data files as data footage, read by expressions.
+ #[test]
+ fn imported_data_files_drive_expressions() {
+ let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/test-out/host-data");
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("levels.csv"), "label,value\nlow,10\nhigh,90\n").unwrap();
+ std::fs::write(dir.join("cfg.json"), r#"{"angle": 33}"#).unwrap();
+ std::fs::write(dir.join("broken.json"), "{nope").unwrap();
+ let mut s = super::session();
+ s.execute("comp.new", json!({"name": "C", "width": 100, "height": 100, "frameRate": 30, "duration": 2})).unwrap();
+ let paths: Vec<String> = ["levels.csv", "cfg.json", "broken.json"].iter().map(|n| dir.join(n).to_string_lossy().to_string()).collect();
+ let r = s.execute("file.import", json!({"paths": paths})).unwrap();
+ assert_eq!(r["items"].as_array().unwrap().len(), 2, "{r}");
+ assert_eq!(r["errors"].as_array().unwrap().len(), 1, "{r}");
+ let csv = r["items"][0].as_u64().unwrap();
+ assert_eq!(s.project.item(effectcraft_engine::project::ItemId(csv)).unwrap().type_name(), "Data");
+ assert!(s.execute("layer.addItem", json!({"item": csv})).is_err(), "data files are not layers");
+ let a = s.execute("layer.newSolid", json!({"color": "#ffffff"})).unwrap()["layer"].as_u64().unwrap();
+ s.execute("prop.setExpression", json!({"layer": a, "path": "transform/opacity", "expression": "footage(\"levels.csv\").sourceData[1].value"})).unwrap();
+ s.execute("prop.setExpression", json!({"layer": a, "path": "transform/rotation", "expression": "footage(\"cfg.json\").sourceData.angle"})).unwrap();
+ assert_eq!(value(&s, a, "transform/opacity").as_f64(), 90.0);
+ assert_eq!(value(&s, a, "transform/rotation").as_f64(), 33.0);
+ }
+
+ /// sampleImage through the renderer: a box's Fill colour follows the solid under it.
+ #[test]
+ fn sample_image_drives_a_colour() {
+ let mut s = super::session();
+ s.execute("comp.new", json!({"name": "C", "width": 100, "height": 100, "frameRate": 30, "duration": 2})).unwrap();
+ s.execute("layer.newSolid", json!({"name": "Bg", "color": "#00ff00"})).unwrap();
+ let a = s.execute("layer.newSolid", json!({"name": "Fg", "color": "#ffffff", "width": 20, "height": 20})).unwrap()["layer"].as_u64().unwrap();
+ s.execute("effect.apply", json!({"layer": a, "effect": "Fill"})).unwrap();
+ s.execute(
+ "prop.setExpression",
+ json!({"layer": a, "path": "effects/#1/color", "expression": "thisComp.layer(\"Bg\").sampleImage(thisComp.layer(\"Bg\").fromComp(toComp(anchorPoint)))"}),
+ )
+ .unwrap();
+ let cid = s.active_comp_id().unwrap();
+ let img = s.render(cid, s.time(), effectcraft_engine::render::RenderOpts::default());
+ let px = img.get(50, 50);
+ assert!(px[1] > 0.99 && px[0] < 0.01, "the box is filled with the sampled green: {px:?}");
+ }
+
+ /// Proxies through the real media and export layers: Render Settings ▸ Proxy Use decides
+ /// whether an export uses the proxy, and Create Proxy renders and attaches one.
+ #[test]
+ fn proxies_in_exports_and_create_proxy() {
+ let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/test-out/host-proxy");
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let p = |n: &str| dir.join(n).to_string_lossy().to_string();
+ let mut s = super::session();
+ // Source and proxy stills, written by the app itself.
+ s.execute("comp.new", json!({"name": "Red", "width": 16, "height": 16, "frameRate": 10, "duration": 1})).unwrap();
+ let red = s.active_comp_id().unwrap();
+ s.execute("layer.newSolid", json!({"color": "#ff0000"})).unwrap();
+ s.execute("comp.saveFrameAs", json!({"path": p("red.png")})).unwrap();
+ s.execute("comp.new", json!({"name": "Blue", "width": 8, "height": 8, "frameRate": 10, "duration": 1})).unwrap();
+ s.execute("layer.newSolid", json!({"color": "#0000ff"})).unwrap();
+ s.execute("comp.saveFrameAs", json!({"path": p("blue.png")})).unwrap();
+ let foot = s.execute("file.import", json!({"paths": [p("red.png")]})).unwrap()["items"][0].as_u64().unwrap();
+ s.execute("file.setProxy", json!({"item": foot, "path": p("blue.png")})).unwrap();
+ s.execute("comp.new", json!({"name": "Out", "width": 16, "height": 16, "frameRate": 10, "duration": 1})).unwrap();
+ let out = s.active_comp_id().unwrap();
+ s.execute("layer.addItem", json!({"item": foot})).unwrap();
+ // Export one frame with each Proxy Use.
+ for (name, using) in [("all", "use_all_[#].png"), ("none", "use_none_[#].png")] {
+ s.execute(
+ "renderQueue.add",
+ json!({"comp": out.0, "format": "png", "output": p(using), "timeSpan": "custom", "start": 0.0, "end": 0.1, "proxyUse": name}),
+ )
+ .unwrap();
+ }
+ s.execute("renderQueue.render", json!({"wait": true})).unwrap();
+ s.poll_render();
+ let centre = |s: &mut effectcraft_engine::Session, path: &str| {
+ let id = s.execute("file.import", json!({"paths": [path]})).unwrap()["items"][0].as_u64().unwrap();
+ s.execute("comp.new", json!({"name": "Probe", "width": 16, "height": 16, "frameRate": 10, "duration": 1})).unwrap();
+ s.execute("layer.addItem", json!({"item": id})).unwrap();
+ let c = s.active_comp_id().unwrap();
+ s.render(c, Default::default(), Default::default()).get(8, 8)
+ };
+ let all = centre(&mut s, &p("use_all_0.png"));
+ assert!(all[2] > 0.99 && all[0] < 0.01, "Use All Proxies renders the blue proxy: {all:?}");
+ let none = centre(&mut s, &p("use_none_0.png"));
+ assert!(none[0] > 0.99 && none[2] < 0.01, "Use No Proxies renders the red source: {none:?}");
+ // Create Proxy ▸ Still: rendered at half size and attached to the comp.
+ s.execute("file.createProxy", json!({"kind": "still", "comp": red.0, "path": p("red_proxy_[#####].png")})).unwrap();
+ s.execute("renderQueue.render", json!({"wait": true})).unwrap();
+ s.poll_render();
+ let px = s.project.item(red).unwrap().proxy.clone().expect("Create Proxy attached the rendered still");
+ assert!(px.enabled);
+ assert_eq!((px.footage.width, px.footage.height), (8, 8));
+ assert!(std::path::Path::new(&px.footage.path).exists(), "{}", px.footage.path);
+ }
+
+ /// A script builds a comp, queues it and renders it through the Render Queue.
+ #[test]
+ fn script_renders_through_the_render_queue() {
+ let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/test-out/host-script");
+ let _ = std::fs::remove_dir_all(&dir);
+ let out = dir.join("scripted.gif");
+ let mut s = super::session();
+ let code = format!(
+ r#"
+ var comp = app.project.items.addComp("Scripted", 64, 48, 1, 0.2, 10);
+ var sq = comp.layers.addSolid([1, 0.5, 0], "Square", 16, 16, 1);
+ sq.transform.position.setValueAtTime(0, [8, 24]);
+ sq.transform.position.setValueAtTime(0.1, [56, 24]);
+ var item = app.project.renderQueue.items.add(comp);
+ item.outputModule(1).applyTemplate("GIF");
+ item.outputModule(1).file = new File({});
+ app.project.renderQueue.render();
+ [item.status == RQItemStatus.DONE, item.outputModule(1).file.fsName, app.project.renderQueue.numItems]
+ "#,
+ serde_json::to_string(&out.to_string_lossy()).unwrap()
+ );
+ let r = s.execute("script.run", json!({"code": code})).unwrap();
+ assert_eq!(r["ok"], json!(true), "{r}");
+ assert_eq!(r["result"][0], json!(true), "{r}");
+ assert_eq!(r["result"][2], json!(1));
+ let bytes = std::fs::read(&out).unwrap();
+ assert!(bytes.starts_with(b"GIF89a"));
+ }
+
+ /// importFile, layers.add(footage) and project save/open from a script.
+ #[test]
+ fn script_imports_footage_and_saves() {
+ let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/test-out/host-script-import");
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let q = |n: &str| serde_json::to_string(&dir.join(n).to_string_lossy()).unwrap();
+ let mut s = super::session();
+ let code = format!(
+ r#"
+ var c = app.project.items.addComp("Src", 32, 32, 1, 1, 10);
+ c.layers.addSolid([0, 1, 0], "G", 32, 32, 1);
+ app.run("comp.saveFrameAs", {{comp: c.id, path: {png}}});
+ var still = app.project.importFile(new ImportOptions(new File({png})));
+ var main = app.project.items.addComp("Main", 64, 64, 1, 1, 10);
+ var l = main.layers.add(still);
+ app.project.save(new File({proj}));
+ [still instanceof FootageItem, still.width, still.mainSource.isStill, l.source.name, app.project.file.name]
+ "#,
+ png = q("frame.png"),
+ proj = q("p.ecproj")
+ );
+ let r = s.execute("script.run", json!({"code": code})).unwrap();
+ assert_eq!(r["ok"], json!(true), "{r}");
+ assert_eq!(r["result"], json!([true, 32, true, "frame.png", "p.ecproj"]), "{r}");
+ let r = s.execute("script.run", json!({"code": format!("app.open(new File({})); app.project.numItems", q("p.ecproj"))})).unwrap();
+ assert_eq!(r["result"], json!(5), "{r}"); // Src, Solids, G, frame.png, Main
+ }
+
#[test]
fn expression_syntax_errors_disable_the_expression() {
let mut s = super::session();
diff --cc crates/media/src/pool.rs
index 478ddc094,f604a69af..9bdefcb69
--- a/crates/media/src/pool.rs
+++ b/crates/media/src/pool.rs
@@@ -386,7 -386,12 +386,12 @@@ impl Inner
let i = Self::frame_index(footage.frame_rate, t, footage.sequence.len() as i64, footage.loop_count);
Loc { key: key(&footage.sequence[i as usize], 0), media_t: None }
}
+ // A layer of a layered still is keyed by its layer index and size mode.
+ FootageKind::Still if footage.layer.is_some() => {
+ let l = footage.layer.as_ref().map_or(0, |l| 1 + l.index as i64 * 2 + l.layer_size as i64);
+ Loc { key: key(&footage.path, l), media_t: None }
+ }
- FootageKind::Still | FootageKind::Sequence | FootageKind::Model => Loc { key: key(&footage.path, 0), media_t: None },
+ FootageKind::Still | FootageKind::Sequence | FootageKind::Model | FootageKind::Data => Loc { key: key(&footage.path, 0), media_t: None },
FootageKind::Video | FootageKind::Audio => {
let rate = footage.frame_rate;
let n = Self::frame_count(rate, footage.duration);
diff --cc crates/project/src/lib.rs
index 0e9c6947a,1665a4f9d..409ae7414
--- a/crates/project/src/lib.rs
+++ b/crates/project/src/lib.rs
@@@ -666,79 -629,23 +666,95 @@@ pub struct Footage
/// Colour profile (from the file's metadata, or Interpret Footage). `None` = sRGB.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub color_profile: Option<ColorSpace>,
+ /// One layer of a layered file (Photoshop) instead of its merged image.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub layer: Option<SourceLayer>,
+ /// Interpret Footage ▸ Fields and Pulldown ▸ Separate Fields.
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub fields: FieldOrder,
+ /// Interpret Footage ▸ Alpha ▸ Invert Alpha.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub invert_alpha: bool,
+ /// Interpret Footage ▸ Color ▸ Interpret As Linear Light: the file's values are linear.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub linear_light: bool,
+ /// Data footage ([`FootageKind::Data`]): the file's text (JSON, CSV or TSV), kept in the
+ /// project so expressions read it everywhere (and on the web).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub data: Option<String>,
+}
+
+fn is_default<T: Default + PartialEq>(v: &T) -> bool {
+ *v == T::default()
+}
+
+impl Default for Footage {
+ fn default() -> Self {
+ Footage {
+ path: String::new(),
+ kind: FootageKind::Still,
+ width: 0,
+ height: 0,
+ pixel_aspect: 1.0,
+ frame_rate: FrameRate::FPS_30,
+ native_rate: None,
+ duration: Tick::ZERO,
+ has_video: false,
+ has_audio: false,
+ alpha: AlphaMode::Straight,
+ premul_color: [0.0; 3],
+ loop_count: 1,
+ codec: String::new(),
+ missing: false,
+ sequence: vec![],
+ color_profile: None,
+ fields: FieldOrder::Off,
+ invert_alpha: false,
+ linear_light: false,
+ data: None,
++ layer: None,
+ }
+ }
+}
+
+impl Footage {
+ /// The data format of data footage: `json`, `csv` or `tsv` (from the file extension).
+ pub fn data_format(&self) -> Option<&'static str> {
+ if self.kind != FootageKind::Data {
+ return None;
+ }
+ let ext = std::path::Path::new(&self.path).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
+ Some(match ext.as_str() {
+ "csv" => "csv",
+ "tsv" | "tab" => "tsv",
+ _ => "json",
+ })
+ }
+}
+
+/// A proxy: a stand-in file used instead of a footage item or composition (File ▸ Set Proxy /
+/// Create Proxy), when its Use Proxy switch is on and the render's Proxy Use allows it.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Proxy {
+ /// The proxy's footage (path, size, rate…; File ▸ Interpret Footage ▸ Proxy edits it).
+ pub footage: Footage,
+ /// Use Proxy (the Project panel's proxy indicator: filled = in use, hollow = set but off).
+ #[serde(default = "yes")]
+ pub enabled: bool,
}
+ /// A layer of a layered still (a Photoshop document) used as footage
+ /// (File ▸ Import ▸ Composition / Composition – Retain Layer Sizes, or Choose Layer).
+ #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+ pub struct SourceLayer {
+ /// Layer record index in the file (bottom of the stack = 0).
+ pub index: u32,
+ pub name: String,
+ /// The footage is the layer's own bounds (Retain Layer Sizes) rather than the document size.
+ #[serde(default)]
+ pub layer_size: bool,
+ }
+
fn one() -> u32 {
1
}
diff --cc crates/render/src/lib.rs
index 01f5f96af,db1ace7d9..ff71fb575
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@@ -723,11 -693,32 +739,22 @@@ impl<'a> Renderer<'a>
if !f.has_video {
return None;
}
+ // Continuously rasterised vector footage: drawn at the on-screen scale.
+ if layer.switches.collapse && is_vector_footage(f) {
+ let k = self.raster_scale(ctx, layer);
+ if let Some(img) = self.footage.vector_frame(*item, f, k) {
+ let mut buf = Buf { img: (*img).clone(), offset: [0.0; 2], scale: k };
+ if let Some(c) = self.pipe.media_in(f.color_profile) {
+ color::convert(&mut buf.img, &c);
+ }
+ return Some(buf);
+ }
+ }
let lt = ctx.source_time(layer);
- let img = self.footage_frame(ctx, layer, *item, f, lt)?;
- let k = if img.width > 0 { f.width.max(1) as f64 / img.width as f64 } else { 1.0 };
- // Keep native pixels when downsampling is small; resample otherwise.
- let mut buf = if s < 0.75 {
- let w = ((f.width as f64 * s).round() as u32).max(1);
- let h = ((f.height as f64 * s).round() as u32).max(1);
- Buf { img: effectcraft_raster::resample(&img, w, h), offset: [0.0; 2], scale: s }
- } else {
- Buf { img: (*img).clone(), offset: [0.0; 2], scale: 1.0 / k }
- };
- if let Some(c) = self.pipe.media_in(f.color_profile) {
- color::convert(&mut buf.img, &c);
- }
- Some(buf)
+ // The proxy is decoded instead, at its own size, and fills the footage's frame.
+ let pf = self.proxy_for(*item).unwrap_or(f);
+ let img = self.footage_frame(ctx, layer, *item, pf, lt)?;
+ Some(self.footage_buf(&img, pf, f.width, f.height))
}
LayerSource::Text => Some(self.authored(text::render(ctx, layer, self.raster_scale(ctx, layer)))),
LayerSource::Shape => layer.props.sub("contents").map(|c| self.authored(shapes::render(ctx, layer, c, self.raster_scale(ctx, layer)))),
diff --cc crates/ui-egui/src/dock.rs
index 3644d7ac0,cd052c3e2..91d7c335c
--- a/crates/ui-egui/src/dock.rs
+++ b/crates/ui-egui/src/dock.rs
@@@ -34,11 -34,11 +34,12 @@@ pub enum PanelKind
History,
Markers,
MaskInterpolation,
+ ScriptConsole,
+ EssentialGraphics,
}
impl PanelKind {
-- pub const ALL: [PanelKind; 25] = [
++ pub const ALL: [PanelKind; 26] = [
PanelKind::Project,
PanelKind::EffectControls,
PanelKind::Composition,
@@@ -63,7 -63,7 +64,8 @@@
PanelKind::History,
PanelKind::Markers,
PanelKind::MaskInterpolation,
+ PanelKind::ScriptConsole,
+ PanelKind::EssentialGraphics,
];
pub fn title(self) -> &'static str {
match self {
@@@ -91,7 -91,7 +93,8 @@@
PanelKind::History => "History",
PanelKind::Markers => "Markers",
PanelKind::MaskInterpolation => "Mask Interpolation",
+ PanelKind::ScriptConsole => "Script Console",
+ PanelKind::EssentialGraphics => "Essential Graphics",
}
}
pub fn id(self) -> String {
diff --cc crates/ui-egui/src/lib.rs
index cc12a3416,0976c47a0..286073796
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@@ -419,8 -434,14 +434,15 @@@ impl EffectcraftApp
view: self.session.view_camera(comp),
roi,
backend: effectcraft_engine::render::Backend::Auto,
+ proxy: Default::default(),
- };
+ }
+ }
+
+ fn request_frame_with(&self, comp: ItemId, frame: i64, scale: f64, urgent: bool) {
+ let Some(c) = self.session.project.comp(comp) else { return };
+ let key = self.frame_key(comp, frame, scale);
+ let t = c.frame_rate.tick_of(frame);
+ let opts = self.frame_opts(comp, scale);
if urgent {
self.frames.request_urgent(&self.render_source(), key, comp, t, opts);
} else {
diff --cc crates/ui-egui/src/menus.rs
index f97851f88,e48bb5145..689963f71
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@@ -697,12 -783,9 +783,12 @@@ fn file_dialog(app: &mut EffectcraftApp
"file.exportLottie" => ("path", Ask::Save("Animation.json")),
"file.importLottie" => ("path", Ask::Open(&["json", "lottie"])),
"render.saveCurrentPreview" => ("path", Ask::Save("Preview.mp4")),
- "file.runScript" => ("path", Ask::Open(&["jsonl", "json", "txt"])),
+ "file.runScript" => ("path", Ask::Open(&["jsx", "js", "jsonl", "json", "txt"])),
"file.replaceFootage" => ("path", Ask::Import),
"file.collectFiles" => ("folder", Ask::Save("Collected Files")),
+ "essential.exportTemplate" => ("path", Ask::Save("Template.ectemplate")),
+ "essential.importTemplate" => ("path", Ask::Open(&["ectemplate"])),
+ "file.setProxy" => ("path", Ask::Open(&["mp4", "mov", "m4v", "mkv", "webm", "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr"])),
_ => return None,
};
if params.get(key).is_some()
@@@ -719,7 -802,7 +805,7 @@@
let Some(f) = app.hooks.pick_files.as_ref() else { return Some(Err("no file dialog available (pass `paths`)".into())) };
let paths = f(&[
"mp4", "mov", "m4v", "mkv", "webm", "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "wav", "aif", "aiff", "mp3", "flac",
- "ogg", "opus", "svg", "gltf", "glb", "obj", "json", "csv", "tsv",
- "ogg", "opus", "svg", "psd", "psb", "gltf", "glb", "obj",
++ "ogg", "opus", "svg", "psd", "psb", "gltf", "glb", "obj", "json", "csv", "tsv",
]);
match (paths.is_empty(), key) {
(true, _) => None,
diff --cc crates/ui-egui/src/panels/mod.rs
index df60beb3a,3cf2dae10..2c1f95eea
--- a/crates/ui-egui/src/panels/mod.rs
+++ b/crates/ui-egui/src/panels/mod.rs
@@@ -6,8 -7,7 +7,9 @@@ pub mod dialogs
pub mod dialogs_3d;
pub mod effect_controls;
pub mod effects_presets;
+pub mod essential;
+pub mod expr_bar;
+ pub mod flowchart;
pub mod forms;
pub mod fx_widgets;
pub mod graph;
@@@ -94,8 -96,7 +100,8 @@@ pub fn show(app: &mut EffectcraftApp, u
PanelKind::Layer => layer_panel::show(app, ui, rect),
PanelKind::Paint => paint_panels::paint(app, ui, rect),
PanelKind::Brushes => paint_panels::brushes(app, ui, rect),
+ PanelKind::EssentialGraphics => essential::show(app, ui, rect),
- other => misc::placeholder(app, ui, rect, other),
+ PanelKind::Flowchart => flowchart::show(app, ui, rect),
}
}
diff --cc crates/ui-egui/src/panels/roto_tool.rs
index 000000000,25354ee34..7047f2380
mode 000000,100644..100644
--- a/crates/ui-egui/src/panels/roto_tool.rs
+++ b/crates/ui-egui/src/panels/roto_tool.rs
@@@ -1,0 -1,331 +1,331 @@@
+ //! Roto Brush and Refine Edge tools in the Layer panel: green foreground strokes, Alt/Option red
+ //! background strokes, Refine Edge strokes along soft edges; the matte overlay (Alpha Boundary in
+ //! pink, Alpha, Alpha Overlay), the segmentation span bar and the Freeze button.
+
+ use effectcraft_engine::effects::roto as fx;
+ use effectcraft_engine::project::{Comp, Layer};
+ use effectcraft_engine::render::{EvalCtx, RenderOpts, Renderer};
+ use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
+ use serde_json::json;
+
+ use crate::theme::Tokens;
+ use crate::{EffectcraftApp, widgets};
+
+ /// Position of the layer's first Roto Brush & Refine Edge effect.
+ pub fn roto_index(layer: &Layer) -> Option<usize> {
+ layer.effects()?.groups().position(|g| matches!(&g.kind, effectcraft_engine::project::GroupKind::Effect { effect } if effect == fx::ID))
+ }
+
+ fn roto_group(layer: &Layer) -> Option<&effectcraft_engine::project::PropGroup> {
+ layer.effects()?.groups().nth(roto_index(layer)?)
+ }
+
+ /// A stroke being drawn.
+ #[derive(Clone, Debug)]
+ struct Drag {
+ layer: u64,
+ kind: &'static str,
+ points: Vec<[f64; 2]>,
+ }
+
+ #[derive(Clone)]
+ struct Overlay {
+ key: (u64, u64, i64, u32, String),
+ tex: egui::TextureHandle,
+ rect: [f64; 4],
+ }
+
+ fn c32(c: [f64; 3], a: u8) -> Color32 {
+ Color32::from_rgba_unmultiplied((c[0] * 255.0) as u8, (c[1] * 255.0) as u8, (c[2] * 255.0) as u8, a)
+ }
+
+ /// Draw the matte overlay of the Roto Brush on `layer` (the panel shows the effect's input).
+ pub fn draw_overlay(
+ app: &mut EffectcraftApp,
+ ctx: &egui::Context,
+ painter: &egui::Painter,
+ comp: &Comp,
+ layer: &Layer,
+ scale: f64,
+ to_screen: &dyn Fn([f64; 2]) -> Pos2,
+ ) {
+ let Some(idx) = roto_index(layer) else { return };
+ let o = app.session.state.roto.clone();
+ if o.view == "none" {
+ return;
+ }
+ let Some(cid) = app.session.active_comp_id() else { return };
+ let time = app.session.time();
+ let key = (
+ app.session.revision,
+ layer.id.0,
+ time.0,
+ (scale * 1000.0) as u32,
+ format!("{}{:?}{:?}{}", o.view, o.overlay_color, o.boundary_color, o.overlay_opacity),
+ );
+ let id = egui::Id::new("roto-overlay");
+ let cached: Option<Overlay> = ctx.data(|d| d.get_temp(id));
+ let ov = match cached {
+ Some(c) if c.key == key => Some(c),
+ _ => {
- let ectx = EvalCtx { project: &app.session.project, comp_id: cid, comp, time, expr: app.session.expr.as_deref() };
++ let ectx = EvalCtx { project: &app.session.project, comp_id: cid, comp, time, expr: app.session.expr.as_deref(), footage: None };
+ let mut r = Renderer::new(&app.session.project, &*app.session.footage, RenderOpts { scale, ..Default::default() });
+ r.expr = app.session.expr.as_deref();
+ r.cache = Some(&app.session.layer_cache);
+ let (Some(inp), Some(out)) = (r.layer_input(&ectx, layer, idx), r.layer_input(&ectx, layer, idx + 1)) else { return };
+ let (w, h) = (inp.img.width as usize, inp.img.height as usize);
+ let a_at = |x: i64, y: i64| -> f32 {
+ // Output pixel at the same layer point.
+ let lx = (x as f64 + 0.5 - inp.offset[0]) / inp.scale;
+ let ly = (y as f64 + 0.5 - inp.offset[1]) / inp.scale;
+ let (ox, oy) = out.to_px([lx, ly]);
+ out.img.get(ox.floor() as i64, oy.floor() as i64)[3]
+ };
+ let alpha: Vec<f32> = (0..w * h).map(|i| a_at((i % w) as i64, (i / w) as i64)).collect();
+ let inside = |x: i64, y: i64| x >= 0 && y >= 0 && x < w as i64 && y < h as i64 && alpha[y as usize * w + x as usize] >= 0.5;
+ let mut px = vec![Color32::TRANSPARENT; w * h];
+ let bc = c32(o.boundary_color, 255);
+ let oc = c32(o.overlay_color, (o.overlay_opacity / 100.0 * 255.0).clamp(0.0, 255.0) as u8);
+ // View Search Region: the band around the boundary (yellow).
+ let search = roto_group(layer).filter(|g| g.prop("rotoBrushMatte/viewSearchRegion").is_some_and(|p| p.value.as_bool())).map(|g| {
+ let r = g.prop("rotoBrushMatte/searchRadius").map(|p| p.value.as_f64()).unwrap_or(15.0) * scale;
+ let bin: Vec<u8> = alpha.iter().map(|a| (*a >= 0.5) as u8).collect();
+ let sd = effectcraft_engine::track::roto::matting::signed_distance(&bin, w, h);
+ (sd, r as f32)
+ });
+ for y in 0..h as i64 {
+ for x in 0..w as i64 {
+ let i = y as usize * w + x as usize;
+ let a = alpha[i];
+ px[i] = match o.view.as_str() {
+ "alpha" => {
+ let v = (a.clamp(0.0, 1.0) * 255.0) as u8;
+ Color32::from_rgb(v, v, v)
+ }
+ "alphaOverlay" if a < 0.5 => oc,
+ "alphaOverlay" => Color32::TRANSPARENT,
+ _ => {
+ let me = a >= 0.5;
+ let edge = me && [(-1, 0), (1, 0), (0, -1), (0, 1)].iter().any(|(dx, dy)| !inside(x + dx, y + dy));
+ if edge { bc } else { Color32::TRANSPARENT }
+ }
+ };
+ if let Some((sd, r)) = &search {
+ let d = sd[i].abs();
+ if (d - r).abs() < 0.75 {
+ px[i] = Color32::from_rgb(255, 220, 0);
+ }
+ }
+ }
+ }
+ let img = egui::ColorImage { size: [w, h], pixels: px, source_size: egui::Vec2::new(w as f32, h as f32) };
+ let x0 = -inp.offset[0] / inp.scale;
+ let y0 = -inp.offset[1] / inp.scale;
+ let rect = [x0, y0, x0 + w as f64 / inp.scale, y0 + h as f64 / inp.scale];
+ let tex = ctx.load_texture("roto-overlay", img, egui::TextureOptions::NEAREST);
+ let c = Overlay { key, tex, rect };
+ ctx.data_mut(|d| d.insert_temp(id, c.clone()));
+ Some(c)
+ }
+ };
+ if let Some(ov) = ov {
+ let r = Rect::from_min_max(to_screen([ov.rect[0], ov.rect[1]]), to_screen([ov.rect[2], ov.rect[3]]));
+ painter.image(ov.tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
+ }
+ }
+
+ /// Pointer handling for the Roto Brush / Refine Edge tools. Returns true when it handled input.
+ pub fn interact(
+ app: &mut EffectcraftApp,
+ ui: &mut egui::Ui,
+ painter: &egui::Painter,
+ area: Rect,
+ layer: &Layer,
+ zoom: f64,
+ to_screen: &dyn Fn([f64; 2]) -> Pos2,
+ to_layer: &dyn Fn(Pos2) -> [f64; 2],
+ ) -> bool {
+ let ctx = ui.ctx().clone();
+ let mods = ui.input(|i| i.modifiers);
+ let Some(kind) = app.ui.tool.roto_kind(mods.alt) else { return false };
+ let resp = ui.interact(area, egui::Id::new("layer-panel-roto"), Sense::click_and_drag());
+ let o = app.session.state.roto.clone();
+ let refine = kind.starts_with("refine");
+ let dia = if refine { o.refine_diameter } else { o.diameter };
+ let col = match kind {
+ "fg" => Color32::from_rgb(40, 220, 60),
+ "bg" => Color32::from_rgb(235, 50, 40),
+ "refine" => Color32::from_rgb(110, 200, 255),
+ _ => Color32::from_rgb(255, 160, 60),
+ };
+ if let Some(hp) = resp.hover_pos() {
+ let lp = to_layer(hp);
+ app.pointer_comp = Some([lp[0] as f32, lp[1] as f32]);
+ ctx.set_cursor_icon(egui::CursorIcon::Crosshair);
+ let r = (dia * 0.5 * zoom) as f32;
+ painter.circle_stroke(hp, r, Stroke::new(1.5, col));
+ let sign = if kind == "bg" || kind == "refineErase" { "−" } else { "+" };
+ painter.text(hp, Align2::CENTER_CENTER, sign, Tokens::semibold(12.0), col);
+ }
+ let did = egui::Id::new("layer-panel-roto-drag");
+ if resp.drag_started()
+ && let Some(pos) = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos())
+ {
+ ctx.data_mut(|d| d.insert_temp(did, Drag { layer: layer.id.0, kind, points: vec![to_layer(pos)] }));
+ }
+ if let Some(mut d) = ctx.data(|d| d.get_temp::<Drag>(did)) {
+ if let Some(pos) = resp.interact_pointer_pos() {
+ let lp = to_layer(pos);
+ let last = d.points.last().copied().unwrap_or(lp);
+ if (lp[0] - last[0]).hypot(lp[1] - last[1]) * zoom >= 1.5 {
+ d.points.push(lp);
+ ctx.data_mut(|dd| dd.insert_temp(did, d.clone()));
+ }
+ }
+ let width = ((dia * zoom) as f32).max(1.0);
+ let pts: Vec<Pos2> = d.points.iter().map(|q| to_screen(*q)).collect();
+ let c = col.gamma_multiply(0.6);
+ if pts.len() == 1 {
+ painter.circle_filled(pts[0], width / 2.0, c);
+ } else {
+ painter.add(egui::Shape::line(pts, Stroke::new(width, c)));
+ }
+ if resp.drag_stopped() {
+ ctx.data_mut(|dd| dd.remove::<Drag>(did));
+ run_stroke(app, d.layer, d.kind, &d.points, dia / 2.0);
+ }
+ } else if resp.clicked()
+ && let Some(pos) = resp.interact_pointer_pos()
+ {
+ run_stroke(app, layer.id.0, kind, &[to_layer(pos)], dia / 2.0);
+ }
+ true
+ }
+
+ fn run_stroke(app: &mut EffectcraftApp, layer: u64, kind: &str, points: &[[f64; 2]], radius: f64) {
+ let r = app.session.execute("roto.stroke", json!({"layer": layer, "kind": kind, "points": points, "radius": radius}));
+ if let Err(e) = r {
+ app.ui.status = e.to_string();
+ }
+ }
+
+ /// The segmentation span bar (above the panel's bottom bar): the layer's frames, the span, the
+ /// base frame (yellow), computed frames (green) and stroke frames. Click to go to a frame; drag
+ /// the span's ends to change it.
+ pub fn span_bar(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, r: Rect, comp: &Comp, layer: &Layer) {
+ let t = app.tokens;
+ let Some(g) = roto_group(layer) else { return };
+ let Some(cid) = app.session.active_comp_id() else { return };
+ let uid = g.uid;
+ let params = effectcraft_engine::effects::flatten_params(g, &mut |p| p.value.clone());
+ let d = fx::data(&params);
+ p.rect_filled(r, 0.0, t.panel_bg);
+ let lim = effectcraft_engine::roto::frame_limits(comp, layer);
+ let n = (lim[1] - lim[0] + 1).max(1) as f32;
+ let track = Rect::from_min_max(pos2(r.min.x + 10.0, r.min.y + 4.0), pos2(r.max.x - 10.0, r.max.y - 4.0));
+ let x_of = |f: f64| track.min.x + ((f - lim[0] as f64) / n as f64) as f32 * track.width();
+ let f_of = |x: f32| (lim[0] as f64 + ((x - track.min.x) / track.width()).clamp(0.0, 0.9999) as f64 * n as f64).floor() as i64;
+ p.rect_filled(track, 2.0, t.pasteboard);
+ if let Some(base) = d.base {
+ let sp = Rect::from_min_max(pos2(x_of(d.span[0] as f64), track.min.y), pos2(x_of(d.span[1] as f64 + 1.0), track.max.y));
+ let frozen = fx::is_frozen(&params);
+ p.rect_filled(sp, 2.0, if frozen { Color32::from_rgb(60, 110, 190) } else { Color32::from_rgb(90, 90, 96) });
+ for (f, done) in app.session.roto_computed(cid, layer.id, uid) {
+ if done {
+ let cr = Rect::from_min_max(pos2(x_of(f as f64), track.max.y - 4.0), pos2(x_of(f as f64 + 1.0), track.max.y));
+ p.rect_filled(cr, 0.0, Color32::from_rgb(70, 200, 90));
+ }
+ }
+ for f in d.stroke_frames() {
+ let x = x_of(f as f64 + 0.5);
+ p.line_segment([pos2(x, track.min.y), pos2(x, track.min.y + 5.0)], Stroke::new(2.0, Color32::WHITE));
+ }
+ let bx = x_of(base as f64 + 0.5);
+ p.rect_filled(Rect::from_center_size(pos2(bx, track.center().y), vec2(6.0, track.height())), 1.0, Color32::from_rgb(240, 200, 40));
+ }
+ // Current time.
+ let fps = comp.frame_rate.as_f64();
+ let cur = fx::frame_of(layer.layer_time(app.session.time()).seconds(), fps);
+ let cx = x_of(cur as f64 + 0.5);
+ p.line_segment([pos2(cx, r.min.y), pos2(cx, r.max.y)], Stroke::new(1.0, t.timecode));
+ p.rect_stroke(track, 2.0, Stroke::new(1.0, Color32::from_black_alpha(140)), StrokeKind::Outside);
+ app.auto.add("layerPanel.rotoSpan", track, "Segmentation span");
+ let resp = ui.interact(track, egui::Id::new("roto-span-bar"), Sense::click_and_drag());
+ let hid = egui::Id::new("roto-span-handle");
+ if resp.drag_started()
+ && let (Some(pos), Some(_)) = (resp.interact_pointer_pos(), d.base)
+ {
+ let (a, b) = (x_of(d.span[0] as f64), x_of(d.span[1] as f64 + 1.0));
+ let h = if (pos.x - a).abs() < 6.0 {
+ 1
+ } else if (pos.x - b).abs() < 6.0 {
+ 2
+ } else {
+ 0
+ };
+ ui.ctx().data_mut(|m| m.insert_temp(hid, h));
+ }
+ let handle: i32 = ui.ctx().data(|m| m.get_temp(hid)).unwrap_or(0);
+ if let Some(pos) = resp.interact_pointer_pos() {
+ let f = f_of(pos.x);
+ if handle == 0 && (resp.clicked() || resp.dragged()) {
+ let t = layer.comp_time(comp.frame_rate.tick_of(f));
+ let _ = app.session.execute("time.set", json!({"time": t.seconds()}));
+ }
+ if handle != 0 && resp.dragged() {
+ p.line_segment([pos2(pos.x, track.min.y), pos2(pos.x, track.max.y)], Stroke::new(2.0, Color32::from_rgb(240, 200, 40)));
+ }
+ if handle != 0 && resp.drag_stopped() {
+ let k = if handle == 1 { "start" } else { "end" };
+ if let Err(e) = app.session.execute("roto.span", json!({"layer": layer.id.0, "effect": uid, k: f})) {
+ app.ui.status = e.to_string();
+ }
+ }
+ }
+ if resp.drag_stopped() {
+ ui.ctx().data_mut(|m| m.remove::<i32>(hid));
+ }
+ }
+
+ /// View-mode toggles and Freeze / Propagate buttons in the Layer panel's bottom bar, from `x`.
+ pub fn bar_buttons(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, bar: Rect, x: f32, layer: &Layer) {
+ let t = app.tokens;
+ let mut x = x;
+ let view = app.session.state.roto.view.clone();
+ for (id, label) in [("alpha", "Alpha"), ("alphaBoundary", "Boundary"), ("alphaOverlay", "Overlay")] {
+ let r = Rect::from_min_size(pos2(x, bar.center().y - 10.0), vec2(66.0, 20.0));
+ let on = view == id;
+ if widgets::text_button(ui, r, label, on, &t, egui::Id::new(("roto-view", id))).clicked() {
+ let v = if on { "none" } else { id };
+ let _ = app.session.execute("roto.options", json!({"view": v}));
+ }
+ app.auto.add(&format!("layerPanel.roto.view.{id}"), r, label);
+ x += 70.0;
+ }
+ let Some(g) = roto_group(layer) else { return };
+ let uid = g.uid;
+ let params = effectcraft_engine::effects::flatten_params(g, &mut |p| p.value.clone());
+ let frozen = fx::is_frozen(&params);
+ let running = app.session.is_roto_running();
+ x += 8.0;
+ let r = Rect::from_min_size(pos2(x, bar.center().y - 10.0), vec2(74.0, 20.0));
+ let label = if frozen { "Unfreeze" } else { "Freeze" };
+ if widgets::text_button(ui, r, label, frozen, &t, egui::Id::new(("roto-freeze", uid))).clicked() {
+ let id = if frozen { "roto.unfreeze" } else { "roto.freeze" };
+ if let Err(e) = app.session.execute(id, json!({"layer": layer.id.0, "effect": uid})) {
+ app.ui.status = e.to_string();
+ }
+ }
+ app.auto.add("layerPanel.roto.freeze", r, label);
+ x += 80.0;
+ if running {
+ let r = Rect::from_min_size(pos2(x, bar.center().y - 10.0), vec2(60.0, 20.0));
+ if widgets::text_button(ui, r, "Stop", false, &t, egui::Id::new("roto-stop")).clicked() {
+ let _ = app.session.execute("roto.cancel", json!({}));
+ }
+ app.auto.add("layerPanel.roto.stop", r, "Stop");
+ if let Some(pr) = app.session.roto_progress() {
+ p.text(pos2(r.max.x + 8.0, bar.center().y), Align2::LEFT_CENTER, pr.banner(), Tokens::ui(11.5), t.text_dim);
+ }
+ }
+ }
diff --cc docs/architecture.md
index a030e26c1,67d94fb92..7acd39228
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@@ -205,34 -219,63 +219,85 @@@ auto-scale; cached per analysis and set
borders from neighbouring frames read with `EffectHost::self_at`. The effect lives in the
effects crate, hence the `effects → track` edge.
+**Essential Graphics** (`project::essential`, `engine::commands::essential`): a comp's
+`essential` field lists its exposed controls (properties, Media Replacement, groups, comments).
+Every precomp layer of such a comp gets an Essential Properties group (`GroupKind::Essential`,
+children `eg<control id>`), kept in step by `Session::edit`; editing a child overrides it for
+that instance. The renderer draws an instance with overrides from a copy of the project with the
+overridden source properties set (`essential::with_overrides`). Templates are `.ectemplate`
+ZIPs: `manifest.json` (controls), `project.ecproj` (the comp and its dependencies), `media/…` and
+`poster.png`; importing offsets every id past the project's (`essential::offset_ids`).
+**Responsive Design — Time**: a time-stretched precomp maps time piecewise so its protected
+marker regions play at 100 % (`eval::responsive_source_time`).
+
+**Proxies and interpretation**: an item's `proxy` (footage or comp) is decoded in its place at
+the source's nominal size when `RenderOpts::proxy` (Render Settings ▸ Proxy Use) allows it.
+Interpret Footage's Separate Fields turns each field into a frame at twice the rate (the other
+lines interpolated); pixel aspect stretches footage, solids and precomps in the comp
+(`EvalCtx::par_ratio`, not inherited by children); Invert Alpha and Interpret As Linear Light
+apply after decoding.
+
+ **3D Camera Tracker** (`effects::camera_tracker`, `engine::camera_track`, `effectcraft-track`'s
+ `camtrack`): `camera.analyze` / `track.camera` render the layer's input to the effect on a
+ background thread and run structure from motion in two steps. Step 1 follows Shi–Tomasi features
+ through the clip with pyramidal Lucas–Kanade (forward–backward checked, re-detected where the frame
+ has none) into long 2D tracks. Step 2 solves the camera: parallax keyframes; a two-view start from
+ the essential matrix (normalised 8-point in RANSAC) or a planar homography decomposition; incremental
+ resection and triangulation; a sparse Levenberg–Marquardt bundle adjustment (Schur complement over
+ the points, Huber loss) with the focal length fixed, shared, or per frame; a log-spaced and
+ golden-section focal search for Fixed Angle of View / Variable Zoom; a rotation-only model for tripod
+ pans, chosen by Auto Detect when it explains the tracks as well. Tracks and solve are stored as JSON
+ in hidden effect parameters with keys: changing the layer's frames clears both, changing Shot Type,
+ Angle of View, Solve Method or deleting points only re-solves. The solve's canonical frame maps to
+ comp space so the first frame's camera is the default comp camera (or so a chosen ground plane is
+ the X-Z plane at the origin); `camera.createFromSolve` keys a one-node "3D Tracker Camera" on every
+ frame and places text, solids, nulls or a shadow catcher and light on the target plane.
+
+ **Roto Brush & Refine Edge** (`effectcraft_track::roto`, `effects::roto`, `engine::roto`):
+ strokes (foreground, background, Refine Edge) are stored as JSON in the effect's hidden Strokes
+ parameter with the base frame and segmentation span. Each frame is segmented by graph cut
+ (Boykov–Jolly hard constraints, GrabCut colour mixtures, our own Boykov–Kolmogorov max-flow,
+ coarse to fine) and propagated to the next frame by warping the matte with block optical flow and
+ re-cutting in a Search Radius band; frames with correction strokes are re-cut with the warped
+ matte as a soft prior. Refine Edge bands get guided-filter + closed-form matting and
+ foreground-colour decontamination. Segmentations are derived data: each frame's chain key (Input
+ Key, settings, strokes from the base frame out) indexes a process-wide cache that renders fill on
+ demand (`self_at`) and `roto.propagate` fills in the background; `Session::edit` keeps the Input
+ Key in step with the layer's source, masks and upstream effects. Freeze stores final 8-bit mattes
+ in the effect.
+
## 5. Expressions
Expressions are JavaScript, run by boa, with After Effects' object model (`thisComp`, `thisLayer`,
`time`, `value`, `wiggle`, `loopOut`, vector maths on arrays, and so on). A syntax error keeps the
-text, disables the expression and shows a warning, like After Effects.
+text, disables the expression and shows a warning, like After Effects. `sampleImage` renders the
+sampled layer through the evaluating renderer's footage source (`EvalCtx::footage`), cached per
+thread and frame; `footage(name)` reads data footage (JSON, CSV, TSV imported with File ▸ Import,
+text kept in the project) through `sourceData`, `sourceText` and `dataValue`. `expr.errors`
+lists failing expressions for the viewer's error bar.
+ ## 5a. Scripting
+
+ `effectcraft-script` runs JavaScript (boa, a fresh context per run; the Script Console keeps one)
+ with an object model written from the behaviour the After Effects Scripting Guide documents:
+ `app`, `Project`, `ItemCollection`, `CompItem`/`FootageItem`/`FolderItem`, `LayerCollection`,
+ `AVLayer`/`TextLayer`/`ShapeLayer`/`CameraLayer`/`LightLayer`, `PropertyGroup`/`Property`
+ (values, keyframes, eases, expressions), `TextDocument`, `Shape`, `KeyframeEase`, `MarkerValue`,
+ `RenderQueue`/`RenderQueueItem`/`OutputModule`, `File`/`Folder` and the enums. The model lives in
+ `prelude.js`; it reads the session through `__query` (JSON snapshots of items, layers, property
+ nodes, values and keys) and edits only through `__exec`, which runs engine commands, so every
+ scripted edit is undoable and identical to the UI's. While a script runs the session is moved
+ into a thread-local the natives borrow (nothing borrowed enters the JS heap); the comp a call
+ targets is made active for that command only. `app.beginUndoGroup`/`endUndoGroup` fold the undo
+ steps in between into one named step. Match names (`ADBE Transform Group`, `ADBE Position`,
+ `ADBE Gaussian Blur 2`, `ADBE Vector Shape - Rect`…) come from a table in `matchnames.rs`; effect
+ parameters are `<effect match name>-0001…`. `File` reads are limited to the project's folder, and
+ writes and the network are refused, unless Preferences ▸ Scripting & Expressions ▸ Allow Scripts
+ to Write Files and Access Network is on. Entry points: the `script.run` command
+ (`Session::script`, set by the host), File ▸ Scripts ▸ Run Script File… (`.jsx`/`.js`; `.json`
+ command scripts still run as steps), Window ▸ Script Console, `effectcraft-cli script` and the
+ MCP `run_script` tool.
+
## 6. Commands, the UI seam and automation
Every action is a command: an id, a label, a menu path, a shortcut, a parameter description,
diff --cc docs/parity.md
index 37b2d670a,0f3103ac4..074c68ba5
--- a/docs/parity.md
+++ b/docs/parity.md
@@@ -84,22 -85,22 +85,22 @@@ the disk cache in the formats wave; th
| Area | Weighted parity | Remaining (agent-hours) | Biggest gaps |
|---|---|---|---|
| Layers | 88% | 4.8 | frame blending, collapse transformations, slip edit |
- | Output | 85% | 4.2 | multiple output modules, pre-render, WebM, audio-only |
+ | Output | 90% | 3.0 | multiple output modules, pre-render (WebM with VP9 alpha + Opus and WAV/AIFF audio-only landed: VP9 is intra-only, Opus CELT-only) |
| Audio | 85% | 0.5 | audio to keyframes |
- | Import | 78% | 4.5 | PSD, SVG as shapes, Lottie |
- | Automation | 76% | 3.3 | a JavaScript scripting object model |
+ | Import | 88% | 2.0 | AI/EPS/PDF vector footage, PSD smart objects and 3D layers (PSD as footage/composition/retain layer sizes, SVG footage and Create Shapes from Vector Layer landed) |
+ | Automation | ≈ 90% | 0.8 | scripting covers the documented core object model (AUT-2, M14.4: `app`, project items, comps, layers, properties and keyframes, text documents, markers, render queue, Script Console, `effectcraft-cli script`, MCP `run_script`); still missing: ScriptUI panels/dialogs, `.jsxbin`, sockets |
| Shapes | 68% | 3.9 | taper and wave strokes (pen tool for shape paths and vertex editing landed in M6.5) |
- | Compositions | ≈ 75% | 5.0 | marker dialog, flowchart (Essential Graphics with master properties, `.ectemplate` templates and Responsive Design — Time landed: CMP-7) |
-| Compositions | 72% | 6.0 | Essential Graphics panel (the marker dialog and Composition Flowchart landed) |
++| Compositions | ≈ 80% | 3.5 | Mocha-style planar tracks for templates, Essential Graphics' rare controls (font menus, mirrored properties) (the marker dialog, Composition Flowchart, Essential Graphics with master properties, `.ectemplate` templates and Responsive Design — Time landed: CMP-6, CMP-7) |
| Animation | 65% | 10.4 | puppet, Wiggler/Smoother/Motion Sketch (motion-path handles and the graph editor transform box landed in M5.8) |
| Text | ≈ 86% | 1.3 | vertical type is basic (upright characters, no tate-chu-yoko), no OpenType feature panel, no extruded strokes (extruded, bevelled text landed in M7.6); per-character styles, paragraph settings, on-canvas editing and the `sourceText` style API landed (M9.9–M9.10) |
| Web | 60% | 2.5 | threads, browser storage, audio |
- | 3D | 72% | 12.0 | 3D camera tracker, multi-view layouts, Advanced 3D motion blur and blend modes, cameras/lights from models; Advanced 3D (glTF/OBJ models, primitives, extruded text and shapes, PBR, image-based light, shadow maps, GPU rasteriser) landed in M7.4–M7.6 |
- | Effects | ≈ 75% | 5.0 | GPU versions of more effects and the 3D Camera Tracker (every other After Effects effect exists since M9.11 and M12.5) |
- | Interface | 55% | 10.4 | drag-to-dock and floating panels, preferences, native macOS menus (viewer rulers/snapping/channels/snapshots landed in M0.13) |
+ | 3D | 76% | 10.0 | multi-view layouts, Advanced 3D motion blur and blend modes, cameras/lights from models; Advanced 3D (glTF/OBJ models, primitives, extruded text and shapes, PBR, image-based light, shadow maps, GPU rasteriser) landed in M7.4–M7.6 |
+ | Effects | ≈ 75% | 5.0 | GPU versions of more effects (every After Effects effect exists since M9.11, M12.5 and M12.6) |
+ | Interface | 70% | 6.0 | Timeline horizontal scrolling of many columns, a richer Learn area (native macOS menu bar, Timeline columns/search/reveal-add, Home screen with recent projects and all AE workspaces landed; viewer rulers/snapping/channels/snapshots landed in M0.13) |
-| Project | 53% | 8.1 | 8/16/32-bit pipeline and colour management, auto-save, proxies, folder moves |
+| Project | ≈ 60% | 6.5 | 8/16/32-bit pipeline and colour management, auto-save, folder moves (proxies and Interpret Footage fields / pixel aspect / alpha guess landed: PRJ-8, PRJ-3) |
- | Masks & roto | 52% | 10.0 | Roto Brush, variable-width mask feather points (mask tracking and Mask Interpolation landed in M6.6) |
- | Preview | 55% | 6.1 | GPU 3D and adjustment layers, disk cache (region of interest, snapshots, exposure and Fast Previews landed in M0.13) |
- | Tracking | ≈ 70% | 4.0 | 3D camera tracker, face tracking and Subspace Warp's mesh warp (Rolling Shutter Repair landed in M9.11; point tracker, mask tracking and Warp Stabilizer landed in M6.x / M12.5) |
+ | Masks & roto | 68% | 6.0 | variable-width mask feather points, Roto Brush's learned (3.0) segmentation model (mask tracking and Mask Interpolation landed in M6.6; Roto Brush & Refine Edge with graph-cut segmentation, flow propagation, edge matting, decontamination and Freeze in M6.7) |
+ | Preview | 62% | 5.0 | GPU 3D and adjustment layers (persistent disk cache with the blue cache bar landed; region of interest, snapshots, exposure and Fast Previews landed in M0.13) |
+ | Tracking | ≈ 85% | 2.5 | face tracking, Subspace Warp's mesh warp, lens distortion in the camera solve (Rolling Shutter Repair landed in M9.11; point tracker, mask tracking, Warp Stabilizer and the 3D Camera Tracker landed in M6.x / M12.5 / M12.6) |
| Paint | 0% | 4.0 | Brush, Clone Stamp, Eraser |
## Effects still missing
@@@ -134,10 -135,10 +135,10 @@@ Mocha and Cineware are third-party and
7. Point tracking and stabilization (in progress).
8. Frame blending, collapse transformations, slip edit.
9. A real 8/16/32-bit pipeline with linear blending and colour management.
- 10. Drag-to-dock and floating panels, saved workspaces, native macOS menus.
+ 10. ~~Drag-to-dock and floating panels, saved workspaces, native macOS menus.~~
11. Auto-save, crash recovery, recent projects (in progress).
-12. Expression gaps: `sampleImage`, `footage()` (the `sourceText` style API landed in M9.9).
+12. ~~Expression gaps: `sampleImage`, `footage()`~~ (landed with data footage, the error bar and the Expression Language menu; the `sourceText` style API landed in M9.9).
- 13. Lottie (in progress), WebM, SVG and PSD import.
+ 13. ~~Lottie, WebM, SVG and PSD import~~ (landed; a disk cache too).
14. Puppet and paint tools (in progress).
15. Preferences and a shortcut editor that can rebind (in progress); real Wiggler, Smoother and Motion Sketch; the marker dialog.