M13.1/M13.2: paint (Brush, Clone Stamp, Eraser) and puppet pins

Paint: non-destructive Paint effect with Brush/Clone/Eraser stroke groups
(Path, Stroke Options, Transform, Duration spans, Write On End keys),
dab rasterizer (diameter/angle/roundness/hardness/spacing/flow/opacity,
pressure dynamics, modes, channels), eraser modes, clone from layer/time,
cache keys include visible strokes. paint.stroke/options/brushPreset/
setCloneSource/removeStroke/presets. Layer panel with paint tools, Paint
and Brushes panels.

Puppet: Puppet effect with meshes and Position/Advanced/Bend/Starch/Overlap
pins; alpha contour -> expansion (exact EDT) -> simplified outline ->
Delaunay with constraint recovery; ARAP (Igarashi 2005) two-step solve with
CG; anti-aliased texture-mapped rendering with overlap depth. puppet.addPin/
movePin/setPin/removePin/mesh/info. Puppet tools in the viewer with mesh
overlay and header options.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-02 09:12:10 -04:00
co-authored by Claude Opus 5.5
parent 5273f1ba96
commit d6f6a10757
28 changed files with 5062 additions and 15 deletions
+4
View File
@@ -16,7 +16,9 @@ mod layer_menu;
mod layer_time;
mod link;
mod mask;
pub mod paint;
mod prop;
pub mod puppet;
mod query;
mod render_queue;
mod stubs;
@@ -102,6 +104,8 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(file_more::specs());
v.extend(comp_more::specs());
v.extend(frontend::specs());
v.extend(paint::specs());
v.extend(puppet::specs());
v.extend(stubs::specs());
v
})
+484
View File
@@ -0,0 +1,484 @@
//! Paint tools (Brush, Clone Stamp, Eraser) and the Paint / Brushes panel options.
//!
//! `paint.stroke` records one stroke into the layer's Paint effect (adding the effect when the
//! last effect in the stack isn't Paint, as After Effects does). Defaults come from the Paint
//! and Brushes panel options in [`PaintOptions`] (`paint.options`, `paint.brushPreset`).
use effectcraft_effects::paint::{self, BRUSH_PRESETS, CHANNELS, DURATIONS, ERASE_MODES, MODES, StrokeKind, StrokeSpec};
use effectcraft_keyframe::{Keyframe, Value as KV};
use effectcraft_project::build::Ids;
use effectcraft_project::{GroupKind, PropGroup, Uid};
use effectcraft_time::Tick;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::{CommandSpec, always, b_p, bad, f_p, has_comp, layer_mut, layer_p, str_p};
use crate::{EngineError, Result, Session, cmd};
/// Paint and Brushes panel state (serde: agents read and set it with `paint.options`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PaintOptions {
/// Foreground (paint) and background colours, straight RGBA 0–1.
pub color: [f64; 4],
pub background: [f64; 4],
/// Percent.
pub opacity: f64,
pub flow: f64,
/// Index into the paint mode list (`paint::MODES`).
pub mode: u32,
/// Index into RGBA / RGB / Alpha.
pub channels: u32,
/// Index into Constant / Write On / Single Frame / Custom.
pub duration: u32,
/// Custom duration in frames.
pub custom_frames: u32,
/// Index into Layer Source & Paint / Paint Only / Last Stroke Only.
pub erase: u32,
// Brushes panel.
pub diameter: f64,
pub angle: f64,
pub roundness: f64,
pub hardness: f64,
pub spacing: f64,
/// Selected preset tip (index into `paint::BRUSH_PRESETS`).
pub preset: Option<usize>,
/// Brush dynamics (pen pressure).
pub size_pressure: bool,
pub min_size: f64,
pub opacity_pressure: bool,
pub flow_pressure: bool,
// Clone options.
/// Clone preset slot (1–5).
pub clone_preset: u32,
/// Source layer (None = the layer being painted).
pub clone_source: Option<u64>,
/// Source point set with Alt/Option-click (layer space of the source layer).
pub clone_point: Option<[f64; 2]>,
/// Aligned: keep the source/destination offset between strokes.
pub aligned: bool,
/// Offset (source − destination) remembered by Aligned.
pub clone_offset: Option<[f64; 2]>,
pub lock_source_time: bool,
/// Source Time Shift in seconds (or the locked Source Time).
pub clone_time_shift: f64,
pub clone_time: f64,
/// Clone Source Overlay.
pub show_overlay: bool,
pub overlay_opacity: f64,
pub overlay_difference: bool,
}
impl Default for PaintOptions {
fn default() -> Self {
PaintOptions {
color: [1.0, 1.0, 1.0, 1.0],
background: [0.0, 0.0, 0.0, 1.0],
opacity: 100.0,
flow: 100.0,
mode: 0,
channels: 0,
duration: 0,
custom_frames: 1,
erase: 0,
diameter: 10.0,
angle: 0.0,
roundness: 100.0,
hardness: 100.0,
spacing: 25.0,
preset: None,
size_pressure: true,
min_size: 1.0,
opacity_pressure: false,
flow_pressure: false,
clone_preset: 1,
clone_source: None,
clone_point: None,
aligned: true,
clone_offset: None,
lock_source_time: false,
clone_time_shift: 0.0,
clone_time: 0.0,
show_overlay: false,
overlay_opacity: 50.0,
overlay_difference: false,
}
}
}
fn norm(s: &str) -> String {
s.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase()
}
/// Index of `v` in `names` (by number or case/space-insensitive name).
fn pick(v: Option<&Value>, names: &[&str], cmd: &str, what: &str) -> Result<Option<u32>> {
match v {
None | Some(Value::Null) => Ok(None),
Some(Value::Number(n)) => {
let i = n.as_u64().unwrap_or(u64::MAX);
if (i as usize) < names.len() { Ok(Some(i as u32)) } else { Err(bad(cmd, format!("`{what}` index out of range"))) }
}
Some(Value::String(s)) => {
let k = norm(s);
names
.iter()
.position(|n| norm(n) == k || (k == "writeon" && norm(n) == "writeon"))
.map(|i| Some(i as u32))
.ok_or_else(|| bad(cmd, format!("unknown {what} `{s}`; one of: {}", names.join(", "))))
}
Some(_) => Err(bad(cmd, format!("`{what}` must be a name or index"))),
}
}
fn mode_names() -> Vec<&'static str> {
MODES.iter().map(|m| m.label()).collect()
}
fn color_p(v: Option<&Value>) -> Option<[f64; 4]> {
let a = v?.as_array()?;
let g = |i: usize, d: f64| a.get(i).and_then(Value::as_f64).unwrap_or(d);
Some([g(0, 0.0), g(1, 0.0), g(2, 0.0), g(3, 1.0)])
}
fn pt(v: Option<&Value>) -> Option<[f64; 2]> {
let a = v?.as_array()?;
Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?])
}
/// Apply option keys from `p` onto `o` (shared by `paint.options` and `paint.stroke`).
fn apply_options(o: &mut PaintOptions, p: &Value, cmd: &str) -> Result<()> {
if let Some(c) = color_p(p.get("color")) {
o.color = c;
}
if let Some(c) = color_p(p.get("background")) {
o.background = c;
}
for (k, f) in [
("opacity", &mut o.opacity as &mut f64),
("flow", &mut o.flow),
("diameter", &mut o.diameter),
("angle", &mut o.angle),
("roundness", &mut o.roundness),
("hardness", &mut o.hardness),
("spacing", &mut o.spacing),
("minSize", &mut o.min_size),
("cloneTimeShift", &mut o.clone_time_shift),
("cloneTime", &mut o.clone_time),
("overlayOpacity", &mut o.overlay_opacity),
] {
if let Some(v) = f_p(p, k) {
*f = v;
}
}
o.opacity = o.opacity.clamp(0.0, 100.0);
o.flow = o.flow.clamp(0.0, 100.0);
o.diameter = o.diameter.clamp(0.0, 2500.0);
o.roundness = o.roundness.clamp(0.0, 100.0);
o.hardness = o.hardness.clamp(0.0, 100.0);
o.spacing = o.spacing.clamp(1.0, 1000.0);
o.min_size = o.min_size.clamp(0.0, 100.0);
for (k, f) in [
("sizePressure", &mut o.size_pressure as &mut bool),
("opacityPressure", &mut o.opacity_pressure),
("flowPressure", &mut o.flow_pressure),
("aligned", &mut o.aligned),
("lockSourceTime", &mut o.lock_source_time),
("showOverlay", &mut o.show_overlay),
("overlayDifference", &mut o.overlay_difference),
] {
if let Some(v) = b_p(p, k) {
*f = v;
}
}
let modes = mode_names();
if let Some(i) = pick(p.get("mode"), &modes, cmd, "mode")? {
o.mode = i;
}
if let Some(i) = pick(p.get("channels"), &CHANNELS, cmd, "channels")? {
o.channels = i;
}
let durs = ["constant", "writeOn", "singleFrame", "custom"];
if let Some(i) = pick(p.get("durationMode"), &DURATIONS, cmd, "durationMode").or_else(|_| pick(p.get("durationMode"), &durs, cmd, "durationMode"))? {
o.duration = i;
}
if let Some(n) = p.get("customFrames").and_then(Value::as_u64) {
o.custom_frames = (n as u32).max(1);
}
let erase = ["layerSourceAndPaint", "paintOnly", "lastStrokeOnly"];
if let Some(i) = pick(p.get("eraseMode"), &ERASE_MODES, cmd, "eraseMode").or_else(|_| pick(p.get("eraseMode"), &erase, cmd, "eraseMode"))? {
o.erase = i;
}
if let Some(n) = p.get("clonePreset").and_then(Value::as_u64) {
o.clone_preset = (n as u32).clamp(1, 5);
}
match p.get("cloneSource") {
Some(Value::Null) => o.clone_source = None,
Some(Value::Number(n)) => o.clone_source = n.as_u64(),
_ => {}
}
if let Some(v) = p.get("clonePoint") {
o.clone_point = pt(Some(v));
o.clone_offset = None;
}
if let Some(v) = p.get("cloneOffset") {
o.clone_offset = pt(Some(v));
}
if let Some(i) = p.get("preset").and_then(Value::as_u64) {
set_preset(o, i as usize, cmd)?;
}
Ok(())
}
fn set_preset(o: &mut PaintOptions, i: usize, cmd: &str) -> Result<()> {
let t = BRUSH_PRESETS.get(i).ok_or_else(|| bad(cmd, format!("no brush preset {i} (0–{})", BRUSH_PRESETS.len() - 1)))?;
o.diameter = t.diameter;
o.angle = t.angle;
o.roundness = t.roundness;
o.hardness = t.hardness;
o.spacing = t.spacing;
o.preset = Some(i);
Ok(())
}
fn options(s: &mut Session, p: &Value) -> Result<Value> {
let mut o = s.state.paint.clone();
apply_options(&mut o, p, "paint.options")?;
// Editing the tip by hand deselects the preset.
if p.get("preset").is_none() && ["diameter", "angle", "roundness", "hardness", "spacing"].iter().any(|k| p.get(k).is_some()) {
o.preset = None;
}
if b_p(p, "reset") == Some(true) {
o = PaintOptions::default();
}
s.state.paint = o;
// View state only: no project revision bump.
Ok(serde_json::to_value(&s.state.paint).unwrap_or(Value::Null))
}
fn preset(s: &mut Session, p: &Value) -> Result<Value> {
let i = match p.get("preset").or_else(|| p.get("name")) {
Some(Value::Number(n)) => n.as_u64().unwrap_or(u64::MAX) as usize,
Some(Value::String(name)) => {
BRUSH_PRESETS.iter().position(|t| norm(t.name) == norm(name)).ok_or_else(|| bad("paint.brushPreset", format!("no preset `{name}`")))?
}
_ => return Ok(json!(BRUSH_PRESETS.iter().map(|t| t.name).collect::<Vec<_>>())),
};
let mut o = s.state.paint.clone();
set_preset(&mut o, i, "paint.brushPreset")?;
s.state.paint = o;
// View state only: no project revision bump.
Ok(json!({"preset": i, "name": BRUSH_PRESETS[i].name}))
}
fn set_clone_source(s: &mut Session, p: &Value) -> Result<Value> {
let point = pt(p.get("point")).ok_or_else(|| bad("paint.setCloneSource", "missing `point` [x, y] (layer space)"))?;
let (_, lid) = layer_p(s, p, "paint.setCloneSource")?;
s.state.paint.clone_source = Some(lid.0);
s.state.paint.clone_point = Some(point);
s.state.paint.clone_offset = None;
Ok(json!({"layer": lid.0, "point": point}))
}
/// The layer's Paint effect to record into: the last effect when it is Paint, else a new one.
fn paint_effect(fx: &mut PropGroup, ids: &mut Ids, layer_size: [f64; 2]) -> Result<Uid> {
if let Some(g) = fx.groups().last().filter(|g| paint::is_paint(g)) {
return Ok(g.uid);
}
let spec = effectcraft_effects::find(paint::ID).ok_or_else(|| EngineError::Other("Paint effect missing".into()))?;
let n = fx.groups().filter(|g| paint::is_paint(g)).count();
let name = if n == 0 { "Paint".to_string() } else { format!("Paint {}", n + 1) };
let g = effectcraft_effects::instantiate(spec, ids, &name, layer_size);
let uid = g.uid;
fx.children.push(g.into());
Ok(uid)
}
fn stroke(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "paint.stroke";
let (cid, lid) = layer_p(s, p, cmd)?;
let kind = match str_p(p, "kind") {
Some(k) => StrokeKind::from_name(k).ok_or_else(|| bad(cmd, format!("unknown kind `{k}` (brush | clone | eraser)")))?,
None => StrokeKind::Brush,
};
let raw = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing `points` [[x, y, pressure?], …] (layer space)"))?;
let mut points = vec![];
let mut pressure = vec![];
for q in raw {
let a = q.as_array().ok_or_else(|| bad(cmd, "each point is [x, y] or [x, y, pressure]"))?;
let (Some(x), Some(y)) = (a.first().and_then(Value::as_f64), a.get(1).and_then(Value::as_f64)) else {
return Err(bad(cmd, "each point is [x, y] or [x, y, pressure]"));
};
points.push([x, y]);
pressure.push(a.get(2).and_then(Value::as_f64).unwrap_or(1.0).clamp(0.0, 1.0));
}
if points.is_empty() {
return Err(bad(cmd, "`points` is empty"));
}
if pressure.iter().all(|v| *v == 1.0) {
pressure.clear();
}
let mut o = s.state.paint.clone();
apply_options(&mut o, p, cmd)?;
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let fr = comp.frame_rate;
let fd = fr.frame_duration();
let t = fr.snap_nearest(super::time_p(s, p, Some(comp)));
let layer = comp.layer(lid).ok_or_else(|| bad(cmd, "no layer"))?;
let lt = layer.layer_time(t);
let (w, h) = effectcraft_render::source_size(&s.project, layer);
let size = if w == 0 { [comp.width as f64, comp.height as f64] } else { [w as f64, h as f64] };
if layer.effects().is_none() || !layer.source.is_av() {
return Err(bad(cmd, "this layer can't be painted on"));
}
let in_t = lt.seconds();
let (out_t, write_on) = match o.duration {
1 => (paint::FOREVER, true),
2 => ((lt + fd).seconds(), false),
3 => ((lt + Tick(fd.0 * o.custom_frames.max(1) as i64)).seconds(), false),
_ => (paint::FOREVER, false),
};
// Write On: End animates 0 → 100 % over the time the stroke took to draw.
let draw = f_p(p, "duration").unwrap_or(points.len() as f64 / fr.as_f64().max(1.0)).max(0.0);
let draw_end = lt + fr.snap_nearest(Tick::from_seconds_f64(draw)).max(fd);
// Clone position: explicit, Aligned offset, or the source point.
let first = points[0];
let mut clone_position = pt(p.get("clonePosition"));
if kind == StrokeKind::Clone && clone_position.is_none() {
clone_position = Some(match (o.aligned, o.clone_offset, o.clone_point) {
(true, Some(off), _) => [first[0] + off[0], first[1] + off[1]],
(_, _, Some(sp)) => sp,
_ => first,
});
}
let clone_source = match p.get("cloneSource") {
Some(Value::Number(n)) => n.as_u64(),
Some(Value::Null) => None,
_ => o.clone_source.filter(|id| *id != lid.0),
};
let spec = StrokeSpec {
kind,
points,
pressure,
color: o.color,
diameter: o.diameter,
angle: o.angle,
hardness: o.hardness,
roundness: o.roundness,
spacing: o.spacing,
channels: o.channels,
opacity: o.opacity,
flow: o.flow,
mode: o.mode,
size_pressure: o.size_pressure,
min_size: o.min_size,
opacity_pressure: o.opacity_pressure,
flow_pressure: o.flow_pressure,
erase_mode: o.erase,
target: None,
clone_source,
clone_position: clone_position.unwrap_or(first),
clone_time_shift: o.clone_time_shift,
lock_time: o.lock_source_time,
clone_time: o.clone_time,
in_time: in_t,
out_time: out_t,
duration: o.duration,
};
let label = format!("{} Stroke", kind.label());
let (fx_uid, uid) = s.edit(&label, None, |proj, st| {
let mut next = proj.next_id;
let l = layer_mut(proj, cid, lid)?;
let fx = l.props.sub_mut("effects").ok_or_else(|| bad(cmd, "this layer has no effects"))?;
let mut ids = Ids(&mut next);
let fx_uid = paint_effect(fx, &mut ids, size)?;
let pg = fx.find_group_mut(fx_uid).ok_or_else(|| bad(cmd, "Paint effect gone"))?;
let mut spec = spec;
if spec.kind == StrokeKind::Eraser && spec.erase_mode == 2 {
spec.target = paint::strokes(pg).filter(|g| g.match_id != "eraser").last().map(|g| g.uid);
}
let name = paint::next_name(pg, spec.kind);
let mut g = paint::stroke_group(&mut ids, &name, &spec);
if write_on && let Some(end) = g.sub_mut("stroke_options").and_then(|o| o.get_mut("end")) {
end.keys = vec![Keyframe::new(lt, KV::Scalar(0.0)), Keyframe::new(draw_end, KV::Scalar(100.0))];
}
let uid = g.uid;
pg.children.push(g.into());
proj.next_id = next;
st.selected_props = vec![(lid, uid)];
if spec.kind == StrokeKind::Clone && st.paint.aligned && st.paint.clone_offset.is_none() {
st.paint.clone_offset = Some([spec.clone_position[0] - spec.points[0][0], spec.clone_position[1] - spec.points[0][1]]);
}
Ok((fx_uid, uid))
})?;
Ok(json!({"effect": fx_uid, "stroke": uid}))
}
/// Find a stroke group by uid or name across the layer's Paint effects.
fn remove_stroke(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "paint.removeStroke";
let (cid, lid) = layer_p(s, p, cmd)?;
let key = p.get("stroke").cloned().ok_or_else(|| bad(cmd, "missing `stroke` (uid or name)"))?;
s.edit("Delete Stroke", None, |proj, st| {
let l = layer_mut(proj, cid, lid)?;
let fx = l.props.sub_mut("effects").ok_or_else(|| bad(cmd, "no effects"))?;
for c in fx.children.iter_mut() {
let Some(g) = c.as_group_mut() else { continue };
if !matches!(&g.kind, GroupKind::Effect { effect } if effect == paint::ID) {
continue;
}
let before = g.children.len();
g.children.retain(|n| {
let Some(sg) = n.as_group() else { return true };
let hit = match &key {
Value::Number(u) => u.as_u64() == Some(sg.uid),
Value::String(name) => &sg.name == name,
_ => false,
};
!(hit && matches!(sg.match_id.as_str(), "brush" | "clone" | "eraser"))
});
if g.children.len() != before {
st.selected_props.clear();
return Ok(());
}
}
Err(bad(cmd, "no such stroke"))
})?;
Ok(Value::Null)
}
fn presets(_: &mut Session, _: &Value) -> Result<Value> {
Ok(json!(
BRUSH_PRESETS
.iter()
.enumerate()
.map(|(i, t)| json!({"index": i, "name": t.name, "diameter": t.diameter, "angle": t.angle, "roundness": t.roundness, "hardness": t.hardness, "spacing": t.spacing}))
.collect::<Vec<_>>()
))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"paint.stroke",
"Paint Stroke",
[],
None,
"{layer?, kind?: brush|clone|eraser, points: [[x,y,pressure?],…] (layer space), time? (s) | frame?, duration? (s, drawing time for Write On), color?: [r,g,b,a], diameter?, angle?, hardness?, roundness?, spacing?, opacity?, flow?, mode?, channels?: RGBA|RGB|Alpha, durationMode?: constant|writeOn|singleFrame|custom, customFrames?, eraseMode?: layerSourceAndPaint|paintOnly|lastStrokeOnly, cloneSource?: layer id, clonePosition?: [x,y], cloneTimeShift? (s), lockSourceTime?, cloneTime? (s), sizePressure?, minSize?, opacityPressure?, flowPressure?}",
has_comp,
stroke
),
cmd!(
"paint.options",
"Paint Options",
[],
None,
"{color?, background?, opacity?, flow?, mode?, channels?, durationMode?, customFrames?, eraseMode?, diameter?, angle?, roundness?, hardness?, spacing?, preset?, sizePressure?, minSize?, opacityPressure?, flowPressure?, clonePreset?, cloneSource?, clonePoint?, cloneOffset?, aligned?, lockSourceTime?, cloneTimeShift?, cloneTime?, showOverlay?, overlayOpacity?, overlayDifference?, reset?}",
always,
options
),
cmd!("paint.brushPreset", "Brush Preset", [], None, "{preset?: index | name}", always, preset),
cmd!("paint.setCloneSource", "Set Clone Source", [], None, "{layer?, point: [x,y]}", has_comp, set_clone_source),
cmd!("paint.removeStroke", "Delete Paint Stroke", [], None, "{layer?, stroke: uid | name}", has_comp, remove_stroke),
crate::query!("paint.presets", "Brush Presets", "{}", presets),
]
}
+386
View File
@@ -0,0 +1,386 @@
//! 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.
//!
//! 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.
use effectcraft_effects::puppet::{self, MeshOpts, PinKind};
use effectcraft_effects::{Buf, Params};
use effectcraft_keyframe::Value as KV;
use effectcraft_project::build::Ids;
use effectcraft_project::{ItemId, LayerId, Node, PropGroup, Uid};
use effectcraft_render::{EvalCtx, RenderOpts, Renderer};
use effectcraft_time::Tick;
use serde_json::{Value, json};
use super::{CommandSpec, bad, f_p, has_comp, layer_mut, layer_p, merge_p, str_p};
use crate::{EngineError, Result, Session, cmd};
fn pt(v: Option<&Value>) -> Option<[f64; 2]> {
let a = v?.as_array()?;
Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?])
}
/// The Puppet effect's input pixels and evaluated parameters at comp time `t`.
pub fn puppet_eval(s: &Session, cid: ItemId, lid: LayerId, fx_uid: Uid, t: Tick) -> Option<(Buf, Params)> {
let comp = s.project.comp(cid)?;
let layer = comp.layer(lid)?;
let fx = layer.effects()?;
let index = fx.groups().position(|g| g.uid == fx_uid)?;
let g = fx.groups().nth(index)?;
let ctx = EvalCtx { project: &s.project, comp_id: cid, comp, time: t, expr: s.expr.as_deref() };
let mut r = Renderer::new(&s.project, &*s.footage, RenderOpts::default());
r.expr = s.expr.as_deref();
r.cache = Some(&s.layer_cache);
let buf = (*r.layer_input(&ctx, layer, index)?).clone();
let params = effectcraft_effects::flatten_params(g, &mut |p| ctx.value(layer, p));
Some((buf, params))
}
fn find_puppet(s: &Session, cid: ItemId, lid: LayerId) -> Option<Uid> {
s.project.comp(cid)?.layer(lid)?.effects()?.groups().find(|g| puppet::is_puppet(g)).map(|g| g.uid)
}
fn snapped(s: &Session, cid: ItemId, p: &Value) -> Result<Tick> {
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
Ok(comp.frame_rate.snap_nearest(super::time_p(s, p, Some(comp))))
}
fn layer_time(s: &Session, cid: ItemId, lid: LayerId, t: Tick) -> Result<Tick> {
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?;
Ok(l.layer_time(t))
}
fn add_pin(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "puppet.addPin";
let (cid, lid) = layer_p(s, p, cmd)?;
let kind = match str_p(p, "kind") {
Some(k) => PinKind::from_name(k).ok_or_else(|| bad(cmd, format!("unknown kind `{k}` (position | advanced | bend | starch | overlap)")))?,
None => PinKind::Position,
};
let at = pt(p.get("position")).ok_or_else(|| bad(cmd, "missing `position` [x, y] (layer space)"))?;
let t = snapped(s, cid, p)?;
let lt = layer_time(s, cid, lid, t)?;
{
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?;
if l.effects().is_none() || !l.source.is_av() {
return Err(bad(cmd, "the Puppet tools work on footage, solid, text, shape and precomp layers"));
}
}
// Which mesh: the one under the click (through the current deformation), else a new one.
let fx_uid = find_puppet(s, cid, lid);
let want_mesh = p.get("mesh").and_then(Value::as_u64);
let new_mesh = p.get("newMesh").and_then(Value::as_bool).unwrap_or(false);
let mut target: Option<(Uid, [f64; 2])> = None;
if let Some(fu) = fx_uid
&& !new_mesh
&& let Some((buf, params)) = puppet_eval(s, cid, lid, fu, t)
{
let meshes = puppet::overlay(&buf, &params);
for (uid, mesh, def, _) in &meshes {
if want_mesh.is_some_and(|w| w != *uid) || mesh.tris.is_empty() {
continue;
}
let inside = mesh.tris.iter().any(|tr| {
let (a, b, c) = (def[tr[0]], def[tr[1]], def[tr[2]]);
let cr = |o: [f64; 2], u: [f64; 2], v: [f64; 2]| (u[0] - o[0]) * (v[1] - o[1]) - (u[1] - o[1]) * (v[0] - o[0]);
cr(a, b, at) >= 0.0 && cr(b, c, at) >= 0.0 && cr(c, a, at) >= 0.0
});
let near = def.iter().map(|v| (v[0] - at[0]).hypot(v[1] - at[1])).fold(f64::MAX, f64::min) < 12.0;
if inside || near || want_mesh.is_some() {
target = Some((*uid, puppet::unmap(mesh, def, at)));
break;
}
}
if target.is_none()
&& let Some(w) = want_mesh
{
return Err(bad(cmd, format!("no mesh {w}")));
}
}
let opts = MeshOpts {
density: f_p(p, "density").unwrap_or(s.state.puppet.density),
expansion: f_p(p, "expansion").unwrap_or(s.state.puppet.expansion),
triangles: f_p(p, "triangles").unwrap_or(s.state.puppet.triangles),
};
let size = {
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let l = comp.layer(lid).ok_or(EngineError::NoComp)?;
let (w, h) = effectcraft_render::source_size(&s.project, l);
if w == 0 { [comp.width as f64, comp.height as f64] } else { [w as f64, h as f64] }
};
let label = match kind {
PinKind::Starch => "Add Starch Pin",
PinKind::Overlap => "Add Overlap Pin",
_ => "Add Puppet Pin",
};
let (fx, mesh, pin) = s.edit(label, None, |proj, st| {
let mut next = proj.next_id;
let l = layer_mut(proj, cid, lid)?;
let fxg = l.props.sub_mut("effects").ok_or_else(|| bad(cmd, "no effects"))?;
let mut ids = Ids(&mut next);
let fx_uid = match fx_uid {
Some(u) => u,
None => {
let spec = effectcraft_effects::find(puppet::ID).ok_or_else(|| EngineError::Other("Puppet effect missing".into()))?;
let g = effectcraft_effects::instantiate(spec, &mut ids, "Puppet", size);
let u = g.uid;
fxg.children.push(g.into());
u
}
};
let pg = fxg.find_group_mut(fx_uid).ok_or_else(|| bad(cmd, "Puppet effect gone"))?;
let (mesh_uid, rest) = match target {
Some((m, r)) => (m, r),
None => {
let n = puppet::meshes(pg).count();
let g = puppet::mesh_group(&mut ids, &format!("Mesh {}", n + 1), at, &opts);
let u = g.uid;
pg.children.push(g.into());
(u, at)
}
};
let name = puppet::next_pin_name(pg, kind);
let mg = pg.find_group_mut(mesh_uid).ok_or_else(|| bad(cmd, "mesh gone"))?;
let mut pin = puppet::pin_group(&mut ids, &name, kind, rest);
if let Some(pos) = pin.get_mut("position") {
if kind.moves() {
pos.value = KV::Vec2(at);
pos.set_animated(true, lt);
} else {
pos.value = KV::Vec2(rest);
}
}
let pin_uid = pin.uid;
let deform = mg.sub_mut("deform").ok_or_else(|| bad(cmd, "mesh has no Deform group"))?;
deform.children.push(pin.into());
proj.next_id = next;
st.selected_props = vec![(lid, pin_uid)];
Ok((fx_uid, mesh_uid, pin_uid))
})?;
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]]}))
}
/// 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);
}
}
}
}
Err(bad(cmd, format!("no puppet pin {key}")))
}
fn with_pin<T>(s: &mut Session, p: &Value, cmd: &str, label: &str, f: impl FnOnce(&mut PropGroup, Tick) -> Result<T>) -> Result<T> {
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)?;
let t = snapped(s, cid, p)?;
let lt = layer_time(s, cid, lid, t)?;
s.edit(label, merge_p(p), |proj, st| {
let l = layer_mut(proj, cid, lid)?;
let g = l.props.find_group_mut(uid).ok_or_else(|| bad(cmd, "pin gone"))?;
let r = f(g, lt)?;
st.selected_props = vec![(lid, uid)];
Ok(r)
})
}
fn move_pin(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "puppet.movePin";
let to = pt(p.get("position")).ok_or_else(|| bad(cmd, "missing `position` [x, y] (layer space)"))?;
with_pin(s, p, cmd, "Move Puppet Pin", |g, lt| {
let kind = PinKind::from_index(g.get("kind").map(|k| k.value.as_enum()).unwrap_or(0));
let pos = g.get_mut("position").ok_or_else(|| bad(cmd, "Bend pins have no position (use puppet.setPin rotation/scale)"))?;
pos.set_value_at(lt, KV::Vec2(to));
// Starch and Overlap pins sit on the rest mesh: moving them moves their region.
if !kind.moves()
&& let Some(r) = g.get_mut("rest")
{
r.value = KV::Vec2(to);
}
Ok(())
})?;
Ok(Value::Null)
}
fn set_pin(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "puppet.setPin";
let fields: Vec<(&str, KV)> = [("scale", "scale"), ("rotation", "rotation"), ("amount", "amount"), ("extent", "extent"), ("inFront", "in_front")]
.iter()
.filter_map(|(k, m)| f_p(p, k).map(|v| (*m, KV::Scalar(v))))
.chain(pt(p.get("position")).map(|v| ("position", KV::Vec2(v))))
.collect();
if fields.is_empty() {
return Err(bad(cmd, "nothing to set (position, scale, rotation, amount, extent, inFront)"));
}
with_pin(s, p, cmd, "Edit Puppet Pin", |g, lt| {
for (m, v) in fields {
let pr = g.get_mut(m).ok_or_else(|| bad(cmd, format!("this pin has no `{m}`")))?;
pr.set_value_at(lt, v);
}
Ok(())
})?;
Ok(Value::Null)
}
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);
}
st.selected_props.retain(|(_, u)| *u != uid);
Ok(())
})?;
Ok(Value::Null)
}
fn mesh_opts(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "puppet.mesh";
let fields: Vec<(&str, f64)> = ["density", "expansion", "triangles"].iter().filter_map(|k| f_p(p, k).map(|v| (*k, v))).collect();
if let Some(b) = p.get("showMesh").and_then(Value::as_bool) {
s.state.puppet.show_mesh = b;
}
if fields.is_empty() {
return Ok(serde_json::to_value(&s.state.puppet).unwrap_or(Value::Null));
}
// Without a layer: set the tool defaults for new meshes.
let has_layer = p.get("layer").is_some() || !s.state.selected_layers.is_empty();
let (cid, lid) = match layer_p(s, p, cmd) {
Ok(x) => x,
Err(_) if !has_layer => {
for (k, v) in &fields {
match *k {
"density" => s.state.puppet.density = v.clamp(0.0, 100.0),
"expansion" => s.state.puppet.expansion = *v,
_ => s.state.puppet.triangles = v.max(10.0),
}
}
return Ok(serde_json::to_value(&s.state.puppet).unwrap_or(Value::Null));
}
Err(e) => return Err(e),
};
let fx = find_puppet(s, cid, lid).ok_or_else(|| bad(cmd, "the layer has no Puppet effect (add a pin first)"))?;
let want = p.get("mesh").and_then(Value::as_u64);
let t = snapped(s, cid, p)?;
let lt = layer_time(s, cid, lid, t)?;
for (k, v) in &fields {
match *k {
"density" => s.state.puppet.density = v.clamp(0.0, 100.0),
"expansion" => s.state.puppet.expansion = *v,
_ => s.state.puppet.triangles = v.max(10.0),
}
}
s.edit("Puppet Mesh", merge_p(p), |proj, _| {
let l = layer_mut(proj, cid, lid)?;
let g = l.props.find_group_mut(fx).ok_or_else(|| bad(cmd, "Puppet effect gone"))?;
let mut done = 0;
for c in g.children.iter_mut() {
let Node::Group(m) = c else { continue };
if m.match_id != "mesh" || want.is_some_and(|w| w != m.uid) {
continue;
}
for (k, v) in &fields {
if let Some(pr) = m.get_mut(k) {
pr.set_value_at(lt, KV::Scalar(*v));
}
}
done += 1;
}
if done == 0 { Err(bad(cmd, "no such mesh")) } else { Ok(()) }
})?;
Ok(Value::Null)
}
/// Meshes, pins and the deformed mesh at the current time (layer space).
fn info(s: &mut Session, p: &Value) -> Result<Value> {
let (cid, lid) = layer_p(s, p, "puppet.info")?;
let Some(fx) = find_puppet(s, cid, lid) else { return Ok(json!({"meshes": []})) };
let t = snapped(s, cid, p)?;
let (buf, params) = puppet_eval(s, cid, lid, fx, t).ok_or_else(|| bad("puppet.info", "the layer has no pixels"))?;
let meshes: Vec<Value> = puppet::overlay(&buf, &params)
.into_iter()
.map(|(uid, mesh, def, pins)| {
json!({
"mesh": uid,
"triangles": mesh.tris.len(),
"vertices": mesh.verts.len(),
"outline": mesh.outline,
"deformed": def,
"tris": mesh.tris,
"pins": pins.iter().map(|pn| json!({"pin": pn.uid, "kind": pn.kind.name(), "rest": pn.rest, "position": pn.position})).collect::<Vec<_>>(),
})
})
.collect();
Ok(json!({"effect": fx, "meshes": meshes}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"puppet.addPin",
"Add Puppet Pin",
[],
None,
"{layer?, kind?: position|advanced|bend|starch|overlap, position: [x,y] (layer space), time? (s) | frame?, mesh?: uid, newMesh?, density?, expansion?, triangles?}",
has_comp,
add_pin
),
cmd!("puppet.movePin", "Move Puppet Pin", [], None, "{layer?, pin: uid | name, position: [x,y], time? | frame?, merge?}", has_comp, move_pin),
cmd!(
"puppet.setPin",
"Edit Puppet Pin",
[],
None,
"{layer?, pin: uid | name, position?, scale? (%), rotation? (°), amount? (%), extent? (px), inFront?, time? | frame?, merge?}",
has_comp,
set_pin
),
cmd!("puppet.removePin", "Delete Puppet Pin", [], None, "{layer?, pin: uid | name}", has_comp, remove_pin),
cmd!(
"puppet.mesh",
"Puppet Mesh Options",
[],
None,
"{layer?, mesh?: uid, density?, expansion?, triangles?, showMesh?, time?, merge?}",
super::always,
mesh_opts
),
crate::query!("puppet.info", "Puppet Mesh Info", "{layer?, time? | frame?}", info),
]
}
/// Puppet tool options (the Tools bar's Mesh: Show / Expansion / Density for new meshes).
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PuppetOptions {
pub density: f64,
pub expansion: f64,
pub triangles: f64,
/// Show the mesh in the viewer.
pub show_mesh: bool,
}
impl Default for PuppetOptions {
fn default() -> Self {
let d = MeshOpts::default();
PuppetOptions { density: d.density, expansion: d.expansion, triangles: d.triangles, show_mesh: false }
}
}
+8
View File
@@ -153,6 +153,12 @@ pub struct EditorState {
/// Viewer 3D view per comp (Active Camera / Front / … / Custom View 3 and edited view cameras).
#[serde(default)]
pub views3d: std::collections::BTreeMap<ItemId, effectcraft_render::three_d::Views3D>,
/// Paint and Brushes panel options (Brush, Clone Stamp and Eraser tools).
#[serde(default)]
pub paint: commands::paint::PaintOptions,
/// Puppet tool options for new meshes.
#[serde(default)]
pub puppet: commands::puppet::PuppetOptions,
}
/// What Copy with Property Links / Copy Expression Only put on the clipboard.
@@ -471,3 +477,5 @@ pub fn text_presets() -> Vec<(String, String)> {
pub fn text_families() -> Vec<String> {
effectcraft_text::families().into_iter().map(|(f, _)| f).collect()
}
#[cfg(test)]
mod tests_paint;
+229
View File
@@ -0,0 +1,229 @@
//! Paint and Puppet commands: undoable edits, options, rendering through the session.
use effectcraft_render::RenderOpts;
use effectcraft_time::Tick;
use serde_json::{Value, json};
use crate::Session;
/// 200×100 comp, 2 s at 30 fps, with a 100×60 blue solid centred (comp 50..150 × 20..80).
fn setup() -> (Session, u64) {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "C", "width": 200, "height": 100, "duration": 2, "frameRate": 30})).unwrap();
let id = s.execute("layer.newSolid", json!({"width": 100, "height": 60, "color": [0, 0, 1]})).unwrap()["layer"].as_u64().unwrap();
(s, id)
}
fn px(s: &Session, t: f64, x: i64, y: i64) -> [f32; 4] {
let cid = s.active_comp_id().unwrap();
s.render(cid, Tick::from_seconds_f64(t), RenderOpts::default()).get(x, y)
}
fn layer(s: &Session, id: u64) -> effectcraft_project::Layer {
s.active_comp().unwrap().layer(effectcraft_project::LayerId(id)).unwrap().clone()
}
#[test]
fn brush_stroke_is_an_undoable_effect() {
let (mut s, id) = setup();
s.execute("paint.options", json!({"color": [1, 0, 0, 1], "diameter": 8, "sizePressure": false})).unwrap();
let r = s.execute("paint.stroke", json!({"layer": id, "points": [[10, 30], [90, 30]]})).unwrap();
let fx = r["effect"].as_u64().unwrap();
let l = layer(&s, id);
let g = l.props.find_group(fx).unwrap();
assert_eq!(g.name, "Paint");
assert_eq!(effectcraft_effects::paint::strokes(g).count(), 1);
assert_eq!(g.groups().next().unwrap().name, "Brush 1");
// Layer (10..90, 30) → comp (60..140, 50).
assert_eq!(px(&s, 0.0, 100, 50), [1.0, 0.0, 0.0, 1.0]);
assert_eq!(px(&s, 0.0, 100, 40), [0.0, 0.0, 1.0, 1.0]);
// Second stroke goes into the same Paint effect.
let r2 = s.execute("paint.stroke", json!({"layer": id, "points": [[50, 5]], "kind": "eraser", "diameter": 20})).unwrap();
assert_eq!(r2["effect"].as_u64(), Some(fx));
assert_eq!(px(&s, 0.0, 100, 25)[3], 0.0);
assert!(s.undo());
assert_eq!(px(&s, 0.0, 100, 25), [0.0, 0.0, 1.0, 1.0]);
assert!(s.undo());
assert!(layer(&s, id).effects().unwrap().children.is_empty());
assert_eq!(px(&s, 0.0, 100, 50), [0.0, 0.0, 1.0, 1.0]);
assert!(s.redo());
assert_eq!(px(&s, 0.0, 100, 50), [1.0, 0.0, 0.0, 1.0]);
// Another effect after Paint: the next stroke starts a new Paint instance.
s.execute("effect.apply", json!({"layer": id, "effect": "Invert"})).unwrap();
let r3 = s.execute("paint.stroke", json!({"layer": id, "points": [[20, 20]]})).unwrap();
assert_ne!(r3["effect"].as_u64(), Some(fx));
assert_eq!(layer(&s, id).props.find_group(r3["effect"].as_u64().unwrap()).unwrap().name, "Paint 2");
}
#[test]
fn durations_set_spans_and_write_on_keys() {
let (mut s, id) = setup();
s.set_time(Tick::from_seconds_f64(0.5));
let r = s.execute("paint.stroke", json!({"layer": id, "points": [[10, 30], [90, 30]], "durationMode": "writeOn", "duration": 0.5})).unwrap();
let l = layer(&s, id);
let g = l.props.find_group(r["stroke"].as_u64().unwrap()).unwrap();
let end = g.sub("stroke_options").unwrap().get("end").unwrap();
assert_eq!(end.keys.len(), 2);
assert_eq!(end.keys[0].time, Tick::from_seconds_f64(0.5));
assert_eq!(end.keys[1].time, Tick::from_seconds_f64(1.0));
// Written on over 0.5–1.0 s: invisible before, half at 0.75 s.
assert_eq!(px(&s, 0.25, 100, 50), [0.0, 0.0, 1.0, 1.0]);
assert_eq!(px(&s, 0.75, 70, 50)[1], 1.0);
assert_eq!(px(&s, 0.75, 130, 50), [0.0, 0.0, 1.0, 1.0]);
assert_eq!(px(&s, 1.5, 130, 50)[1], 1.0);
// Single Frame: visible on its frame only.
s.set_time(Tick::from_seconds_f64(1.0));
s.execute("paint.stroke", json!({"layer": id, "points": [[50, 50]], "durationMode": "singleFrame", "color": [1, 0, 0, 1], "diameter": 6})).unwrap();
assert_eq!(px(&s, 1.0, 100, 70), [1.0, 0.0, 0.0, 1.0]);
assert_eq!(px(&s, 1.0 + 1.0 / 30.0, 100, 70), [0.0, 0.0, 1.0, 1.0]);
assert_eq!(px(&s, 0.9, 100, 70), [0.0, 0.0, 1.0, 1.0]);
}
#[test]
fn eraser_last_stroke_only_targets_previous_stroke() {
let (mut s, id) = setup();
s.execute("paint.stroke", json!({"layer": id, "points": [[40, 30]], "color": [0, 1, 0, 1], "diameter": 30})).unwrap();
let b = s.execute("paint.stroke", json!({"layer": id, "points": [[50, 30]], "color": [1, 0, 0, 1], "diameter": 30})).unwrap()["stroke"].as_u64().unwrap();
let e = s.execute("paint.stroke", json!({"layer": id, "kind": "eraser", "eraseMode": "lastStrokeOnly", "points": [[50, 30]], "diameter": 10})).unwrap();
let l = layer(&s, id);
let eg = l.props.find_group(e["stroke"].as_u64().unwrap()).unwrap();
assert_eq!(eg.get("target").unwrap().value.as_f64() as u64, b);
assert_eq!(px(&s, 0.0, 100, 50), [0.0, 1.0, 0.0, 1.0]);
}
#[test]
fn clone_stroke_uses_source_point_and_aligned_offset() {
let (mut s, id) = setup();
// Paint a red dot at layer (20, 20), then clone it to (70, 40).
s.execute("paint.stroke", json!({"layer": id, "points": [[20, 20]], "color": [1, 0, 0, 1], "diameter": 10, "sizePressure": false})).unwrap();
s.execute("paint.setCloneSource", json!({"layer": id, "point": [20, 20]})).unwrap();
let r = s.execute("paint.stroke", json!({"layer": id, "kind": "clone", "points": [[70, 40]], "diameter": 12})).unwrap();
let l = layer(&s, id);
let g = l.props.find_group(r["stroke"].as_u64().unwrap()).unwrap();
assert_eq!(g.sub("stroke_options").unwrap().get("clone_position").unwrap().value.as_vec2(), [20.0, 20.0]);
assert_eq!(s.state.paint.clone_offset, Some([-50.0, -20.0]));
// Clone source is this layer before paint: blue copied over blue. With Paint on the
// source layer itself the clone samples the unpainted source.
assert_eq!(px(&s, 0.0, 120, 60), [0.0, 0.0, 1.0, 1.0]);
// Aligned: the next stroke keeps the offset.
let r = s.execute("paint.stroke", json!({"layer": id, "kind": "clone", "points": [[80, 45]]})).unwrap();
let l = layer(&s, id);
let g = l.props.find_group(r["stroke"].as_u64().unwrap()).unwrap();
assert_eq!(g.sub("stroke_options").unwrap().get("clone_position").unwrap().value.as_vec2(), [30.0, 25.0]);
}
#[test]
fn clone_from_another_layer() {
let (mut s, id) = setup();
let red = s.execute("layer.newSolid", json!({"width": 100, "height": 60, "color": [1, 0, 0]})).unwrap()["layer"].as_u64().unwrap();
// Hide the red layer by moving it out of view instead of relying on a switch command.
s.execute("prop.set", json!({"layer": red, "path": "transform/position", "value": [1000, 1000, 0]})).unwrap();
s.execute("paint.stroke", json!({"layer": id, "kind": "clone", "cloneSource": red, "clonePosition": [50, 30], "points": [[50, 30]], "diameter": 10}))
.unwrap();
assert_eq!(px(&s, 0.0, 100, 50), [1.0, 0.0, 0.0, 1.0]);
assert_eq!(px(&s, 0.0, 70, 50), [0.0, 0.0, 1.0, 1.0]);
}
#[test]
fn paint_options_and_presets() {
let mut s = Session::default();
let o = s.execute("paint.options", json!({"opacity": 50, "mode": "Multiply", "channels": "RGB", "durationMode": "custom", "customFrames": 5})).unwrap();
assert_eq!(o["opacity"], json!(50.0));
assert_eq!(s.state.paint.mode, 2);
assert_eq!(s.state.paint.channels, 1);
assert_eq!(s.state.paint.duration, 3);
assert!(s.execute("paint.options", json!({"mode": "Nope"})).is_err());
let r = s.execute("paint.brushPreset", json!({"preset": "Soft Round 45 px"})).unwrap();
assert_eq!(r["preset"], json!(13));
assert_eq!(s.state.paint.diameter, 45.0);
assert_eq!(s.state.paint.hardness, 0.0);
let list = s.execute("paint.presets", json!({})).unwrap();
assert!(list.as_array().unwrap().len() >= 20);
// State is serde (agents read it).
let j = serde_json::to_value(&s.state).unwrap();
let back: crate::EditorState = serde_json::from_value(j).unwrap();
assert_eq!(back.paint, s.state.paint);
}
fn pin_count(s: &Session, id: u64) -> usize {
let l = layer(s, id);
l.effects().unwrap().groups().map(effectcraft_effects::puppet::pin_count).sum()
}
#[test]
fn puppet_pins_deform_and_undo() {
let (mut s, id) = setup();
let a = s.execute("puppet.addPin", json!({"layer": id, "position": [10, 30]})).unwrap();
let b = s.execute("puppet.addPin", json!({"layer": id, "position": [90, 30]})).unwrap();
assert_eq!(a["mesh"], b["mesh"], "second pin lands on the same mesh");
assert_eq!(pin_count(&s, id), 2);
let l = layer(&s, id);
let pin = l.props.find_group(a["pin"].as_u64().unwrap()).unwrap();
assert_eq!(pin.name, "Puppet Pin 1");
assert_eq!(pin.get("position").unwrap().keys.len(), 1, "position pins are keyframed");
// Pins at rest: the layer looks the same.
assert_eq!(px(&s, 0.0, 100, 50), [0.0, 0.0, 1.0, 1.0]);
let info = s.execute("puppet.info", json!({"layer": id})).unwrap();
assert!(info["meshes"][0]["triangles"].as_u64().unwrap() > 50);
// Move both pins down 15 px at 1 s: the whole layer follows.
s.set_time(Tick::from_seconds_f64(1.0));
s.execute("puppet.movePin", json!({"layer": id, "pin": a["pin"], "position": [10, 45]})).unwrap();
s.execute("puppet.movePin", json!({"layer": id, "pin": "Puppet Pin 2", "position": [90, 45]})).unwrap();
let l = layer(&s, id);
assert_eq!(l.props.find_group(a["pin"].as_u64().unwrap()).unwrap().get("position").unwrap().keys.len(), 2);
assert_eq!(px(&s, 1.0, 100, 90), [0.0, 0.0, 1.0, 1.0]);
assert_eq!(px(&s, 1.0, 100, 25)[3], 0.0);
assert_eq!(px(&s, 0.0, 100, 25), [0.0, 0.0, 1.0, 1.0]);
// A third pin added while deformed maps back to the rest mesh.
let c = s.execute("puppet.addPin", json!({"layer": id, "position": [50, 45]})).unwrap();
let rest = c["rest"].as_array().unwrap();
assert!((rest[1].as_f64().unwrap() - 30.0).abs() < 0.5, "{rest:?}");
s.undo();
s.undo();
s.undo();
assert_eq!(pin_count(&s, id), 2);
assert_eq!(px(&s, 1.0, 100, 25), [0.0, 0.0, 1.0, 1.0]);
}
#[test]
fn puppet_pin_kinds_and_mesh_options() {
let (mut s, id) = setup();
for (k, pos) in [("position", [10, 30]), ("starch", [50, 30]), ("bend", [90, 30]), ("overlap", [30, 30]), ("advanced", [70, 30])] {
s.execute("puppet.addPin", json!({"layer": id, "kind": k, "position": pos})).unwrap();
}
let l = layer(&s, id);
let names: Vec<String> = {
let fx = l.effects().unwrap().groups().next().unwrap();
effectcraft_effects::puppet::meshes(fx).flat_map(|m| effectcraft_effects::puppet::pins(m).map(|p| p.name.clone())).collect()
};
assert_eq!(names, ["Puppet Pin 1", "Starch 1", "Puppet Pin 2", "Overlap 1", "Puppet Pin 3"]);
assert!(s.execute("puppet.movePin", json!({"layer": id, "pin": "Puppet Pin 2", "position": [1, 1]})).is_err(), "bend pins have no position");
s.execute("puppet.setPin", json!({"layer": id, "pin": "Puppet Pin 2", "rotation": 30})).unwrap();
s.execute("puppet.setPin", json!({"layer": id, "pin": "Starch 1", "amount": 80, "extent": 25})).unwrap();
s.execute("puppet.mesh", json!({"layer": id, "density": 80, "expansion": 5})).unwrap();
let l = layer(&s, id);
let fx = l.effects().unwrap().groups().next().unwrap();
let m = effectcraft_effects::puppet::meshes(fx).next().unwrap();
assert_eq!(m.get("density").unwrap().value.as_f64(), 80.0);
assert_eq!(m.get("expansion").unwrap().value.as_f64(), 5.0);
// Renders, deterministically.
let cid = s.active_comp_id().unwrap();
let a = s.render(cid, Tick::ZERO, RenderOpts::default());
let b = s.render(cid, Tick::ZERO, RenderOpts::default());
assert_eq!(a, b);
s.execute("puppet.removePin", json!({"layer": id, "pin": "Overlap 1"})).unwrap();
assert_eq!(pin_count(&s, id), 4);
}
#[test]
fn project_with_paint_and_puppet_round_trips() {
let (mut s, id) = setup();
s.execute("paint.stroke", json!({"layer": id, "points": [[10, 30, 0.5], [90, 30, 1.0]], "durationMode": "writeOn"})).unwrap();
s.execute("puppet.addPin", json!({"layer": id, "position": [10, 30]})).unwrap();
let j = s.project.to_json();
let back = effectcraft_project::Project::from_json(&j).unwrap();
assert_eq!(&back, s.project.as_ref());
let v: Value = serde_json::from_str(&j).unwrap();
assert!(v.to_string().contains("ec.paint.paint") && v.to_string().contains("ec.distort.puppet"));
}