Merge main into M13.14

This commit is contained in:
Brandon Thomas
2026-10-03 11:50:14 -04:00
324 changed files with 24730 additions and 457 deletions
+68 -7
View File
@@ -36,14 +36,56 @@ fn create(s: &mut Session, p: &Value) -> Result<Value> {
let doc = crate::vector::vector_doc(&f.path, &bytes, f.layer.as_ref(), f.page)
.unwrap_or_else(|| Err(format!("{}: not a vector file", f.path)))
.map_err(EngineError::Other)?;
let id = s.edit("Create Shapes from Vector Layer", None, |proj, st| {
let l = crate::vector::shapes_from_vector(proj, &comp, &src, &doc);
let id = l.id;
insert_above(proj, cid, lid, l, true)?;
st.selected_layers = vec![id];
Ok(id)
// Images become footage layers (PNG files written next to the source and
// imported), parented to the shape layer below it.
let (images, masks) = crate::vector::vector_images(&doc);
if masks > 0 {
skipped.push(format!("{}: {masks} soft mask(s) not converted (shape layers have no soft masks)", src.name));
}
let mut image_items = vec![];
for (i, img) in images.iter().enumerate() {
match image_footage(s, &f.path, i + 1, img) {
Ok(item) => image_items.push((item, i)),
Err(e) => skipped.push(format!("{}: image {} not converted ({e})", src.name, i + 1)),
}
if img.clipped {
skipped.push(format!("{}: image {} is clipped or masked; its footage layer is not", src.name, i + 1));
}
}
let mut notes = vec![];
let ids = s.edit("Create Shapes from Vector Layer", None, |proj, st| {
// Without images: one shape layer. With images: the shapes between them
// in layers of their own, so the stack keeps the document's paint order.
let segments = if image_items.is_empty() { vec![doc.clone()] } else { crate::vector::split_at_images(&doc) };
let top = crate::vector::shapes_from_vector(proj, &comp, &src, segments.last().unwrap_or(&doc));
// Top to bottom: the last segment, image n, segment n − 1, … image 1, segment 0.
let mut stack = vec![];
for k in (0..segments.len().saturating_sub(1)).rev() {
if let Some((item, i)) = image_items.iter().find(|(_, i)| *i == k) {
let (il, note) = crate::vector::image_layer(proj, &comp, *item, &images[*i], &top);
notes.extend(note);
stack.push(il);
}
let seg = &segments[k];
if seg.root.children.is_empty() {
continue;
}
let mut sl = crate::vector::shapes_from_vector(proj, &comp, &src, seg);
sl.name = format!("{} {}", top.name, k + 1);
stack.push(sl);
}
let mut ids = vec![top.id];
ids.extend(stack.iter().filter(|l| matches!(l.source, LayerSource::Shape)).map(|l| l.id));
// Each directly above the source: the top layer first.
insert_above(proj, cid, lid, top, true)?;
for l in stack {
insert_above(proj, cid, lid, l, true)?;
}
st.selected_layers = vec![ids[0]];
Ok(ids)
})?;
created.push(id.0);
skipped.extend(notes);
created.extend(ids.iter().map(|i| i.0));
}
"shapesFromText" => {
if !matches!(src.source, LayerSource::Text) {
@@ -118,6 +160,25 @@ fn create(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"layers": created, "skipped": skipped}))
}
/// An image of a vector file written as `<file> Image <n>.png` next to it and imported: the
/// footage item.
fn image_footage(s: &mut Session, source: &str, n: usize, img: &crate::vector::VectorImage) -> Result<effectcraft_project::ItemId> {
let src = std::path::Path::new(source);
let stem = src.file_stem().map(|x| x.to_string_lossy().into_owned()).unwrap_or_else(|| "Vector".into());
let name = format!("{stem} Image {n}.png");
let path = match src.parent().filter(|p| !p.as_os_str().is_empty()) {
Some(dir) => dir.join(&name).to_string_lossy().into_owned(),
None => name,
};
let png = super::comp_more::encode_png(&img.rgba, img.width, img.height).map_err(EngineError::Other)?;
s.services.write_file(&path, &png).map_err(|e| EngineError::Other(format!("cannot write {path}: {e}")))?;
let r = super::file::import(s, &json!({"paths": [path]}))?;
if let Some(e) = r["errors"].as_array().and_then(|e| e.first()) {
return Err(EngineError::Other(e.as_str().unwrap_or("import failed").to_string()));
}
r["items"].get(0).and_then(Value::as_u64).map(effectcraft_project::ItemId).ok_or_else(|| EngineError::Other(format!("{path} was not imported")))
}
/// Insert `l` directly above layer `below`; optionally switch the source's video off (as After
/// Effects does after converting).
fn insert_above(
+189 -32
View File
@@ -96,6 +96,9 @@ fn add_property(s: &mut Session, p: &Value) -> Result<Value> {
Some(t)
}
};
// A property already in the panel (as the same kind of control) is added again as a mirror
// (`mirror: false`: skipped).
let mirror = b_p(p, "mirror").unwrap_or(true);
let mut added = vec![];
for (cid, lid, uid) in &targets {
let l = s.project.comp(*cid).and_then(|c| c.layer(*lid)).ok_or(EngineError::NoComp)?;
@@ -110,30 +113,122 @@ fn add_property(s: &mut Session, p: &Value) -> Result<Value> {
{
return Err(bad(C, format!("`{}` can't be shown as a {} control", pr.name, t.label())));
}
if s.project.comp(*cid).and_then(|c| c.essential.as_ref()).is_some_and(|e| e.control_for_as(*lid, *uid, as_type).is_some()) {
continue;
}
let name = rename.clone().unwrap_or_else(|| match as_type {
let eg = s.project.comp(*cid).and_then(|c| c.essential.as_ref());
let existing = eg
.and_then(|e| e.control_for_as(*lid, *uid, as_type).or_else(|| as_type.is_none().then(|| e.driver_of(*lid, *uid)).flatten()))
.map(|c| (c.id, c.name.clone()));
let (kind, as_type) = match existing {
Some(_) if !mirror => continue,
Some((of, _)) => (EgKind::Mirror { of }, None),
None => (EgKind::Property { layer: *lid, prop: *uid, links: vec![] }, as_type),
};
let name = rename.clone().or(existing.map(|e| e.1)).unwrap_or_else(|| match as_type {
Some(ControlType::Font) => format!("{} Font", l.name),
_ => pr.name.clone(),
});
added.push((*cid, *lid, *uid, name, as_type));
added.push((*cid, kind, name, as_type));
}
let ids = s.edit("Add Property to Essential Graphics", None, |proj, st| {
if let Some((cid, ..)) = added.first() {
st.essential_primary.get_or_insert(*cid);
}
let mut ids = vec![];
for (k, (cid, lid, uid, name, as_type)) in added.iter().enumerate() {
for (k, (cid, kind, name, as_type)) in added.iter().enumerate() {
let id = proj.alloc();
let eg = eg_of(proj, *cid)?;
let ctl = EgControl { id, name: name.clone(), kind: EgKind::Property { layer: *lid, prop: *uid }, as_type: *as_type };
let ctl = EgControl { id, name: name.clone(), kind: kind.clone(), as_type: *as_type };
insert(eg, ctl, group, index.map(|i| i + k), C)?;
ids.push(id);
}
Ok(ids)
})?;
Ok(json!({"controls": ids}))
let mirrors: Vec<u64> = ids.iter().zip(&added).filter(|(_, a)| matches!(a.1, EgKind::Mirror { .. })).map(|(i, _)| *i).collect();
Ok(json!({"controls": ids, "mirrors": mirrors}))
}
/// Add a mirror of a property control (the same property shown again, e.g. in another group).
fn add_mirror(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "essential.addMirror";
let cid = eg_comp(s, p)?;
let of = control_p(p, C)?;
let eg = s.project.comp(cid).and_then(|c| c.essential.clone()).unwrap_or_default();
let master =
eg.resolve(of).filter(|c| matches!(c.kind, EgKind::Property { .. })).ok_or_else(|| bad(C, format!("control {of} is not a property control")))?;
let (of, master_name) = (master.id, master.name.clone());
let name = str_p(p, "name").map(str::to_string).unwrap_or(master_name);
let group = p.get("group").and_then(Value::as_u64);
let index = p.get("index").and_then(Value::as_u64).map(|i| i as usize);
let id = s.edit("Add Mirror to Essential Graphics", None, |proj, _| {
let id = proj.alloc();
insert(eg_of(proj, cid)?, EgControl { id, name, kind: EgKind::Mirror { of }, as_type: None }, group, index, C)?;
Ok(id)
})?;
Ok(json!({"control": id, "of": of}))
}
/// The property a link command names: `{layer, path|prop}` or the first selected property.
fn link_target(s: &Session, p: &Value, cmd: &str) -> Result<(ItemId, LayerId, Uid)> {
if p.get("path").is_some() || p.get("prop").is_some() {
return super::prop::prop_ref(s, p, cmd);
}
let cid = comp_id(s, p)?;
selected_leaf_props(s)
.into_iter()
.next()
.map(|(l, u)| (cid, l, u))
.ok_or_else(|| bad(cmd, "select a property in the timeline (or give `layer` and `path`)"))
}
/// Make a property control drive another property too (same kind of value).
fn link_property(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "essential.linkProperty";
let cid = eg_comp(s, p)?;
let control = control_p(p, C)?;
let (pc, lid, uid) = link_target(s, p, C)?;
if pc != cid {
return Err(bad(C, "the property must be in the Essential Graphics composition"));
}
let eg = s.project.comp(cid).and_then(|c| c.essential.clone()).unwrap_or_default();
let ctl = eg.resolve(control).ok_or_else(|| bad(C, format!("no control {control}")))?.clone();
if ctl.as_type == Some(ControlType::Font) {
return Err(bad(C, "a Font control can't drive other properties"));
}
let (main, _) = essential::source_prop(&s.project, cid, &ctl).ok_or_else(|| bad(C, format!("control {control} is not a property control")))?;
let main = main.props.find(match ctl.kind {
EgKind::Property { prop, .. } => prop,
_ => 0,
});
let target = s.project.comp(cid).and_then(|c| c.layer(lid)).and_then(|l| l.props.find(uid)).ok_or_else(|| bad(C, "no such property"))?;
if !main.is_some_and(|m| essential::linkable(m, target)) {
return Err(bad(C, format!("`{}` is not the same kind of property as the control", target.name)));
}
if let Some(d) = eg.driver_of(lid, uid) {
return Err(bad(C, format!("`{}` is already driven by control {}", target.name, d.id)));
}
let id = ctl.id;
s.edit("Link Property to Essential Graphics Control", None, |proj, _| {
if let Some(EgControl { kind: EgKind::Property { links, .. }, .. }) = eg_of(proj, cid)?.find_mut(id) {
links.push(essential::EgLink { layer: lid, prop: uid });
}
Ok(())
})?;
Ok(json!({"control": id, "layer": lid.0, "prop": uid}))
}
fn unlink_property(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "essential.unlinkProperty";
let cid = eg_comp(s, p)?;
let control = control_p(p, C)?;
let (_, lid, uid) = link_target(s, p, C)?;
let eg = s.project.comp(cid).and_then(|c| c.essential.clone()).unwrap_or_default();
let id = eg.resolve(control).map(|c| c.id).ok_or_else(|| bad(C, format!("no control {control}")))?;
s.edit("Unlink Property from Essential Graphics Control", None, |proj, _| match eg_of(proj, cid)?.find_mut(id) {
Some(EgControl { kind: EgKind::Property { links, .. }, .. }) if links.iter().any(|k| k.layer == lid && k.prop == uid) => {
links.retain(|k| !(k.layer == lid && k.prop == uid));
Ok(())
}
_ => Err(bad(C, "the property is not linked to this control")),
})?;
Ok(json!({"control": id, "layer": lid.0, "prop": uid}))
}
fn control_type(pr: &effectcraft_project::Property) -> Option<ControlType> {
@@ -249,11 +344,17 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "essential.remove";
let cid = eg_comp(s, p)?;
let id = control_p(p, C)?;
// A property control's mirrors go with it.
let mirrors = s.project.comp(cid).and_then(|c| c.essential.as_ref()).map(|e| e.mirrors_of(id)).unwrap_or_default();
s.edit("Remove Essential Graphics Control", None, |proj, _| {
eg_of(proj, cid)?.remove(id).ok_or_else(|| bad(C, format!("no control {id}")))?;
let eg = eg_of(proj, cid)?;
eg.remove(id).ok_or_else(|| bad(C, format!("no control {id}")))?;
for m in &mirrors {
eg.remove(*m);
}
Ok(())
})?;
Ok(json!({"control": id}))
Ok(json!({"control": id, "mirrors": mirrors}))
}
fn move_control(s: &mut Session, p: &Value) -> Result<Value> {
@@ -381,8 +482,12 @@ pub fn supported_properties(project: &Project, cid: ItemId) -> Vec<Value> {
fn control_json(project: &Project, cid: ItemId, c: &EgControl) -> Value {
match &c.kind {
EgKind::Property { layer, prop } => {
EgKind::Property { layer, prop, .. } => {
let src = essential::source_prop(project, cid, c);
let links: Vec<Value> = essential::linked_props(project, cid, c)
.into_iter()
.map(|(l, pr)| json!({"layer": l.id.0, "layerName": l.name, "prop": pr.uid, "path": super::match_path_of(&l.props, pr.uid)}))
.collect();
json!({
"id": c.id, "name": c.name, "kind": "property", "layer": layer.0, "prop": prop,
"layerName": src.map(|(l, _)| l.name.clone()),
@@ -390,6 +495,24 @@ fn control_json(project: &Project, cid: ItemId, c: &EgControl) -> Value {
"type": src.and_then(|(_, pr)| essential::effective_type(c, pr)),
"value": src.map(|(_, pr)| value_json(essential::effective_type(c, pr), &pr.value_at(Tick::ZERO))),
"missing": src.is_none(),
"links": links,
"mirrors": project.comp(cid).and_then(|c| c.essential.as_ref()).map(|e| e.mirrors_of(c.id)).unwrap_or_default(),
})
}
EgKind::Mirror { of } => {
// Shown as its master (same kind of control).
let master = project.comp(cid).and_then(|x| x.essential.as_ref()).and_then(|e| e.resolve(c.id)).cloned();
let src = essential::source_prop(project, cid, c);
let ty = |pr| master.as_ref().and_then(|m| essential::effective_type(m, pr));
json!({
"id": c.id, "name": c.name, "kind": "mirror", "of": of,
"layer": src.map(|(l, _)| l.id.0),
"prop": src.map(|(_, pr)| pr.uid),
"layerName": src.map(|(l, _)| l.name.clone()),
"path": src.and_then(|(l, pr)| super::match_path_of(&l.props, pr.uid)),
"type": src.and_then(|(_, pr)| ty(pr)),
"value": src.map(|(_, pr)| value_json(ty(pr), &pr.value_at(Tick::ZERO))),
"missing": src.is_none(),
})
}
EgKind::Media { layer } => json!({
@@ -464,6 +587,7 @@ fn instance_json(s: &mut Session, p: &Value) -> Result<Value> {
}
let kind = match c.kind {
EgKind::Property { .. } => "property",
EgKind::Mirror { .. } => "mirror",
EgKind::Media { .. } => "media",
EgKind::Comment { .. } => "comment",
EgKind::Group { .. } => "group",
@@ -520,11 +644,21 @@ fn targets(s: &Session, cid: ItemId, lid: LayerId, p: &Value) -> Vec<(u64, Uid)>
let Some(l) = s.project.comp(cid).and_then(|c| c.layer(lid)) else { return vec![] };
let over = essential::overridden(l);
let Some(g) = essential::group(l) else { return vec![] };
let want = p.get("control").and_then(Value::as_u64);
// A control, its master and the master's mirrors share one value: act on all of them.
let want: Option<Vec<u64>> = p.get("control").and_then(Value::as_u64).map(|w| {
let src = match l.source {
LayerSource::Comp { item } => s.project.comp(item).and_then(|c| c.essential.as_ref()),
_ => None,
};
match src.and_then(|e| e.resolve(w).map(|m| (e, m.id))) {
Some((e, m)) => std::iter::once(m).chain(e.mirrors_of(m)).chain(std::iter::once(w)).collect(),
None => vec![w],
}
});
let mut out = vec![];
g.walk("", &mut |_, pr| {
if let Some(c) = essential::control_of(&pr.match_id)
&& want.is_none_or(|w| w == c)
&& want.as_ref().is_none_or(|w| w.contains(&c))
&& (want.is_some() || over.contains(&pr.uid))
{
out.push((c, pr.uid));
@@ -570,7 +704,8 @@ fn push_to_comp(s: &mut Session, p: &Value) -> Result<Value> {
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).cloned().ok_or(EngineError::NoComp)?;
let mut writes = vec![];
for (control, uid) in &ts {
let (Some(ctl), Some(pr)) = (eg.find(*control), l.props.find(*uid)) else { continue };
// A mirror pushes into its master's properties.
let (Some(ctl), Some(pr)) = (eg.resolve(*control), l.props.find(*uid)) else { continue };
writes.push((ctl.kind.clone(), pr.clone(), ctl.as_type));
}
s.edit("Push Override Values to Source", None, |proj, _| {
@@ -578,7 +713,7 @@ fn push_to_comp(s: &mut Session, p: &Value) -> Result<Value> {
for (kind, pr, as_type) in &writes {
match kind {
// A Font control writes only the font (the source keeps its text and keys).
EgKind::Property { layer, prop } if *as_type == Some(ControlType::Font) => {
EgKind::Property { layer, prop, .. } if *as_type == Some(ControlType::Font) => {
if let Some(target) = sc.layer_mut(*layer).and_then(|l| l.props.find_mut(*prop)) {
essential::merge_font(&mut target.value, &pr.value);
for k in &mut target.keys {
@@ -586,24 +721,27 @@ fn push_to_comp(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
EgKind::Property { layer, prop } => {
let Some(inner) = sc.layer_mut(*layer) else { continue };
// Instance keys are in the precomp layer's time (= the source comp's time);
// the source property's keys are in the inner layer's time.
let keys: Vec<_> = pr
.keys
.iter()
.map(|k| {
let mut k = k.clone();
k.time = inner.layer_time(k.time);
k
})
.collect();
if let Some(target) = inner.props.find_mut(*prop) {
target.value = pr.value.clone();
target.keys = keys;
EgKind::Property { .. } => {
for (layer, prop) in kind.targets() {
let Some(inner) = sc.layer_mut(layer) else { continue };
// Instance keys are in the precomp layer's time (= the source comp's
// time); the source property's keys are in the inner layer's time.
let keys: Vec<_> = pr
.keys
.iter()
.map(|k| {
let mut k = k.clone();
k.time = inner.layer_time(k.time);
k
})
.collect();
if let Some(target) = inner.props.find_mut(prop) {
target.value = pr.value.clone();
target.keys = keys;
}
}
}
EgKind::Media { layer } => {
if let Some(inner) = sc.layer_mut(*layer) {
inner.source = LayerSource::Footage { item: ItemId(pr.value.as_f64().max(0.0) as u64) };
@@ -843,10 +981,29 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Property to Essential Graphics",
["Animation"],
None,
"{comp?, layer?, path?|prop?: uid (default: the selected properties), name?, group?: control id, index?, as?: font (Source Text font family/style/size) | scale (uniform Scale)}",
"{comp?, layer?, path?|prop?: uid (default: the selected properties), name?, group?: control id, index?, as?: font (Source Text font family/style/size) | scale (uniform Scale), mirror?: bool (a property already present is added as a mirror; default true)}",
has_selected_props,
add_property
),
cmd!("essential.addMirror", "Add Mirror", [], None, "{comp?, control, name?, group?, index?}", has_eg, add_mirror),
cmd!(
"essential.linkProperty",
"Link Property to Control",
[],
None,
"{comp?, control, layer?, path?|prop? (default: the selected property)}",
has_eg,
link_property
),
cmd!(
"essential.unlinkProperty",
"Unlink Property",
[],
None,
"{comp?, control, layer?, path?|prop? (default: the selected property)}",
has_eg,
unlink_property
),
cmd!("essential.addMedia", "Add Media Replacement", [], None, "{layer, name?, group?}", has_comp, add_media),
cmd!("essential.addGroup", "Add Group", [], None, "{comp?, name?, index?}", has_comp, add_group),
cmd!("essential.addComment", "Add Comment", [], None, "{comp?, text?, group?}", has_comp, add_comment),
+72 -5
View File
@@ -213,7 +213,7 @@ fn apply_output(om: &mut OutputModule, templates: &RenderTemplates, roi: Option<
}
let before = om.clone();
if let Some(f) = str_p(p, "format") {
let f = OutputFormat::from_name(f).ok_or_else(|| bad(cmd, "format: h264|prores|webm|png|jpeg|tiff|exr|gif|wav|aiff"))?;
let f = OutputFormat::from_name(f).ok_or_else(|| bad(cmd, "format: h264|hevc|av1|prores|webm|png|jpeg|tiff|exr|gif|wav|aiff"))?;
om.set_format(f);
}
if let Some(c) = str_p(p, "channels") {
@@ -223,7 +223,7 @@ fn apply_output(om: &mut OutputModule, templates: &RenderTemplates, roi: Option<
"alpha" | "alphaonly" => Channels::Alpha,
_ => return Err(bad(cmd, "channels: rgb|rgba|alpha")),
};
if om.channels == Channels::Rgba && !om.format.supports_alpha() {
if om.channels == Channels::Rgba && !om.supports_alpha() {
return Err(bad(cmd, format!("{} has no alpha channel", om.format.label())));
}
}
@@ -234,6 +234,7 @@ fn apply_output(om: &mut OutputModule, templates: &RenderTemplates, roi: Option<
_ => return Err(bad(cmd, "color: straight|premultiplied")),
};
}
any |= apply_codec_options(om, p, cmd)?;
if let Some(q) = f_p(p, "quality") {
om.quality = q.clamp(1.0, 100.0) as u8;
}
@@ -377,6 +378,62 @@ fn apply_output(om: &mut OutputModule, templates: &RenderTemplates, roi: Option<
Ok(any)
}
/// HEVC / AV1 codec options, the WebM video codec and the Opus audio options.
fn apply_codec_options(om: &mut OutputModule, p: &Value, cmd: &str) -> Result<bool> {
use effectcraft_project::render_queue::{CodecProfile, OpusApplication, RateControlMode, VideoCodecOptions, WebmVideoCodec};
let mut any = false;
if let Some(c) = str_p(p, "webmCodec") {
om.webm_codec = match c.to_ascii_lowercase().as_str() {
"vp9" => WebmVideoCodec::Vp9,
"av1" => WebmVideoCodec::Av1,
_ => return Err(bad(cmd, "webmCodec: vp9|av1")),
};
if !om.supports_alpha() {
om.channels = Channels::Rgb;
}
any = true;
}
if let Some(v) = str_p(p, "profile") {
om.codec.profile = CodecProfile::from_name(v).ok_or_else(|| bad(cmd, "profile: main|main10"))?;
any = true;
}
match p.get("level") {
Some(Value::Null) => {
om.codec.level = None;
any = true;
}
Some(v) => {
let s = match v {
Value::String(s) => s.clone(),
other => other.to_string(),
};
om.codec.level = VideoCodecOptions::parse_level(&s).ok_or_else(|| bad(cmd, "level: auto|null or a level like 4.1"))?;
any = true;
}
None => {}
}
if let Some(v) = str_p(p, "rateControl") {
om.codec.rate_control = RateControlMode::from_name(v).ok_or_else(|| bad(cmd, "rateControl: bitrate|quality"))?;
any = true;
}
if let Some(q) = f_p(p, "quality") {
om.codec.quality = q.clamp(1.0, 100.0) as u8;
}
if let Some(b) = f_p(p, "audioBitrate") {
om.opus_bitrate_kbps = b.clamp(6.0, 510.0) as u32;
any = true;
}
if let Some(a) = str_p(p, "opusApplication") {
om.opus_application = match a.to_ascii_lowercase().as_str() {
"audio" | "music" => OpusApplication::Audio,
"voip" | "voice" | "speech" => OpusApplication::Voip,
_ => return Err(bad(cmd, "opusApplication: audio|voice")),
};
any = true;
}
Ok(any)
}
/// `module` (1-based; 1 = the first output module).
fn module_p(s: &Session, i: usize, p: &Value, cmd: &str) -> Result<usize> {
let n = p.get("module").and_then(Value::as_u64).unwrap_or(1) as usize;
@@ -618,7 +675,17 @@ fn formats(s: &mut Session, _: &Value) -> Result<Value> {
})
})
.collect();
Ok(json!({"formats": v, "proresProfiles": ProResProfile::ALL.iter().map(|p| p.label()).collect::<Vec<_>>()}))
use effectcraft_project::render_queue::{CodecProfile, VideoCodecOptions};
let level = |l: &u8| format!("{}.{}", l / 10, l % 10);
Ok(json!({
"formats": v,
"proresProfiles": ProResProfile::ALL.iter().map(|p| p.label()).collect::<Vec<_>>(),
"codecProfiles": CodecProfile::ALL.iter().map(|p| p.label()).collect::<Vec<_>>(),
"hevcLevels": VideoCodecOptions::HEVC_LEVELS.iter().map(level).collect::<Vec<_>>(),
"av1Levels": VideoCodecOptions::AV1_LEVELS.iter().map(level).collect::<Vec<_>>(),
"webmCodecs": ["vp9", "av1"],
"opusApplications": ["audio", "voice"],
}))
}
/// `item?|index?`, else the last item (the queue's newest entry).
@@ -902,7 +969,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add to Render Queue",
["Composition"],
Some("Cmd+M"),
"{comp?: id|name, template?: Render Settings template, format?: h264|prores|webm|png|jpeg|tiff|exr|gif|wav|aiff, output?: path|template, log?: errorsOnly|plusSettings|plusPerFrameInfo, quality?: best|draft|1-100 (jpeg, webm), resolution?: full|half|third|quarter|scale, proxyUse?, effects?, solo?, guideLayers?, colorDepth?, frameBlending?, fieldRender?, pulldown?, motionBlur?, timeSpan?: workArea|comp|custom, start?: s, end?: s, duration?: s, frameRate?: fps|null, skipExisting?: bool, storageOverflow?: bool, channels?: rgb|rgba|alpha, color?, bitrate?: kbps, webmBitrate?, keyframeInterval?, proresProfile?, crop?, resize?, includeProjectLink?, audio?: auto|on|off, sampleRate?, audioChannels?, audioFormat?, loop?: bool (values as in setRenderSettings / setOutputModule)}",
"{comp?: id|name, template?: Render Settings template, format?: h264|hevc|av1|prores|webm|png|jpeg|tiff|exr|gif|wav|aiff, output?: path|template, log?: errorsOnly|plusSettings|plusPerFrameInfo, quality?: best|draft|1-100 (jpeg, webm), resolution?: full|half|third|quarter|scale, proxyUse?, effects?, solo?, guideLayers?, colorDepth?, frameBlending?, fieldRender?, pulldown?, motionBlur?, timeSpan?: workArea|comp|custom, start?: s, end?: s, duration?: s, frameRate?: fps|null, skipExisting?: bool, storageOverflow?: bool, channels?: rgb|rgba|alpha, color?, bitrate?: kbps, webmBitrate?, keyframeInterval?, proresProfile?, profile?, level?, rateControl?, webmCodec?, audioBitrate?, opusApplication?, crop?, resize?, includeProjectLink?, audio?: auto|on|off, sampleRate?, audioChannels?, audioFormat?, loop?: bool (values as in setRenderSettings / setOutputModule)}",
can_add,
add
),
@@ -922,7 +989,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Output Module Settings...",
[],
None,
"{item?|index?, module?: n (1 = first), template?: name, format?, channels?: rgb|rgba|alpha, color?: straight|premultiplied, quality?: 1-100, bitrate?: kbps, webmBitrate?: bool, keyframeInterval?: frames, proresProfile?: proxy|lt|standard|hq|4444|4444xq, crop?: bool|{useRoi?, roi?, top?, left?, bottom?, right?}, cropTop?, cropLeft?, cropBottom?, cropRight?, resize?: bool|{preset?, width?, height?, lockAspect?, quality?: low|high}, resizeWidth?, resizeHeight?, postRenderAction?: none|import|importAndReplace|setProxy, includeProjectLink?: bool, audio?: auto|on|off, sampleRate?, audioChannels?: mono|stereo, audioFormat?: 16|24|32, loop?: bool, output?}",
"{item?|index?, module?: n (1 = first), template?: name, format?: h264|hevc|av1|prores|webm|png|jpeg|tiff|exr|gif|wav|aiff, channels?: rgb|rgba|alpha, color?: straight|premultiplied, quality?: 1-100, bitrate?: kbps, webmBitrate?: bool, keyframeInterval?: frames (0 = auto), proresProfile?: proxy|lt|standard|hq|4444|4444xq, profile?: main|main10 (HEVC/AV1), level?: auto|4.1, rateControl?: bitrate|quality, webmCodec?: vp9|av1, audioBitrate?: Opus kbps, opusApplication?: audio|voice, crop?: bool|{useRoi?, roi?, top?, left?, bottom?, right?}, cropTop?, cropLeft?, cropBottom?, cropRight?, resize?: bool|{preset?, width?, height?, lockAspect?, quality?: low|high}, resizeWidth?, resizeHeight?, postRenderAction?: none|import|importAndReplace|setProxy, includeProjectLink?: bool, audio?: auto|on|off, sampleRate?, audioChannels?: mono|stereo, audioFormat?: 16|24|32, loop?: bool, output?}",
has_items,
set_output_module
),
+2
View File
@@ -856,6 +856,8 @@ mod tests_anim_tools;
#[cfg(test)]
mod tests_camera_track;
#[cfg(test)]
mod tests_codec_options;
#[cfg(test)]
mod tests_color_view;
#[cfg(test)]
mod tests_disk_cache;
+1 -1
View File
@@ -173,7 +173,7 @@ pub fn bytes_per_frame(om: &OutputModule, w: u32, h: u32, fps: f64) -> f64 {
let px = (w as f64 * h as f64) / (1920.0 * 1080.0);
let mbps = |m: f64| m * 1_000_000.0 / 8.0;
match om.format {
OutputFormat::H264 => om.bitrate_kbps as f64 * 1000.0 / 8.0 / fps,
OutputFormat::H264 | OutputFormat::Hevc | OutputFormat::Av1 => om.bitrate_kbps as f64 * 1000.0 / 8.0 / fps,
OutputFormat::ProRes => {
let rate = match om.prores_profile {
Proxy => 45.0,
+1 -1
View File
@@ -159,6 +159,6 @@ fn without_exporter() {
s.execute("renderQueue.add", json!({})).unwrap();
assert!(!s.is_enabled("renderQueue.render"));
let f = s.execute("renderQueue.formats", json!({})).unwrap();
assert_eq!(f["formats"].as_array().unwrap().len(), 10);
assert_eq!(f["formats"].as_array().unwrap().len(), 12);
assert_eq!(f["formats"][0]["available"], false);
}
+145 -2
View File
@@ -116,6 +116,8 @@ pub struct Widget {
/// Frontends paint it instead of the control's default look, unless it contains
/// [`DrawOp::Os`] (`drawOSControl()`), which draws the default look first.
pub draw: Vec<DrawOp>,
/// The image of an image control or icon button.
pub image: Option<ImageRef>,
pub children: Vec<Widget>,
}
@@ -156,8 +158,37 @@ pub enum DrawOp {
},
/// `drawOSControl()`: the control's default look.
Os,
/// `drawImage(image, x, y, w?, h?)` (drawn as a placeholder frame).
Image { x: f64, y: f64, w: f64, h: f64 },
/// `drawImage(image, x, y, w?, h?)`: `w` / `h` 0 = the image's own size.
Image {
#[serde(default)]
image: Option<ImageRef>,
x: f64,
y: f64,
w: f64,
h: f64,
},
}
/// A ScriptUIImage (`ScriptUI.newImage`, an image control's or icon button's image, a
/// `drawImage` argument): an image file, or embedded PNG / JPEG bytes.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(default)]
pub struct ImageRef {
/// File path (or a resource name we can't resolve: drawn as a placeholder).
pub src: Option<String>,
/// Embedded bytes as a binary string (one character per byte, as in resource strings).
pub data: Option<String>,
pub name: String,
}
impl ImageRef {
/// The encoded image bytes (the embedded data, else the file through `services`).
pub fn bytes(&self, services: &dyn crate::Services) -> Option<Vec<u8>> {
if let Some(d) = &self.data {
return d.chars().map(|c| u8::try_from(c as u32).ok()).collect();
}
services.read_file(self.src.as_deref()?).ok()
}
}
impl PathSeg {
@@ -207,6 +238,67 @@ impl PathSeg {
flush(&mut cur, &mut out, false);
out
}
/// The area `fillPath` paints, as triangles: every subpath closed, overlapping subpaths
/// combined by the non-zero winding rule (`even_odd`: the even-odd rule), so concave,
/// self-intersecting and holed paths fill correctly (frontends' polygon fills are often
/// convex-only). Exact trapezoid decomposition: the plane is cut into horizontal bands at
/// every vertex and edge crossing; inside a band no edges cross, so each inside span is a
/// trapezoid (two triangles).
pub fn fill_triangles(path: &[PathSeg], n: usize, even_odd: bool) -> Vec<[[f64; 2]; 3]> {
// Non-horizontal edges, top to bottom, with their winding direction.
let mut edges: Vec<([f64; 2], [f64; 2], i32)> = vec![];
for (pts, _) in PathSeg::polylines(path, n) {
for i in 0..pts.len() {
let (a, b) = (pts[i], pts[(i + 1) % pts.len()]);
if !(a[0].is_finite() && a[1].is_finite() && b[0].is_finite() && b[1].is_finite()) || a[1] == b[1] {
continue;
}
edges.push(if a[1] < b[1] { (a, b, 1) } else { (b, a, -1) });
}
}
if edges.len() < 2 {
return vec![];
}
let x_at = |e: &([f64; 2], [f64; 2], i32), y: f64| e.0[0] + (e.1[0] - e.0[0]) * (y - e.0[1]) / (e.1[1] - e.0[1]);
let mut ys: Vec<f64> = edges.iter().flat_map(|e| [e.0[1], e.1[1]]).collect();
// Where two edges cross, a band boundary.
for i in 0..edges.len() {
for j in i + 1..edges.len() {
let (a, b) = (&edges[i], &edges[j]);
let (lo, hi) = (a.0[1].max(b.0[1]), a.1[1].min(b.1[1]));
if hi <= lo {
continue;
}
let (d0, d1) = (x_at(a, lo) - x_at(b, lo), x_at(a, hi) - x_at(b, hi));
if d0 * d1 < 0.0 {
ys.push(lo + (hi - lo) * d0 / (d0 - d1));
}
}
}
ys.sort_by(f64::total_cmp);
ys.dedup_by(|a, b| (*a - *b).abs() < 1e-9);
let mut out = vec![];
let mut row: Vec<(f64, f64, f64, i32)> = vec![];
for w in ys.windows(2) {
let (ya, yb) = (w[0], w[1]);
let ym = (ya + yb) * 0.5;
row.clear();
row.extend(edges.iter().filter(|e| e.0[1] < ym && ym < e.1[1]).map(|e| (x_at(e, ym), x_at(e, ya), x_at(e, yb), e.2)));
row.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut wind = 0;
for k in 0..row.len().saturating_sub(1) {
wind += row[k].3;
let inside = if even_odd { wind % 2 != 0 } else { wind != 0 };
if inside {
let (l, r) = (row[k], row[k + 1]);
out.push([[l.1, ya], [r.1, ya], [r.2, yb]]);
out.push([[l.1, ya], [r.2, yb], [l.2, yb]]);
}
}
}
out
}
}
impl Widget {
@@ -689,4 +781,55 @@ mod tests {
let j = serde_json::to_value(&ui).unwrap();
assert_eq!(j["windows"][0]["root"]["type"], "window");
}
fn area(tris: &[[[f64; 2]; 3]]) -> f64 {
tris.iter().map(|t| ((t[1][0] - t[0][0]) * (t[2][1] - t[0][1]) - (t[2][0] - t[0][0]) * (t[1][1] - t[0][1])).abs() * 0.5).sum()
}
fn poly(pts: &[[f64; 2]]) -> Vec<PathSeg> {
let mut v = vec![PathSeg::M { x: pts[0][0], y: pts[0][1] }];
v.extend(pts[1..].iter().map(|p| PathSeg::L { x: p[0], y: p[1] }));
v.push(PathSeg::Z);
v
}
fn covers(tris: &[[[f64; 2]; 3]], p: [f64; 2]) -> bool {
let s = |a: [f64; 2], b: [f64; 2]| (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]);
tris.iter().any(|t| {
let (d0, d1, d2) = (s(t[0], t[1]), s(t[1], t[2]), s(t[2], t[0]));
(d0 >= 0.0 && d1 >= 0.0 && d2 >= 0.0) || (d0 <= 0.0 && d1 <= 0.0 && d2 <= 0.0)
})
}
#[test]
fn concave_self_intersecting_and_holed_fills() {
// An L (concave): area 3, the notch stays empty.
let l = poly(&[[0.0, 0.0], [2.0, 0.0], [2.0, 1.0], [1.0, 1.0], [1.0, 2.0], [0.0, 2.0]]);
let t = PathSeg::fill_triangles(&l, 48, false);
assert!((area(&t) - 3.0).abs() < 1e-9, "{}", area(&t));
assert!(covers(&t, [0.5, 1.5]) && !covers(&t, [1.5, 1.5]));
// A five-pointed star drawn in one stroke: non-zero fills the centre, even-odd doesn't.
let star: Vec<[f64; 2]> = (0..5)
.map(|i| {
let a = (i * 2 % 5) as f64 * std::f64::consts::TAU / 5.0 - std::f64::consts::FRAC_PI_2;
[50.0 + 40.0 * a.cos(), 50.0 + 40.0 * a.sin()]
})
.collect();
let nz = PathSeg::fill_triangles(&poly(&star), 48, false);
let eo = PathSeg::fill_triangles(&poly(&star), 48, true);
assert!(covers(&nz, [50.0, 50.0]) && !covers(&eo, [50.0, 50.0]));
assert!(covers(&eo, [50.0, 15.0]), "a point of the star");
assert!(area(&nz) > area(&eo));
// A rectangle with a hole (an inner square the other way round).
let mut holed = poly(&[[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0]]);
holed.extend(poly(&[[3.0, 3.0], [3.0, 7.0], [7.0, 7.0], [7.0, 3.0]]));
let h = PathSeg::fill_triangles(&holed, 48, false);
assert!((area(&h) - 84.0).abs() < 1e-9 && !covers(&h, [5.0, 5.0]));
// rectPath + ellipsePath in one path; an unclosed subpath fills as if closed.
let shapes = vec![PathSeg::R { x: 0.0, y: 0.0, w: 4.0, h: 2.0 }, PathSeg::E { x: 10.0, y: 0.0, w: 20.0, h: 20.0 }];
let a = area(&PathSeg::fill_triangles(&shapes, 256, false));
assert!((a - 8.0 - std::f64::consts::PI * 100.0).abs() < 1.0, "{a}");
let open = vec![PathSeg::M { x: 0.0, y: 0.0 }, PathSeg::L { x: 4.0, y: 0.0 }, PathSeg::L { x: 0.0, y: 4.0 }];
assert!((area(&PathSeg::fill_triangles(&open, 48, false)) - 8.0).abs() < 1e-9);
}
}
+53
View File
@@ -0,0 +1,53 @@
//! M13.4: HEVC / AV1 output modules and the WebM codec / Opus options over the command API.
use effectcraft_project::render_queue::{Channels, CodecProfile, OpusApplication, OutputFormat, RateControlMode, VideoCodecOptions, WebmVideoCodec};
use serde_json::json;
use crate::Session;
fn session() -> Session {
let mut s = Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
s
}
#[test]
fn hevc_and_av1_output_module_options() {
let mut s = session();
let a = s
.execute(
"renderQueue.add",
json!({"format": "hevc", "profile": "main10", "level": "4.1", "rateControl": "quality", "quality": 85, "keyframeInterval": 30}),
)
.unwrap();
assert!(a["outputPath"].as_str().unwrap().ends_with(".mp4"), "{a}");
let om = &s.project.render_queue[0].output;
assert_eq!(om.format, OutputFormat::Hevc);
assert_eq!(om.codec, VideoCodecOptions { profile: CodecProfile::Main10, level: Some(41), rate_control: RateControlMode::Quality, quality: 85 });
assert_eq!(om.keyframe_interval, 30);
assert_eq!(a["output"]["codec"]["profile"], "Main10", "{a}");
let id = a["item"].clone();
s.execute("renderQueue.setOutputModule", json!({"item": id, "format": "av1", "level": null, "rateControl": "bitrate", "bitrate": 3000})).unwrap();
let om = &s.project.render_queue[0].output;
assert_eq!((om.format, om.codec.level, om.codec.rate_control, om.bitrate_kbps), (OutputFormat::Av1, None, RateControlMode::Bitrate, 3000));
assert!(s.execute("renderQueue.setOutputModule", json!({"item": id, "channels": "rgba"})).is_err(), "AV1 MP4 has no alpha");
assert!(s.execute("renderQueue.setOutputModule", json!({"item": id, "profile": "high"})).is_err());
assert!(s.execute("renderQueue.setOutputModule", json!({"item": id, "level": "0.5"})).is_err());
assert!(s.execute("renderQueue.setOutputModule", json!({"item": id, "rateControl": "cbr2"})).is_err());
// WebM: VP9 with alpha, then AV1 (alpha dropped) with voice-tuned Opus.
s.execute("renderQueue.setOutputModule", json!({"item": id, "format": "webm", "channels": "rgba"})).unwrap();
assert_eq!(s.project.render_queue[0].output.channels, Channels::Rgba);
s.execute("renderQueue.setOutputModule", json!({"item": id, "webmCodec": "av1", "audioBitrate": 24, "opusApplication": "voice"})).unwrap();
let om = &s.project.render_queue[0].output;
assert_eq!((om.webm_codec, om.channels, om.opus_bitrate_kbps, om.opus_application), (WebmVideoCodec::Av1, Channels::Rgb, 24, OpusApplication::Voip));
assert!(s.execute("renderQueue.setOutputModule", json!({"item": id, "webmCodec": "theora"})).is_err());
// The formats query lists the new formats and option values.
let f = s.execute("renderQueue.formats", json!({})).unwrap();
let ids: Vec<&str> = f["formats"].as_array().unwrap().iter().filter_map(|v| v["id"].as_str()).collect();
assert!(ids.contains(&"Hevc") && ids.contains(&"Av1"), "{ids:?}");
assert_eq!(f["codecProfiles"], json!(["Main", "Main 10"]));
assert!(f["hevcLevels"].as_array().unwrap().contains(&json!("4.1")));
assert_eq!(f["webmCodecs"], json!(["vp9", "av1"]));
}
+79 -2
View File
@@ -67,11 +67,15 @@ fn controls_are_listed_typed_and_editable() {
assert_eq!(l["controls"][1]["name"], "Opacity");
s.execute("essential.remove", json!({"control": opacity})).unwrap();
assert_eq!(s.execute("essential.list", json!({})).unwrap()["controls"].as_array().unwrap().len(), 3);
// Unsupported properties are refused; adding the same property twice adds nothing.
// Unsupported properties are refused; adding the same property twice adds a mirror (or
// nothing with `mirror: false`).
s.execute("layer.addMask", json!({"layer": solid})).unwrap();
assert!(s.execute("essential.addProperty", json!({"layer": solid, "path": "masks/#1/path"})).is_err());
let again = s.execute("essential.addProperty", json!({"layer": solid, "path": "effects/#1/color"})).unwrap();
let again = s.execute("essential.addProperty", json!({"layer": solid, "path": "effects/#1/color", "mirror": false})).unwrap();
assert_eq!(again["controls"], json!([]));
let again = s.execute("essential.addProperty", json!({"layer": solid, "path": "effects/#1/color"})).unwrap();
assert_eq!(again["mirrors"], again["controls"]);
s.execute("edit.undo", json!({})).unwrap();
// Dropdown Menu Control: its items are editable and it becomes a dropdown control.
s.execute("effect.apply", json!({"layer": solid, "effect": "Dropdown Menu Control"})).unwrap();
s.execute("effect.editDropdown", json!({"layer": solid, "items": ["Small", "Medium", "Large", "Huge"]})).unwrap();
@@ -141,6 +145,79 @@ fn master_properties_override_per_instance_push_and_revert() {
assert!(essential::group(&l).unwrap().children.iter().all(|n| n.name() != "Card Color"));
}
#[test]
fn mirrored_and_linked_properties() {
let (mut s, card, solid, ids) = card();
let opacity = ids["opacity"].as_u64().unwrap();
// A second solid whose opacity the Opacity control drives too.
let bg2 = s.execute("layer.newSolid", json!({"name": "BG2", "color": "#00ff00"})).unwrap()["layer"].as_u64().unwrap();
s.execute("essential.linkProperty", json!({"control": opacity, "layer": bg2, "path": "transform/opacity"})).unwrap();
// Not the same kind of property; already driven.
assert!(s.execute("essential.linkProperty", json!({"control": opacity, "layer": bg2, "path": "transform/position"})).is_err());
assert!(s.execute("essential.linkProperty", json!({"control": ids["color"], "layer": bg2, "path": "transform/opacity"})).is_err());
let opa = |s: &Session, l: u64| s.project.comp(card).unwrap().layer(LayerId(l)).unwrap().props.prop("transform/opacity").unwrap().value.as_f64();
// The link follows the main property, and the main property follows the link.
s.execute("prop.set", json!({"comp": card.0, "layer": solid, "path": "transform/opacity", "value": 40})).unwrap();
assert_eq!(opa(&s, bg2), 40.0);
s.execute("prop.set", json!({"comp": card.0, "layer": bg2, "path": "transform/opacity", "value": 70})).unwrap();
assert_eq!(opa(&s, solid), 70.0);
let l = s.execute("essential.list", json!({})).unwrap();
let c = l["controls"].as_array().unwrap().iter().find(|c| c["id"] == opacity).unwrap().clone();
assert_eq!(c["links"][0]["layer"], bg2);
assert_eq!(c["links"][0]["path"], "transform/opacity");
// Adding the Opacity again (into the Words group) mirrors it.
let m = s.execute("essential.addProperty", json!({"layer": solid, "path": "transform/opacity", "group": ids["group"], "name": "Fade"})).unwrap();
let mirror = m["mirrors"][0].as_u64().unwrap();
let l = s.execute("essential.list", json!({})).unwrap();
let mc = &l["controls"][2]["children"][1];
assert_eq!((mc["id"].as_u64(), mc["kind"].as_str(), mc["of"].as_u64(), mc["name"].as_str()), (Some(mirror), Some("mirror"), Some(opacity), Some("Fade")));
assert_eq!(mc["value"], json!(70.0));
// A mirror of the mirror shows the same master; the linked solid also counts as present.
let m2 = s.execute("essential.addMirror", json!({"control": mirror})).unwrap();
assert_eq!(m2["of"], opacity);
let again = s.execute("essential.addProperty", json!({"layer": bg2, "path": "transform/opacity"})).unwrap();
assert_eq!(again["mirrors"].as_array().unwrap().len(), 1);
s.execute("edit.undo", json!({})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
// Instances: setting the mirror sets the master (and both links) for that instance only.
s.execute("comp.new", json!({"name": "Main", "width": 64, "height": 64, "frameRate": 30, "duration": 2})).unwrap();
let main = s.active_comp_id().unwrap();
let a = s.execute("layer.addItem", json!({"item": card.0})).unwrap()["layer"].as_u64().unwrap();
let inst = s.execute("essential.instance", json!({"layer": a})).unwrap();
let find = |inst: &Value, id: u64| inst["controls"].as_array().unwrap().iter().find(|c| c["control"] == id).unwrap().clone();
assert_eq!(find(&inst, mirror)["kind"], "mirror");
s.execute("essential.set", json!({"layer": a, "control": mirror, "value": 20})).unwrap();
let inst = s.execute("essential.instance", json!({"layer": a})).unwrap();
assert_eq!((find(&inst, opacity)["value"].clone(), find(&inst, opacity)["overridden"].clone()), (json!(20.0), json!(true)));
assert_eq!((find(&inst, mirror)["value"].clone(), find(&inst, mirror)["overridden"].clone()), (json!(20.0), json!(true)));
// Rendered: both solids at 20 % (green BG2 on top of the red-filled solid).
let px = center(&s, main);
assert!((px[3] - (1.0 - 0.8 * 0.8)).abs() < 0.02, "{px:?}");
assert_eq!(opa(&s, solid), 70.0, "the source comp keeps its value");
// Setting the master updates the mirror.
s.execute("essential.set", json!({"layer": a, "control": opacity, "value": 55})).unwrap();
assert_eq!(find(&s.execute("essential.instance", json!({"layer": a})).unwrap(), mirror)["value"], json!(55.0));
// Reverting the mirror reverts the master too.
s.execute("essential.revert", json!({"layer": a, "control": mirror})).unwrap();
let inst = s.execute("essential.instance", json!({"layer": a})).unwrap();
assert_eq!((find(&inst, opacity)["overridden"].clone(), find(&inst, mirror)["value"].clone()), (json!(false), json!(70.0)));
// Push to Comp from a mirror writes the master and its links.
s.execute("essential.set", json!({"layer": a, "control": mirror, "value": 35})).unwrap();
s.execute("essential.pushToComp", json!({"layer": a, "control": mirror})).unwrap();
assert_eq!((opa(&s, solid), opa(&s, bg2)), (35.0, 35.0));
// Saved and loaded with the project.
let back = effectcraft_project::Project::from_json(&s.project.to_json()).unwrap();
assert_eq!(back.comp(card).unwrap().essential, s.project.comp(card).unwrap().essential);
// Unlink; removing the master removes its mirrors.
s.execute("essential.unlinkProperty", json!({"comp": card.0, "control": opacity, "layer": bg2, "path": "transform/opacity"})).unwrap();
s.execute("prop.set", json!({"comp": card.0, "layer": solid, "path": "transform/opacity", "value": 10})).unwrap();
assert_eq!(opa(&s, bg2), 35.0);
let r = s.execute("essential.remove", json!({"comp": card.0, "control": opacity})).unwrap();
assert_eq!(r["mirrors"], json!([mirror]));
let eg = s.project.comp(card).unwrap().essential.clone().unwrap();
assert!(eg.find(mirror).is_none() && essential::group(s.project.comp(main).unwrap().layer(LayerId(a)).unwrap()).is_some());
}
#[test]
fn template_export_import_round_trip_with_overrides() {
let dir = out_dir("ectemplate");
+12 -2
View File
@@ -16,10 +16,20 @@ fn font_and_scale_controls_override_per_instance() {
let t = s.execute("essential.addProperty", json!({"layer": text, "path": "text/sourceText"})).unwrap()["controls"][0].as_u64().unwrap();
let f = s.execute("essential.addProperty", json!({"layer": text, "path": "text/sourceText", "as": "font"})).unwrap()["controls"][0].as_u64().unwrap();
let sc = s.execute("essential.addProperty", json!({"layer": text, "path": "transform/scale", "as": "scale"})).unwrap()["controls"][0].as_u64().unwrap();
// Adding the same font control again is a no-op; opacity can't be a font.
// Adding the same font control again adds nothing with `mirror: false` (else a mirror of
// it); opacity can't be a font.
assert!(
s.execute("essential.addProperty", json!({"layer": text, "path": "text/sourceText", "as": "font"})).unwrap()["controls"].as_array().unwrap().is_empty()
s.execute("essential.addProperty", json!({"layer": text, "path": "text/sourceText", "as": "font", "mirror": false})).unwrap()["controls"]
.as_array()
.unwrap()
.is_empty()
);
let m = s.execute("essential.addProperty", json!({"layer": text, "path": "text/sourceText", "as": "font"})).unwrap();
assert_eq!(m["mirrors"].as_array().unwrap().len(), 1);
let ml = s.execute("essential.list", json!({})).unwrap();
let mirror = ml["controls"].as_array().unwrap().iter().find(|c| c["kind"] == "mirror").unwrap().clone();
assert_eq!((mirror["of"].as_u64(), mirror["type"].as_str()), (Some(f), Some("font")));
s.execute("edit.undo", json!({})).unwrap();
assert!(s.execute("essential.addProperty", json!({"layer": text, "path": "transform/opacity", "as": "font"})).is_err());
assert_eq!(s.execute("essential.canAdd", json!({"layer": text, "path": "transform/opacity", "as": "font"})).unwrap()["ok"], false);
assert_eq!(s.execute("essential.canAdd", json!({"layer": text, "path": "transform/scale", "as": "scale"})).unwrap()["type"], "scale");
+19
View File
@@ -314,13 +314,32 @@ fn variable_font_axes_animator() {
let l = comp.layer(LayerId(t)).unwrap();
effectcraft_render::text::glyph_paths(&ctx, l).iter().map(|(p, _)| effectcraft_text::kurbo::Shape::area(p).abs()).sum::<f64>()
};
// The distance between the two H's left edges: the H advance.
let gap = |s: &Session| {
let cid = s.active_comp_id().unwrap();
let comp = s.project.comp(cid).unwrap();
let ctx = effectcraft_render::EvalCtx::new(&s.project, cid, comp, s.time());
let l = comp.layer(LayerId(t)).unwrap();
let x0: Vec<f64> = effectcraft_render::text::glyph_paths(&ctx, l).iter().map(|(p, _)| effectcraft_text::kurbo::Shape::bounding_box(p).x0).collect();
x0[1] - x0[0]
};
let before = area(&s);
let gap_before = gap(&s);
let l = s.active_comp().unwrap().layer(LayerId(t)).unwrap().clone();
let pg = l.props.find_group(anim).unwrap().sub("properties").unwrap().props().next().unwrap().uid;
let range = (axis.max - axis.min) as f64;
s.execute("prop.set", json!({"layer": t, "prop": pg, "value": range})).unwrap();
let after = area(&s);
assert!((after - before).abs() > 1.0, "{} axis moved the outline: {before} → {after}", axis.tag);
// Advances follow the axis too (the text is re-spaced, not only redrawn).
let a = axes.iter().find(|a| a.tag == tag).unwrap();
let f = effectcraft_text::fonts::face(face);
let gid = f.glyph('H').unwrap();
let upem = f.units_per_em() as f64;
let units = |v: f32| effectcraft_text::variable::advance_units_at(face, gid, &[(a.tag.clone(), v)]).unwrap() as f64;
let want = (units((a.default + range as f32).min(a.max)) - units(a.default)) * 60.0 / upem;
let moved = gap(&s) - gap_before;
assert!((moved - want).abs() < 0.5, "{} axis: advance change {moved}, expected {want}", a.tag);
s.execute("edit.undo", json!({})).unwrap();
assert!((area(&s) - before).abs() < 1e-6);
let _ = info;
+127 -1
View File
@@ -162,7 +162,8 @@ fn clipped_items(ids: &mut Ids, s: &effectcraft_svg::Shape, m: Affine, clips: &[
/// Clipping groups (PDF / Illustrator clipping masks): shapes inside them are intersected with
/// the clip paths through Merge Paths ▸ Intersect (see [`clipped_items`]). Clips enclosing the
/// whole document are layer masks instead ([`vector_clip_masks`], used by
/// [`shapes_from_vector`]). Images and soft masks are not converted.
/// [`shapes_from_vector`]). Images are skipped (Layer ▸ Create makes them footage layers, see
/// [`split_at_images`]); soft masks are not converted.
pub fn svg_contents(ids: &mut Ids, doc: &Doc) -> Vec<PropGroup> {
fn walk(ids: &mut Ids, nodes: &[Node], m: Affine, clips: &[BezPath]) -> Vec<PropGroup> {
let mut out = vec![];
@@ -340,6 +341,131 @@ fn like_source(dst: &mut Layer, src: &Layer) {
dst.switches.three_d = src.switches.three_d;
}
/// A raster image of a vector document (Create Shapes from Vector Layer makes it a footage
/// layer: shape layers have no images).
pub struct VectorImage {
pub name: String,
pub width: u32,
pub height: u32,
/// Straight RGBA8.
pub rgba: std::sync::Arc<Vec<u8>>,
/// Image pixels → document pixels.
pub transform: Affine,
pub opacity: f64,
/// Inside a clipping group or under a soft mask (not carried over).
pub clipped: bool,
}
/// The document's images, bottom first, and how many soft-masked groups it has.
pub fn vector_images(doc: &Doc) -> (Vec<VectorImage>, usize) {
fn walk(g: &effectcraft_svg::Group, m: Affine, opacity: f64, clipped: bool, out: &mut Vec<VectorImage>, masks: &mut usize) {
let m = m * g.transform;
let opacity = opacity * g.opacity;
let clipped = clipped || !g.clip.is_empty() || g.mask.is_some();
if g.mask.is_some() {
*masks += 1;
}
for c in &g.children {
match c {
Node::Group(sub) => walk(sub, m, opacity, clipped, out, masks),
Node::Image(im) => out.push(VectorImage {
name: im.name.clone(),
width: im.width,
height: im.height,
rgba: im.rgba.clone(),
transform: m * im.transform,
opacity: opacity * im.opacity,
clipped,
}),
Node::Shape(_) => {}
}
}
}
let (_, doc) = vector_clip_masks(doc);
let mut out = vec![];
let mut masks = 0;
walk(&doc.root, Affine::IDENTITY, 1.0, false, &mut out, &mut masks);
(out, masks)
}
/// The document split at its images (paint order): segment `k` keeps the shapes drawn between
/// image `k − 1` and image `k` (groups, clips and blend modes kept, images dropped), so shape
/// layers and image footage layers can stack in the document's order. One more segment than
/// images.
pub fn split_at_images(doc: &Doc) -> Vec<Doc> {
fn count(g: &effectcraft_svg::Group) -> usize {
g.children
.iter()
.map(|c| match c {
Node::Group(s) => count(s),
Node::Image(_) => 1,
Node::Shape(_) => 0,
})
.sum()
}
/// Keep the shapes between images `seg − 1` and `seg`; `seen` counts images passed.
fn prune(g: &effectcraft_svg::Group, seg: usize, seen: &mut usize) -> effectcraft_svg::Group {
let mut out = g.clone();
out.children = vec![];
for c in &g.children {
match c {
Node::Image(_) => *seen += 1,
Node::Shape(_) => {
if *seen == seg {
out.children.push(c.clone());
}
}
Node::Group(s) => {
let p = prune(s, seg, seen);
if !p.children.is_empty() {
out.children.push(Node::Group(p));
}
}
}
}
out
}
let n = count(&doc.root);
(0..=n)
.map(|seg| {
let mut d = doc.clone();
d.root = prune(&doc.root, seg, &mut 0);
d
})
.collect()
}
/// A footage layer for an image of a vector document, parented to `parent` (the shape layer,
/// whose layer space is document pixels) and placed by the image's transform (anchor at its
/// top-left corner; position, rotation and scale from the matrix). Returns a note when the
/// placement has a skew, which layer transforms cannot express.
pub fn image_layer(proj: &mut Project, comp: &Comp, item: ItemId, img: &VectorImage, parent: &Layer) -> (Layer, Option<String>) {
let mut l = build::layer(proj, comp, &img.name, LayerSource::Footage { item }, (img.width, img.height), None);
let c = img.transform.as_coeffs();
let theta = c[1].atan2(c[0]);
let (sn, cs) = theta.sin_cos();
let sx = (c[0] * c[0] + c[1] * c[1]).sqrt();
let sy = -c[2] * sn + c[3] * cs;
let skew = c[2] * cs + c[3] * sn;
let set = |l: &mut Layer, path: &str, v: Value| {
if let Some(p) = l.props.prop_mut(path) {
p.value = v;
}
};
set(&mut l, "transform/anchor", Value::Vec3([0.0, 0.0, 0.0]));
set(&mut l, "transform/position", Value::Vec3([c[4], c[5], 0.0]));
set(&mut l, "transform/scale", Value::Vec3([sx * 100.0, sy * 100.0, 100.0]));
set(&mut l, "transform/rotation", Value::Scalar(theta.to_degrees()));
set(&mut l, "transform/opacity", Value::Scalar((img.opacity * 100.0).clamp(0.0, 100.0)));
l.start_time = parent.start_time;
l.in_point = parent.in_point;
l.out_point = parent.out_point;
l.stretch = parent.stretch;
l.parent = Some(parent.id);
let note = (skew.abs() > 1e-3 * sy.abs().max(1e-9)).then(|| format!("{}: skewed image placed without its skew", img.name));
(l, note)
}
/// Layer ▸ Create ▸ Create Shapes from Vector Layer: `doc` is the SVG shown by `src`. A clip
/// enclosing the whole document becomes the layer's masks (Add, then Intersect); nested clips
/// are kept with Merge Paths (see [`svg_contents`]).