Merge pull request #2 from storytold/puppet-rigging
Puppet tools: pin editing, rigging to nulls, follow-through; expression runtime fix
This commit is contained in:
@@ -56,6 +56,10 @@ fn select_all(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
if s.state.text_edit.is_some() {
|
||||
return s.execute("text.setSelection", json!({"select": "all"}));
|
||||
}
|
||||
// A puppet pin selected: every pin of that kind.
|
||||
if let Some(r) = super::puppet::select_all_of_kind(s) {
|
||||
return Ok(r);
|
||||
}
|
||||
if let Some(c) = s.active_comp() {
|
||||
s.state.selected_layers = c.layers.iter().map(|l| l.id).collect();
|
||||
}
|
||||
@@ -120,6 +124,10 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !s.state.selected_vertices.is_empty() && p.get("layers").is_none() {
|
||||
return s.execute("mask.deleteVertices", json!({}));
|
||||
}
|
||||
// Puppet pins selected → delete the pins (not their layer).
|
||||
if p.get("layers").is_none() && !super::puppet::selected_pins(s).is_empty() {
|
||||
return s.execute("puppet.removePin", json!({}));
|
||||
}
|
||||
// Effects selected → remove them.
|
||||
if p.get("layers").is_none() && !super::effect::selected_effects(s).is_empty() {
|
||||
return s.execute("effect.remove", json!({}));
|
||||
|
||||
@@ -12,10 +12,17 @@
|
||||
//!
|
||||
//! The path is `path`/`prop` of `layer`, else the selected path property, else the layer's first
|
||||
//! mask or shape path. Each command is one undo step.
|
||||
//!
|
||||
//! **Puppet pins** rig the same way (controllers drive the pins, or props ride along with a pin):
|
||||
//! with `pins`, selected pins, or a layer that has Puppet pins but no path, Points Follow Nulls
|
||||
//! makes a null per Position / Advanced pin and gives the pin's Position an expression following
|
||||
//! it (`fromComp` of the null's anchor, so parented nulls rig limbs), and Nulls Follow Points makes
|
||||
//! nulls whose Position follows each pin (`toComp` of its Position).
|
||||
|
||||
use effectcraft_effects::puppet::PinKind;
|
||||
use effectcraft_geom::vec2;
|
||||
use effectcraft_keyframe::Value as KV;
|
||||
use effectcraft_project::{ItemId, LayerId, Uid};
|
||||
use effectcraft_project::{Comp, ItemId, Layer, LayerId, Uid};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, b_p, bad, comp_id, has_layers};
|
||||
@@ -85,13 +92,80 @@ fn info(s: &Session, cid: ItemId, lid: LayerId, uid: Uid, cmd: &str) -> Result<P
|
||||
[q.x, q.y]
|
||||
})
|
||||
.collect();
|
||||
// Seen from another layer (the nulls).
|
||||
let reference = from_other_layer(comp, layer, uid).ok_or_else(|| bad(cmd, "can't reference that path"))?;
|
||||
let prop_name = layer.props.name_path_of(uid).and_then(|n| n.split('/').rev().nth(1).map(str::to_string)).unwrap_or_else(|| pr.name.clone());
|
||||
Ok(PathInfo { comp_pts, path, reference, layer_name: layer.name.clone(), prop_name, span: (layer.in_point.seconds(), layer.out_point.seconds()) })
|
||||
}
|
||||
|
||||
/// An expression reference to `uid` of `layer` as another layer (the nulls) sees it.
|
||||
fn from_other_layer(comp: &Comp, layer: &Layer, uid: Uid) -> Option<String> {
|
||||
let mut other = layer.clone();
|
||||
other.id = LayerId(u64::MAX);
|
||||
other.name = "\u{0}".into();
|
||||
let reference = super::link::reference(comp, &other, layer, uid, true).ok_or_else(|| bad(cmd, "can't reference that path"))?;
|
||||
let prop_name = layer.props.name_path_of(uid).and_then(|n| n.split('/').rev().nth(1).map(str::to_string)).unwrap_or_else(|| pr.name.clone());
|
||||
Ok(PathInfo { comp_pts, path, reference, layer_name: layer.name.clone(), prop_name, span: (layer.in_point.seconds(), layer.out_point.seconds()) })
|
||||
super::link::reference(comp, &other, layer, uid, true)
|
||||
}
|
||||
|
||||
/// A Puppet pin to rig: its layer, name, Position property, where it is now (comp space) and the
|
||||
/// reference to its Position from another layer.
|
||||
struct PinRig {
|
||||
layer: LayerId,
|
||||
layer_name: String,
|
||||
name: String,
|
||||
position: Uid,
|
||||
comp_pt: [f64; 2],
|
||||
reference: String,
|
||||
}
|
||||
|
||||
/// The pins to rig, when the command targets Puppet pins: `pins` / `pin`, else the selected pins,
|
||||
/// else (no path given) every pin of a layer that has pins but no mask or shape path. Bend,
|
||||
/// Starch and Overlap pins have no Position and are skipped.
|
||||
fn pin_targets(s: &Session, p: &Value, cmd: &str) -> Result<Option<(ItemId, Vec<PinRig>)>> {
|
||||
if p.get("path").is_some() || p.get("prop").is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
let named = p.get("pins").is_some() || p.get("pin").is_some();
|
||||
let pins = if named || !super::puppet::selected_pins(s).is_empty() {
|
||||
super::puppet::pins_p(s, p, cmd)?
|
||||
} else {
|
||||
if target(s, p, cmd).is_ok() {
|
||||
return Ok(None);
|
||||
}
|
||||
let cid = comp_id(s, p)?;
|
||||
let lid = match p.get("layer") {
|
||||
Some(_) => super::layer_p(s, p, cmd)?.1,
|
||||
None => match s.state.selected_layers.first() {
|
||||
Some(l) => *l,
|
||||
None => return Ok(None),
|
||||
},
|
||||
};
|
||||
let all: Vec<_> =
|
||||
s.project.comp(cid).and_then(|c| c.layer(lid)).map(|l| super::puppet::layer_pins(l).map(|g| (cid, lid, g.uid)).collect()).unwrap_or_default();
|
||||
if all.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
all
|
||||
};
|
||||
let cid = pins.first().map(|x| x.0).ok_or_else(|| bad(cmd, "no puppet pins"))?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let ctx =
|
||||
effectcraft_render::EvalCtx { project: &s.project, comp_id: cid, comp, time: s.time(), expr: s.expr.as_deref(), footage: Some(s.footage.as_ref()) };
|
||||
let mut out = vec![];
|
||||
for (_, lid, uid) in pins {
|
||||
let Some(layer) = comp.layer(lid) else { continue };
|
||||
let Some(g) = layer.props.find_group(uid) else { continue };
|
||||
if !PinKind::from_index(g.get("kind").map(|k| k.value.as_enum()).unwrap_or(0)).moves() {
|
||||
continue;
|
||||
}
|
||||
let Some(pos) = g.get("position") else { continue };
|
||||
let v = ctx.value(layer, pos).as_vec2();
|
||||
let q = ctx.layer_to_comp(layer).0.apply(vec2(v[0], v[1]));
|
||||
let reference = from_other_layer(comp, layer, pos.uid).ok_or_else(|| bad(cmd, "can't reference that pin"))?;
|
||||
out.push(PinRig { layer: lid, layer_name: layer.name.clone(), name: g.name.clone(), position: pos.uid, comp_pt: [q.x, q.y], reference });
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err(bad(cmd, "no Position or Advanced puppet pins to rig (Bend, Starch and Overlap pins have no Position)"));
|
||||
}
|
||||
Ok(Some((cid, out)))
|
||||
}
|
||||
|
||||
/// A new null at `at` (comp space) named `name`, made unique in the comp (expressions find
|
||||
@@ -113,6 +187,19 @@ fn new_null(s: &mut Session, cid: ItemId, name: &str, at: [f64; 2]) -> Result<(u
|
||||
|
||||
fn nulls_follow_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "paths.nullsFollowPoints";
|
||||
if let Some((cid, pins)) = pin_targets(s, p, C)? {
|
||||
let nulls = super::app_more::grouped(s, "Nulls Follow Points", |s| {
|
||||
let mut out = vec![];
|
||||
for pin in &pins {
|
||||
let (id, _) = new_null(s, cid, &format!("{}: {}", pin.layer_name, pin.name), pin.comp_pt)?;
|
||||
let e = format!("var src = thisComp.layer({});\nvar p = src.toComp({});\n[p[0], p[1]]", quote(&pin.layer_name), pin.reference);
|
||||
s.execute("prop.setExpression", json!({"comp": cid.0, "layer": id, "path": "transform/position", "expression": e}))?;
|
||||
out.push(id);
|
||||
}
|
||||
Ok(out)
|
||||
})?;
|
||||
return Ok(json!({"nulls": nulls, "pins": pins.iter().map(|p| p.position).collect::<Vec<_>>()}));
|
||||
}
|
||||
let (cid, lid, uid) = target(s, p, C)?;
|
||||
let pi = info(s, cid, lid, uid, C)?;
|
||||
let nulls = super::app_more::grouped(s, "Nulls Follow Points", |s| {
|
||||
@@ -130,6 +217,19 @@ fn nulls_follow_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn points_follow_nulls(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "paths.pointsFollowNulls";
|
||||
if let Some((cid, pins)) = pin_targets(s, p, C)? {
|
||||
let nulls = super::app_more::grouped(s, "Points Follow Nulls", |s| {
|
||||
let mut out = vec![];
|
||||
for pin in &pins {
|
||||
let (id, name) = new_null(s, cid, &format!("{}: {}", pin.layer_name, pin.name), pin.comp_pt)?;
|
||||
let e = format!("var n = thisComp.layer({});\nvar q = fromComp(n.toComp(n.transform.anchorPoint));\n[q[0], q[1]]", quote(&name));
|
||||
s.execute("prop.setExpression", json!({"comp": cid.0, "layer": pin.layer.0, "prop": pin.position, "expression": e}))?;
|
||||
out.push(id);
|
||||
}
|
||||
Ok(out)
|
||||
})?;
|
||||
return Ok(json!({"nulls": nulls, "pins": pins.iter().map(|p| p.position).collect::<Vec<_>>()}));
|
||||
}
|
||||
let (cid, lid, uid) = target(s, p, C)?;
|
||||
let pi = info(s, cid, lid, uid, C)?;
|
||||
let nulls = super::app_more::grouped(s, "Points Follow Nulls", |s| {
|
||||
@@ -191,7 +291,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Points Follow Nulls",
|
||||
[],
|
||||
None,
|
||||
"{layer?, path?|prop?} → a null per vertex; the path follows them (expression)",
|
||||
"{layer?, path?|prop?, pins?: [uid | name…]} → a null per vertex (or Position / Advanced puppet pin); the path (pins) follow them (expressions)",
|
||||
has_layers,
|
||||
points_follow_nulls
|
||||
),
|
||||
@@ -200,7 +300,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Nulls Follow Points",
|
||||
[],
|
||||
None,
|
||||
"{layer?, path?|prop?} → a null per vertex following it (Position expressions)",
|
||||
"{layer?, path?|prop?, pins?: [uid | name…]} → a null per vertex (or puppet pin) following it (Position expressions)",
|
||||
has_layers,
|
||||
nulls_follow_points
|
||||
),
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
//! Puppet tools: pins on the layer's Puppet effect (Position, Advanced, Bend, Starch and
|
||||
//! Overlap pins), mesh options, and a query of the current mesh for overlays and agents.
|
||||
//!
|
||||
//! Pins are selected like properties (`puppet.selectPins`; Edit ▸ Clear / Delete removes the
|
||||
//! selected pins, not their layer). Follow-Through (`puppet.follow`) makes pins trail a leader pin
|
||||
//! with a delay, for hair, cloth and overlapping action.
|
||||
//!
|
||||
//! Pin positions are layer space. A new pin is attached to the mesh under it: the click is
|
||||
//! mapped back through the current deformation to the rest mesh (its hidden rest position), and
|
||||
//! Position / Advanced pins get a Position keyframe at the current time, as in After Effects.
|
||||
@@ -9,7 +13,7 @@ use effectcraft_effects::puppet::{self, MeshOpts, PinKind};
|
||||
use effectcraft_effects::{Buf, Params};
|
||||
use effectcraft_keyframe::{Keyframe, Value as KV};
|
||||
use effectcraft_project::build::Ids;
|
||||
use effectcraft_project::{ItemId, LayerId, Node, PropGroup, Uid};
|
||||
use effectcraft_project::{ItemId, Layer, LayerId, Node, PropGroup, Uid};
|
||||
use effectcraft_render::{EvalCtx, RenderOpts, Renderer};
|
||||
use effectcraft_time::Tick;
|
||||
use serde_json::{Value, json};
|
||||
@@ -162,25 +166,102 @@ fn add_pin(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"effect": fx, "mesh": mesh, "pin": pin, "rest": [target.map(|x| x.1).unwrap_or(at)[0], target.map(|x| x.1).unwrap_or(at)[1]]}))
|
||||
}
|
||||
|
||||
/// The pin groups of a layer's Puppet effects, in stack order.
|
||||
pub(crate) fn layer_pins(l: &Layer) -> impl Iterator<Item = &PropGroup> {
|
||||
l.effects().into_iter().flat_map(|fx| fx.groups().filter(|g| puppet::is_puppet(g))).flat_map(puppet::meshes).flat_map(puppet::pins)
|
||||
}
|
||||
|
||||
/// Selected puppet pins of the active comp: (layer, pin uid).
|
||||
pub(crate) fn selected_pins(s: &Session) -> Vec<(LayerId, Uid)> {
|
||||
let Some(c) = s.active_comp() else { return vec![] };
|
||||
s.state.selected_props.iter().filter(|(l, u)| c.layer(*l).is_some_and(|l| layer_pins(l).any(|g| g.uid == *u))).copied().collect()
|
||||
}
|
||||
|
||||
/// Edit ▸ Select All with puppet pins selected: every pin of the selected pins' kinds on their
|
||||
/// layers. `None` when no pin is selected (Select All then selects layers).
|
||||
pub(crate) fn select_all_of_kind(s: &mut Session) -> Option<Value> {
|
||||
let sel = selected_pins(s);
|
||||
let comp = s.active_comp()?;
|
||||
let kind = |g: &PropGroup| PinKind::from_index(g.get("kind").map(|k| k.value.as_enum()).unwrap_or(0));
|
||||
let mut kinds = vec![];
|
||||
for (l, u) in &sel {
|
||||
if let Some(g) = comp.layer(*l).and_then(|l| l.props.find_group(*u)) {
|
||||
kinds.push((*l, kind(g)));
|
||||
}
|
||||
}
|
||||
if kinds.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let all: Vec<(LayerId, Uid)> =
|
||||
comp.layers.iter().flat_map(|l| layer_pins(l).filter(|g| kinds.contains(&(l.id, kind(g)))).map(|g| (l.id, g.uid)).collect::<Vec<_>>()).collect();
|
||||
s.state.selected_props = all.clone();
|
||||
Some(json!({ "pins": all.iter().map(|(_, u)| *u).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
/// Find a pin group (uid or name) in the layer's Puppet effects.
|
||||
fn pin_uid(s: &Session, cid: ItemId, lid: LayerId, key: &Value, cmd: &str) -> Result<Uid> {
|
||||
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?;
|
||||
let fx = l.effects().ok_or_else(|| bad(cmd, "no effects"))?;
|
||||
for g in fx.groups().filter(|g| puppet::is_puppet(g)) {
|
||||
for m in puppet::meshes(g) {
|
||||
for pin in puppet::pins(m) {
|
||||
let hit = match key {
|
||||
Value::Number(n) => n.as_u64() == Some(pin.uid),
|
||||
Value::String(name) => &pin.name == name,
|
||||
_ => false,
|
||||
};
|
||||
if hit {
|
||||
return Ok(pin.uid);
|
||||
}
|
||||
let hit = |pin: &&PropGroup| match key {
|
||||
Value::Number(n) => n.as_u64() == Some(pin.uid),
|
||||
Value::String(name) => &pin.name == name,
|
||||
_ => false,
|
||||
};
|
||||
layer_pins(l).find(hit).map(|g| g.uid).ok_or_else(|| bad(cmd, format!("no puppet pin {key}")))
|
||||
}
|
||||
|
||||
/// Pins named by `pin` or `pins` (uids or names) on `layer`, else the selected pins (of `layer`
|
||||
/// when given): (comp, layer, pin uid).
|
||||
pub(crate) fn pins_p(s: &Session, p: &Value, cmd: &str) -> Result<Vec<(ItemId, LayerId, Uid)>> {
|
||||
let keys: Vec<Value> = match (p.get("pin"), p.get("pins")) {
|
||||
(Some(k), _) => vec![k.clone()],
|
||||
(None, Some(Value::Array(a))) => a.clone(),
|
||||
(None, Some(_)) => return Err(bad(cmd, "`pins` must be an array of pin uids or names")),
|
||||
(None, None) => vec![],
|
||||
};
|
||||
if !keys.is_empty() {
|
||||
let (cid, lid) = layer_p(s, p, cmd)?;
|
||||
return keys.iter().map(|k| pin_uid(s, cid, lid, k, cmd).map(|u| (cid, lid, u))).collect();
|
||||
}
|
||||
let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
|
||||
let only = match p.get("layer") {
|
||||
Some(_) => Some(layer_p(s, p, cmd)?.1),
|
||||
None => None,
|
||||
};
|
||||
let sel: Vec<_> = selected_pins(s).into_iter().filter(|(l, _)| only.is_none_or(|o| o == *l)).map(|(l, u)| (cid, l, u)).collect();
|
||||
if sel.is_empty() {
|
||||
return Err(bad(cmd, "missing `pin` / `pins` (uids or names), and no puppet pins are selected"));
|
||||
}
|
||||
Ok(sel)
|
||||
}
|
||||
|
||||
/// Select pins (the viewer's click / Shift-click on a pin). Plain: only these pins; `add`: add
|
||||
/// them; `toggle`: flip each. An empty `pins` deselects every pin.
|
||||
fn select_pins(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "puppet.selectPins";
|
||||
let want = match p.get("pins") {
|
||||
Some(Value::Array(a)) if a.is_empty() => vec![],
|
||||
_ => pins_p(s, p, cmd)?,
|
||||
};
|
||||
let (add, toggle) = (super::b_p(p, "add").unwrap_or(false), super::b_p(p, "toggle").unwrap_or(false));
|
||||
let st = &mut s.state;
|
||||
if !add && !toggle {
|
||||
st.selected_props.clear();
|
||||
st.selected_keys.clear();
|
||||
}
|
||||
for (_, l, u) in want {
|
||||
let at = st.selected_props.iter().position(|x| *x == (l, u));
|
||||
match at {
|
||||
Some(i) if toggle => {
|
||||
st.selected_props.remove(i);
|
||||
}
|
||||
Some(_) => {}
|
||||
None => st.selected_props.push((l, u)),
|
||||
}
|
||||
if !st.selected_layers.contains(&l) {
|
||||
st.selected_layers.push(l);
|
||||
}
|
||||
}
|
||||
Err(bad(cmd, format!("no puppet pin {key}")))
|
||||
Ok(json!({ "pins": selected_pins(s).iter().map(|(_, u)| *u).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
fn with_pin<T>(s: &mut Session, p: &Value, cmd: &str, label: &str, f: impl FnOnce(&mut PropGroup, Tick) -> Result<T>) -> Result<T> {
|
||||
@@ -237,19 +318,19 @@ fn set_pin(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn remove_pin(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "puppet.removePin";
|
||||
let (cid, lid) = layer_p(s, p, cmd)?;
|
||||
let key = p.get("pin").cloned().ok_or_else(|| bad(cmd, "missing `pin` (uid or name)"))?;
|
||||
let uid = pin_uid(s, cid, lid, &key, cmd)?;
|
||||
s.edit("Delete Puppet Pin", None, |proj, st| {
|
||||
let l = layer_mut(proj, cid, lid)?;
|
||||
if let Some(parent) = l.props.parent_of_mut(uid) {
|
||||
parent.children.retain(|c| c.uid() != uid);
|
||||
let pins = pins_p(s, p, "puppet.removePin")?;
|
||||
let label = if pins.len() == 1 { "Delete Puppet Pin" } else { "Delete Puppet Pins" };
|
||||
s.edit(label, None, |proj, st| {
|
||||
for (cid, lid, uid) in &pins {
|
||||
let l = layer_mut(proj, *cid, *lid)?;
|
||||
if let Some(parent) = l.props.parent_of_mut(*uid) {
|
||||
parent.children.retain(|c| c.uid() != *uid);
|
||||
}
|
||||
st.selected_props.retain(|(_, u)| u != uid);
|
||||
}
|
||||
st.selected_props.retain(|(_, u)| *u != uid);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
Ok(json!({ "removed": pins.len() }))
|
||||
}
|
||||
|
||||
fn mesh_opts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -341,6 +422,43 @@ fn record_pin(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let key = p.get("pin").cloned().ok_or_else(|| bad(cmd, "missing `pin` (uid or name)"))?;
|
||||
let uid = pin_uid(s, cid, lid, &key, cmd)?;
|
||||
let rec = samples(p, cmd)?;
|
||||
// Several selected pins dragged together (`pins`): each follows the drag's displacement from
|
||||
// where it is when recording begins; one undo step.
|
||||
if let Some(Value::Array(others)) = p.get("pins")
|
||||
&& !others.is_empty()
|
||||
{
|
||||
let start = match p.get("start").and_then(Value::as_f64) {
|
||||
Some(t) => Tick::from_seconds_f64(t),
|
||||
None => s.time_of(cid),
|
||||
};
|
||||
let lt = layer_time(s, cid, lid, start)?;
|
||||
let mut pins = vec![(uid, rec[0].1)];
|
||||
for k in others {
|
||||
let u = pin_uid(s, cid, lid, k, cmd)?;
|
||||
if pins.iter().any(|(x, _)| *x == u) {
|
||||
continue;
|
||||
}
|
||||
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?;
|
||||
let at = l.props.find_group(u).and_then(|g| g.get("position")).map(|pr| pr.value_at(lt).as_vec2());
|
||||
pins.push((u, at.ok_or_else(|| bad(cmd, "only Position and Advanced pins record motion"))?));
|
||||
}
|
||||
let o = rec[0].1;
|
||||
return super::app_more::grouped(s, "Record Puppet Pins", |s| {
|
||||
let mut last = Value::Null;
|
||||
for (u, base) in &pins {
|
||||
let moved: Vec<Value> = rec.iter().map(|(t, q)| json!([t, base[0] + q[0] - o[0], base[1] + q[1] - o[1]])).collect();
|
||||
let mut one = p.clone();
|
||||
if let Some(m) = one.as_object_mut() {
|
||||
m.remove("pins");
|
||||
m.insert("pin".into(), json!(u));
|
||||
m.insert("samples".into(), Value::Array(moved));
|
||||
}
|
||||
last = s.execute(cmd, one)?;
|
||||
}
|
||||
last["pins"] = json!(pins.iter().map(|(u, _)| *u).collect::<Vec<_>>());
|
||||
Ok(last)
|
||||
});
|
||||
}
|
||||
let opts = &s.state.puppet;
|
||||
let speed = f_p(p, "speed").unwrap_or(opts.record_speed).clamp(1.0, 10_000.0) / 100.0;
|
||||
// Smoothing 10 (the default) keeps the path within 1 layer pixel of the drag.
|
||||
@@ -406,6 +524,68 @@ fn record_pin(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"keys": n, "start": start.seconds(), "end": end.seconds(), "frames": nframes + 1}))
|
||||
}
|
||||
|
||||
/// Follow-Through (hair, cloth, tails, overlapping action): each follower pin trails the leader
|
||||
/// pin's motion by a delay, through an expression on its Position. The followers nearest the
|
||||
/// leader trail least; with `cascade` the k-th nearest trails k × `delay`, otherwise all trail by
|
||||
/// `delay`. `amount` (%) scales the motion they inherit; their own keyframes still add on top.
|
||||
/// The leader is `leader`, else the first selected pin; the followers are `pins`, else the other
|
||||
/// selected pins of the leader's layer. One undo step.
|
||||
fn follow(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "puppet.follow";
|
||||
let (cid, lid, leader, mut followers) = match p.get("leader") {
|
||||
Some(k) => {
|
||||
let (cid, lid) = layer_p(s, p, cmd)?;
|
||||
let leader = pin_uid(s, cid, lid, k, cmd)?;
|
||||
let rest: Vec<Uid> = pins_p(s, p, cmd)?.into_iter().filter(|(_, l, u)| *l == lid && *u != leader).map(|x| x.2).collect();
|
||||
(cid, lid, leader, rest)
|
||||
}
|
||||
None => {
|
||||
let sel = pins_p(s, p, cmd)?;
|
||||
let (cid, lid, leader) = sel[0];
|
||||
(cid, lid, leader, sel.iter().skip(1).filter(|(_, l, _)| *l == lid).map(|x| x.2).collect())
|
||||
}
|
||||
};
|
||||
followers.dedup();
|
||||
if followers.is_empty() {
|
||||
return Err(bad(cmd, "select the leader pin first, then the pins that follow it (or pass `leader` and `pins`)"));
|
||||
}
|
||||
let delay = f_p(p, "delay").unwrap_or(0.1).clamp(0.0, 10.0);
|
||||
let amount = f_p(p, "amount").unwrap_or(100.0) / 100.0;
|
||||
let cascade = super::b_p(p, "cascade").unwrap_or(true);
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let layer = comp.layer(lid).ok_or(EngineError::NoComp)?;
|
||||
// (Position uid, rest) of a pin that moves.
|
||||
let moving = |uid: Uid| -> Result<(Uid, [f64; 2], String)> {
|
||||
let g = layer.props.find_group(uid).ok_or_else(|| bad(cmd, "pin gone"))?;
|
||||
if !PinKind::from_index(g.get("kind").map(|k| k.value.as_enum()).unwrap_or(0)).moves() {
|
||||
return Err(bad(cmd, format!("`{}` has no Position (only Position and Advanced pins follow or lead)", g.name)));
|
||||
}
|
||||
let pos = g.get("position").ok_or_else(|| bad(cmd, "the pin has no Position"))?;
|
||||
Ok((pos.uid, g.get("rest").map(|r| r.value.as_vec2()).unwrap_or([0.0; 2]), g.name.clone()))
|
||||
};
|
||||
let (lead_pos, lead_rest, lead_name) = moving(leader)?;
|
||||
let reference = super::link::reference(comp, layer, layer, lead_pos, true).ok_or_else(|| bad(cmd, "can't reference the leader pin"))?;
|
||||
let mut rigs = followers.iter().map(|u| moving(*u).map(|(pos, rest, _)| (*u, pos, rest))).collect::<Result<Vec<_>>>()?;
|
||||
let dist = |r: [f64; 2]| (r[0] - lead_rest[0]).hypot(r[1] - lead_rest[1]);
|
||||
rigs.sort_by(|a, b| dist(a.2).total_cmp(&dist(b.2)));
|
||||
let out = super::app_more::grouped(s, "Follow-Through", |s| {
|
||||
let mut out = vec![];
|
||||
for (k, (pin, pos, _)) in rigs.iter().enumerate() {
|
||||
let d = if cascade { delay * (k + 1) as f64 } else { delay };
|
||||
let e = format!(
|
||||
"// Follow-Through: trails {} by {d} s\nvar lead = {reference};\nvalue + (lead.valueAtTime(time - {d}) - [{}, {}]) * {amount}",
|
||||
serde_json::to_string(&lead_name).unwrap_or_default(),
|
||||
lead_rest[0],
|
||||
lead_rest[1]
|
||||
);
|
||||
s.execute("prop.setExpression", json!({"comp": cid.0, "layer": lid.0, "prop": pos, "expression": e}))?;
|
||||
out.push(json!({"pin": pin, "delay": d}));
|
||||
}
|
||||
Ok(out)
|
||||
})?;
|
||||
Ok(json!({"leader": leader, "pins": out}))
|
||||
}
|
||||
|
||||
/// Record Options (the Puppet tool's Record Options… dialog): `speed`, `smoothing`,
|
||||
/// `useDraftDeformation`, `showMesh`. Returns the options.
|
||||
fn record_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -469,7 +649,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_comp,
|
||||
set_pin
|
||||
),
|
||||
cmd!("puppet.removePin", "Delete Puppet Pin", [], None, "{layer?, pin: uid | name}", has_comp, remove_pin),
|
||||
cmd!(
|
||||
"puppet.removePin",
|
||||
"Delete Puppet Pin",
|
||||
[],
|
||||
None,
|
||||
"{layer?, pin?: uid | name, pins?: [uid | name…]} (default: the selected pins)",
|
||||
has_comp,
|
||||
remove_pin
|
||||
),
|
||||
cmd!("puppet.selectPins", "Select Puppet Pins", [], None, "{layer?, pins: [uid | name…] ([] deselects), add?, toggle?}", has_comp, select_pins),
|
||||
cmd!(
|
||||
"puppet.mesh",
|
||||
"Puppet Mesh Options",
|
||||
@@ -485,10 +674,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Record Puppet Pin",
|
||||
[],
|
||||
None,
|
||||
"{layer?, pin: uid | name, samples: [[t, x, y]…] (t = seconds since the drag began, layer space), start? (s, default current time), speed? (%, Record Options), smoothing? (Record Options)}",
|
||||
"{layer?, pin: uid | name, samples: [[t, x, y]…] (t = seconds since the drag began, layer space), pins?: [uid | name…] (more pins that move by the same displacement), start? (s, default current time), speed? (%, Record Options), smoothing? (Record Options)}",
|
||||
has_comp,
|
||||
record_pin
|
||||
),
|
||||
cmd!(
|
||||
"puppet.follow",
|
||||
"Follow-Through...",
|
||||
[],
|
||||
None,
|
||||
"{layer?, leader?: uid | name (default: the first selected pin), pins?: [uid | name…] (default: the other selected pins), delay? (s, 0.1), amount? (%, 100), cascade? (true: the k-th nearest pin trails k × delay)}",
|
||||
has_comp,
|
||||
follow
|
||||
),
|
||||
cmd!(
|
||||
"puppet.recordOptions",
|
||||
"Record Options...",
|
||||
|
||||
@@ -216,6 +216,127 @@ fn puppet_pin_kinds_and_mesh_options() {
|
||||
assert_eq!(pin_count(&s, id), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn puppet_pins_select_and_delete_without_touching_the_layer() {
|
||||
let (mut s, id) = setup();
|
||||
let a = s.execute("puppet.addPin", json!({"layer": id, "position": [10, 30]})).unwrap()["pin"].clone();
|
||||
let b = s.execute("puppet.addPin", json!({"layer": id, "position": [90, 30]})).unwrap()["pin"].clone();
|
||||
s.execute("puppet.addPin", json!({"layer": id, "position": [50, 30]})).unwrap();
|
||||
// A new pin is selected: Delete removes it, and the layer stays.
|
||||
assert_eq!(s.execute("edit.clear", json!({})).unwrap(), json!({"removed": 1}));
|
||||
assert_eq!(pin_count(&s, id), 2);
|
||||
assert!(s.active_comp().unwrap().layer(effectcraft_project::LayerId(id)).is_some());
|
||||
// Click, Shift-click (toggle) and add by name.
|
||||
let sel = |s: &mut Session, q: Value| s.execute("puppet.selectPins", q).unwrap()["pins"].clone();
|
||||
assert_eq!(sel(&mut s, json!({"layer": id, "pins": [a, b]})), json!([a, b]));
|
||||
assert_eq!(sel(&mut s, json!({"layer": id, "pins": [b], "toggle": true})), json!([a]));
|
||||
assert_eq!(sel(&mut s, json!({"layer": id, "pins": ["Puppet Pin 2"], "add": true})), json!([a, b]));
|
||||
assert!(s.execute("puppet.selectPins", json!({"layer": id, "pins": ["Puppet Pin 9"]})).is_err());
|
||||
// Deleting both is one undo step.
|
||||
assert_eq!(s.execute("edit.clear", json!({})).unwrap(), json!({"removed": 2}));
|
||||
assert_eq!(pin_count(&s, id), 0);
|
||||
s.undo();
|
||||
assert_eq!(pin_count(&s, id), 2);
|
||||
// Nothing selected: removing needs a pin.
|
||||
assert_eq!(sel(&mut s, json!({"layer": id, "pins": []})), json!([]));
|
||||
assert!(s.execute("puppet.removePin", json!({"layer": id})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn puppet_select_all_takes_the_pin_kind_and_several_pins_record_together() {
|
||||
let (mut s, id) = setup();
|
||||
let a = s.execute("puppet.addPin", json!({"layer": id, "position": [10, 30]})).unwrap()["pin"].clone();
|
||||
let b = s.execute("puppet.addPin", json!({"layer": id, "position": [90, 30]})).unwrap()["pin"].clone();
|
||||
let st = s.execute("puppet.addPin", json!({"layer": id, "kind": "starch", "position": [50, 30]})).unwrap()["pin"].clone();
|
||||
// Ctrl+A with a Position pin selected: every Position pin, not the Starch pin.
|
||||
s.execute("puppet.selectPins", json!({"layer": id, "pins": [a]})).unwrap();
|
||||
assert_eq!(s.execute("edit.selectAll", json!({})).unwrap()["pins"], json!([a, b]));
|
||||
s.execute("puppet.selectPins", json!({"layer": id, "pins": [st]})).unwrap();
|
||||
assert_eq!(s.execute("edit.selectAll", json!({})).unwrap()["pins"], json!([st]));
|
||||
// Without pins selected, Select All selects layers as before.
|
||||
s.execute("puppet.selectPins", json!({"layer": id, "pins": []})).unwrap();
|
||||
assert_eq!(s.execute("edit.selectAll", json!({})).unwrap(), json!(1));
|
||||
// Recording a drag of pin A with B selected too: B moves by the same displacement.
|
||||
let steps = s.history.undo.len();
|
||||
let samples: Vec<Value> = [0.0, 0.25, 0.5].iter().map(|t| json!([t, 10.0, 30.0 + 40.0 * t])).collect();
|
||||
let r = s.execute("puppet.recordPin", json!({"layer": id, "pin": a, "pins": [b], "samples": samples, "smoothing": 0})).unwrap();
|
||||
assert_eq!(r["pins"], json!([a, b]));
|
||||
assert_eq!(s.history.undo.len(), steps + 1, "one undo step");
|
||||
let last = |s: &Session, pin: &Value| pin_keys(s, id, pin.as_u64().unwrap()).last().unwrap().1;
|
||||
assert_eq!(last(&s, &a), [10.0, 50.0]);
|
||||
assert_eq!(last(&s, &b), [90.0, 50.0]);
|
||||
// Starch pins don't record.
|
||||
assert!(s.execute("puppet.recordPin", json!({"layer": id, "pin": a, "pins": [st], "samples": samples})).is_err());
|
||||
}
|
||||
|
||||
fn expr_of(s: &Session, layer: u64, uid: u64) -> String {
|
||||
let l = layer_of(s, layer);
|
||||
l.props.find(uid).and_then(|p| p.expr.as_ref()).map(|e| e.text.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn layer_of(s: &Session, id: u64) -> effectcraft_project::Layer {
|
||||
s.active_comp().unwrap().layer(effectcraft_project::LayerId(id)).unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn puppet_pins_rig_to_nulls_both_ways() {
|
||||
let (mut s, id) = setup();
|
||||
s.execute("puppet.addPin", json!({"layer": id, "position": [10, 30]})).unwrap();
|
||||
s.execute("puppet.addPin", json!({"layer": id, "position": [90, 30]})).unwrap();
|
||||
let bend = s.execute("puppet.addPin", json!({"layer": id, "kind": "bend", "position": [50, 30]})).unwrap()["pin"].clone();
|
||||
// Only a Bend pin selected: nothing to rig.
|
||||
assert!(s.execute("paths.pointsFollowNulls", json!({})).is_err());
|
||||
// No pin selected and no path: every Position pin of the layer gets a null on it, and the
|
||||
// pin's Position follows the null; one undo step.
|
||||
s.execute("puppet.selectPins", json!({"layer": id, "pins": []})).unwrap();
|
||||
let steps = s.history.undo.len();
|
||||
let r = s.execute("paths.pointsFollowNulls", json!({"layer": id})).unwrap();
|
||||
assert_eq!(s.history.undo.len(), steps + 1);
|
||||
let nulls: Vec<u64> = r["nulls"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
|
||||
let pins: Vec<u64> = r["pins"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
|
||||
assert_eq!((nulls.len(), pins.len()), (2, 2));
|
||||
let solid = layer_of(&s, id).name;
|
||||
let null = layer_of(&s, nulls[0]);
|
||||
assert_eq!(null.name, format!("{solid}: Puppet Pin 1"));
|
||||
// Layer (10, 30) is comp (60, 50).
|
||||
assert_eq!(null.props.prop("transform/position").unwrap().value.components()[..2], [60.0, 50.0]);
|
||||
let e = expr_of(&s, id, pins[0]);
|
||||
assert!(e.contains(&format!("thisComp.layer(\"{solid}: Puppet Pin 1\")")) && e.contains("fromComp(n.toComp(n.transform.anchorPoint))"), "{e}");
|
||||
// Nulls Follow Points: a null riding on a pin, through the pin's Position.
|
||||
let r = s.execute("paths.nullsFollowPoints", json!({"layer": id, "pins": ["Puppet Pin 2"]})).unwrap();
|
||||
let rider = layer_of(&s, r["nulls"][0].as_u64().unwrap());
|
||||
let e = rider.props.prop("transform/position").unwrap().expr.as_ref().unwrap().text.clone();
|
||||
assert!(e.contains(&format!("thisComp.layer(\"{solid}\")")) && e.contains("(\"Puppet Pin 2\")(\"Position\")") && e.contains("toComp"), "{e}");
|
||||
assert!(s.execute("paths.nullsFollowPoints", json!({"layer": id, "pins": [bend]})).is_err());
|
||||
// Trace Path still needs a path.
|
||||
assert!(s.execute("paths.tracePath", json!({"layer": id})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn puppet_follow_through_trails_the_leader_by_cascading_delays() {
|
||||
let (mut s, id) = setup();
|
||||
let lead = s.execute("puppet.addPin", json!({"layer": id, "position": [10, 30]})).unwrap()["pin"].clone();
|
||||
let far = s.execute("puppet.addPin", json!({"layer": id, "position": [90, 30]})).unwrap()["pin"].clone();
|
||||
let near = s.execute("puppet.addPin", json!({"layer": id, "position": [50, 30]})).unwrap()["pin"].clone();
|
||||
let pos_uid = |s: &Session, pin: &Value| layer_of(s, id).props.find_group(pin.as_u64().unwrap()).unwrap().get("position").unwrap().uid;
|
||||
// Leader first, then the followers (in any order): nearer pins trail less.
|
||||
s.execute("puppet.selectPins", json!({"layer": id, "pins": [lead, far, near]})).unwrap();
|
||||
let steps = s.history.undo.len();
|
||||
let r = s.execute("puppet.follow", json!({"delay": 0.2})).unwrap();
|
||||
assert_eq!(s.history.undo.len(), steps + 1, "one undo step");
|
||||
assert_eq!(r["leader"], lead);
|
||||
assert_eq!(r["pins"], json!([{"pin": near, "delay": 0.2}, {"pin": far, "delay": 0.4}]));
|
||||
let e = expr_of(&s, id, pos_uid(&s, &far));
|
||||
assert!(e.contains("(\"Puppet Pin 1\")(\"Position\")") && e.contains("valueAtTime(time - 0.4)") && e.contains("- [10, 30]) * 1"), "{e}");
|
||||
// Without cascade every follower trails by the same delay; `amount` scales the motion.
|
||||
s.execute("puppet.follow", json!({"layer": id, "leader": "Puppet Pin 1", "pins": [far, near], "delay": 0.25, "amount": 50, "cascade": false})).unwrap();
|
||||
assert!(expr_of(&s, id, pos_uid(&s, &far)).contains("valueAtTime(time - 0.25)") && expr_of(&s, id, pos_uid(&s, &far)).contains("* 0.5"));
|
||||
// Errors: no followers, or a pin without a Position.
|
||||
assert!(s.execute("puppet.follow", json!({"layer": id, "leader": "Puppet Pin 1", "pins": [lead]})).is_err());
|
||||
let bend = s.execute("puppet.addPin", json!({"layer": id, "kind": "bend", "position": [30, 30]})).unwrap()["pin"].clone();
|
||||
assert!(s.execute("puppet.follow", json!({"layer": id, "leader": "Puppet Pin 1", "pins": [bend]})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_with_paint_and_puppet_round_trips() {
|
||||
let (mut s, id) = setup();
|
||||
|
||||
Reference in New Issue
Block a user