From e2e149ad9f8504fd134ca024bafc3214e5a41050 Mon Sep 17 00:00:00 2001 From: Bar Borer Date: Fri, 4 Dec 2026 07:11:19 +0200 Subject: [PATCH] Puppet: press-drag with a pin tool places the pin and drags it (#4337) * Puppet: press-drag with a pin tool places the pin and drags it With a Puppet pin tool, a press on the layer's art followed by a drag did nothing: a pin took a click to place and a second press to move. As in After Effects, the pin now goes down where the button does and follows the pointer while it is held. Position and Advanced pins carry the mesh to the release point, Starch and Overlap pins are placed where the drag ends, and a Bend pin (no position) stays where it was placed. puppet.addPin takes a `merge` key so the add and the following puppet.movePin steps are one undo step. A plain click still just adds a pin. Co-Authored-By: Claude Opus 5.5 * Puppet: store a drag-placed Starch/Overlap pin's rest like a click puppet.movePin wrote the raw (deformed-space) point into a Starch or Overlap pin's rest, while puppet.addPin maps a click back to the rest mesh. On a deformed mesh a press-drag and a click at the same point stored different rests. movePin now maps the point through the mesh's current deformation without the pin itself (puppet::overlay_without), as addPin does before the pin exists, so a drag, a click and a later drag of an existing pin all rest under the pointer. Position, Advanced and Bend pins are unchanged. Co-Authored-By: Claude Opus 5.5 * Puppet: decide the pin kind before evaluating a drag's rest mapping Position, Advanced and Bend pin drags no longer evaluate the deformation just to discard it; only Starch and Overlap pins map through the rest mesh. Co-Authored-By: Claude Opus 5.5 * Puppet: place a dragged Starch/Overlap pin on the mesh under the release, solve only its mesh A press-drag that places a Starch or Overlap pin now ends with `puppet.movePin` `place: true`, which moves the pin into the mesh a click at the release point would choose (the first mesh the point is on or beside, deformed without the pin), in the gesture's undo step. It used to stay in the pressed mesh's Deform group, acting on nothing under it. While dragging, the rest point is mapped through the pin's own mesh only (`puppet::overlay_of_pin`), not every mesh of the layer, so each pointer move builds and solves one mesh. Co-Authored-By: Claude Opus 5.5 * Puppet: a dragged Starch/Overlap pin released on unmeshed art meshes it, as a click does `puppet.movePin` with `place` now does what a click at the release point does when that point is on no mesh: on art no mesh covers, it adds a mesh there (with the current mesh options) and moves the pin onto it, resting at the release point, in the drag's undo step. Where a click would place nothing (the art is already a mesh's own), the pin keeps its mesh. Co-Authored-By: Claude Opus 5.5 * Puppet: a Starch/Overlap drag released off the art places it only where a click would The end of a drag that placed a Starch or Overlap pin now asks the same question a click does (`puppet_click_layer`, shared by press, click and release): only when a click at the release point would put a pin on this layer does `puppet.movePin` get `place`. A release on empty canvas used to mesh the unmeshed art nearest the pointer, which a click there never does; the pin now stays on its mesh. Co-Authored-By: Claude Opus 5.5 * Puppet: a Starch/Overlap drag that leaves the mesh its press made removes that mesh The first Starch or Overlap press on unmeshed art makes a mesh for the new pin. When the release puts the pin on another mesh (or a new one on another piece), the press-made mesh was left behind empty: Show Mesh outlined it and the renderer kept rasterizing it. `puppet.addPin` now reports `newMesh`; the viewer keeps that mesh in the gesture and passes it to the release's `puppet.movePin` as `madeMesh`, which removes it in the same edit when the pin was its only pin and the placement is elsewhere. Meshes that existed before the gesture, including empty ones, are never removed. Undo stays one step. Test: puppet_starch_drag_off_unmeshed_art_leaves_no_mesh_behind (two islands: release piece meshed; no Puppet effect at all; a pre-existing empty mesh that must stay). The puppet viewer tests were built and run locally (15 pass; the new test fails with the fix disabled). Clippy and the engine test suite were not run locally; CI is the check for those. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/effects/src/puppet.rs | 22 +- crates/engine/src/cmd/puppet.rs | 144 ++++++++++- crates/engine/src/tests/paint.rs | 52 ++++ crates/ui-egui/src/panels/puppet_tool.rs | 24 ++ crates/ui-egui/src/panels/viewer.rs | 70 +++-- crates/ui-egui/src/panels/viewer/gesture.rs | 6 +- crates/ui-egui/tests/it/ui_viewer.rs | 271 ++++++++++++++++++++ 7 files changed, 556 insertions(+), 33 deletions(-) diff --git a/crates/effects/src/puppet.rs b/crates/effects/src/puppet.rs index 9f3babaf9..2ae61dfb5 100644 --- a/crates/effects/src/puppet.rs +++ b/crates/effects/src/puppet.rs @@ -1127,13 +1127,33 @@ pub fn pin_count(fx: &PropGroup) -> usize { /// The deformed mesh for overlays: mesh, deformed vertices (layer space) per mesh group uid. pub fn overlay(buf: &Buf, params: &Params) -> Vec<(u64, Arc, Vec<[f64; 2]>, Vec)> { + overlay_without(buf, params, None) +} + +/// [`overlay`] deformed as if pin `skip` were not there (it is still listed): the deformation a +/// new pin is placed through, before it exists. +pub fn overlay_without(buf: &Buf, params: &Params, skip: Option) -> Vec<(u64, Arc, Vec<[f64; 2]>, Vec)> { + deformed_meshes(buf, params, skip, |_| true) +} + +/// The [`overlay_without`] entry of the one mesh that holds pin `pin`, deformed as if that pin +/// were not there: only that mesh is built and solved, not the layer's other meshes (a drag +/// updates this on every pointer move). None when no enabled mesh holds an enabled `pin`. +pub fn overlay_of_pin(buf: &Buf, params: &Params, pin: u64) -> Option<(u64, Arc, Vec<[f64; 2]>, Vec)> { + deformed_meshes(buf, params, Some(pin), |m| m.pins.iter().any(|p| p.uid == pin)).into_iter().next() +} + +/// The meshes `keep` picks, built and deformed as if pin `skip` were not there. +fn deformed_meshes(buf: &Buf, params: &Params, skip: Option, keep: impl Fn(&MeshParams) -> bool) -> Vec<(u64, Arc, Vec<[f64; 2]>, Vec)> { let first = original(params); let refine = if first { legacy::rounds(params) } else { refinement_rounds(params) }; parse(params) .into_iter() + .filter(|m| keep(m)) .map(|m| { let mesh = mesh_for(buf, &m); - let def = if first { legacy::solve(&mesh, &m.pins, refine) } else { solve_shared(&mesh, &m.pins, refine).to_vec() }; + let solved: Vec = m.pins.iter().filter(|p| Some(p.uid) != skip).copied().collect(); + let def = if first { legacy::solve(&mesh, &solved, refine) } else { solve_shared(&mesh, &solved, refine).to_vec() }; (m.uid, mesh, def, m.pins) }) .collect() diff --git a/crates/engine/src/cmd/puppet.rs b/crates/engine/src/cmd/puppet.rs index 054be7582..01f8fcd72 100644 --- a/crates/engine/src/cmd/puppet.rs +++ b/crates/engine/src/cmd/puppet.rs @@ -180,7 +180,9 @@ fn add_pin(s: &mut Session, p: &Value) -> Result { PinKind::Overlap => "Add Overlap Pin", _ => "Add Puppet Pin", }; - let (fx, mesh, pin) = s.edit(label, None, |proj, st| { + // `merge`: a press-drag that places the pin and then moves it (`puppet.movePin` with the same + // key) is one undo step, as in After Effects. + let (fx, mesh, pin) = s.edit(label, merge_p(p), |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"))?; @@ -224,7 +226,10 @@ fn add_pin(s: &mut Session, p: &Value) -> Result { 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]]})) + // `newMesh`: this add made the mesh (a press-drag hands it to `puppet.movePin` as `madeMesh`). + Ok( + json!({"effect": fx, "mesh": mesh, "pin": pin, "newMesh": target.is_none(), "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. @@ -340,24 +345,133 @@ fn with_pin(s: &mut Session, p: &Value, cmd: &str, label: &str, f: impl FnOnc }) } +/// The Puppet effect that holds pin `pin` when it is a Starch or Overlap pin (decided from the +/// stored kind, before any deformation is evaluated). +fn resting_pin_effect(s: &Session, cid: ItemId, lid: LayerId, pin: Uid) -> Option { + let fx = s.project.comp(cid)?.layer(lid)?.effects()?; + let owner = fx.groups().filter(|g| puppet::is_puppet(g)).find(|g| g.find_group(pin).is_some())?; + let g = owner.find_group(pin)?; + matches!(PinKind::from_index(g.get("kind").map(|k| k.value.as_enum()).unwrap_or(0)), PinKind::Starch | PinKind::Overlap).then_some(owner.uid) +} + +/// Where a Starch or Overlap pin dragged to `to` (effect space) rests: the point of its mesh's +/// rest shape that is under `to` as the mesh is deformed without the pin (a Starch pin stiffens +/// the solve), as `puppet.addPin` maps a click before the pin exists, so a drag and a click at +/// one point store the same rest. Only the pin's own mesh is built and solved: a drag asks this on +/// every pointer move, and a layer can have many meshes. None for any other pin (Position, +/// Advanced, Bend), or when there is no mesh to map through. +pub fn dragged_rest(s: &Session, cid: ItemId, lid: LayerId, pin: Uid, t: Tick, to: [f64; 2]) -> Option<[f64; 2]> { + let fu = resting_pin_effect(s, cid, lid, pin)?; + let (buf, params) = puppet_eval(s, cid, lid, fu, t)?; + let (_, mesh, def, _) = puppet::overlay_of_pin(&buf, ¶ms, pin)?; + (!mesh.tris.is_empty()).then(|| puppet::unmap(&mesh, &def, to)) +} + +/// Where `puppet.movePin` with `place` puts a new Starch or Overlap pin. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Placement { + /// On this existing mesh, resting at this point. + Mesh(Uid, [f64; 2]), + /// On a new mesh of this Puppet effect for the art under the release point, resting there. + NewMesh(Uid), +} + +/// Where a new Starch or Overlap pin that a drag placed goes when the drag ends at `to` (effect +/// space), as a click at `to` would place it: on the first of its Puppet effect's meshes that `to` +/// is on or beside (deformed without the pin), at the rest point under `to`; else, on art no mesh +/// covers, on a new mesh there. None for any other pin, or where a click would place nothing (the +/// art there is a mesh's own): the pin then keeps its mesh. +pub fn placed_rest(s: &Session, cid: ItemId, lid: LayerId, pin: Uid, t: Tick, to: [f64; 2]) -> Option { + let fu = resting_pin_effect(s, cid, lid, pin)?; + let (buf, params) = puppet_eval(s, cid, lid, fu, t)?; + match puppet::overlay_without(&buf, ¶ms, Some(pin)).into_iter().find(|(_, mesh, def, _)| on_mesh(mesh, def, to)) { + Some((uid, mesh, def, _)) => Some(Placement::Mesh(uid, puppet::unmap(&mesh, &def, to))), + None => (!repeats_mesh(&buf, ¶ms, to)).then_some(Placement::NewMesh(fu)), + } +} + fn move_pin(s: &mut Session, p: &Value) -> Result { let cmd = "puppet.movePin"; let to = pt(p.get("position")).ok_or_else(|| bad(cmd, "missing `position` [x, y] (effect space)"))?; - with_pin(s, p, cmd, "Move Puppet Pin", |g, lt| { + 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)?; + // `place`: the end of the drag that placed this pin. A Starch or Overlap pin goes where a click + // at `to` would put it (the mesh there, or a new one on unmeshed art), not on the pressed mesh. + let placed = if super::b_p(p, "place").unwrap_or(false) { placed_rest(s, cid, lid, uid, t, to) } else { None }; + let rest = match placed { + Some(Placement::Mesh(_, r)) => r, + Some(Placement::NewMesh(_)) => to, + None => dragged_rest(s, cid, lid, uid, t, to).unwrap_or(to), + }; + // `madeMesh`: the mesh the press that placed this pin made for it. When the placement takes the + // pin off it, that mesh is left with no pins and is removed in the same edit (a click at the + // release point would never have made it). A mesh that was there before the gesture stays. + let made = if placed.is_some() { p.get("madeMesh").and_then(Value::as_u64) } else { None }; + let opts = MeshOpts { density: s.state.puppet.density, expansion: s.state.puppet.expansion, triangles: s.state.puppet.triangles }; + s.edit("Move Puppet Pin", merge_p(p), |proj, st| { + let mut next = proj.next_id; + let l = layer_mut(proj, cid, lid)?; + // The made mesh goes when this pin is its only one and the placement is on another mesh. + let drop = made.filter(|m| { + !matches!(placed, Some(Placement::Mesh(to, _)) if to == *m) + && l.props.find_group(*m).is_some_and(|g| g.match_id == "mesh" && puppet::pins(g).map(|g| g.uid).eq([uid])) + }); + let mesh = match placed { + Some(Placement::Mesh(m, _)) => Some(m), + Some(Placement::NewMesh(fu)) => { + let pg = l.props.sub_mut("effects").and_then(|fx| fx.find_group_mut(fu)).ok_or_else(|| bad(cmd, "Puppet effect gone"))?; + // Named as if the dropped mesh were already gone, as a click would name it. + let n = puppet::meshes(pg).filter(|g| Some(g.uid) != drop).count(); + let g = puppet::mesh_group(&mut Ids(&mut next), &format!("Mesh {}", n + 1), to, &opts); + let u = g.uid; + pg.children.push(g.into()); + Some(u) + } + None => None, + }; + if let Some(m) = mesh { + rehome_pin(&mut l.props, uid, m).ok_or_else(|| bad(cmd, "pin or mesh gone"))?; + } + if let Some(m) = drop + && let Some(parent) = l.props.parent_of_mut(m) + { + parent.children.retain(|c| c.uid() != m); + } + let g = l.props.find_group_mut(uid).ok_or_else(|| bad(cmd, "pin gone"))?; 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); + if kind.moves() { + pos.set_value_at(lt, KV::Vec2(to)); + } else { + // Starch and Overlap pins sit on the rest mesh: moving them moves their region, to the + // rest point under `to` (where `puppet.addPin` would place one). + pos.set_value_at(lt, KV::Vec2(rest)); + if let Some(r) = g.get_mut("rest") { + r.value = KV::Vec2(rest); + } } + proj.next_id = next; + st.selected_props = vec![(lid, uid)]; Ok(()) })?; Ok(Value::Null) } +/// Move pin group `pin` into the Deform group of mesh group `mesh` (a no-op when it is there). +fn rehome_pin(props: &mut PropGroup, pin: Uid, mesh: Uid) -> Option<()> { + if props.find_group(mesh)?.sub("deform")?.groups().any(|g| g.uid == pin) { + return Some(()); + } + let from = props.parent_of_mut(pin)?; + let i = from.children.iter().position(|n| n.uid() == pin)?; + let node = from.children.remove(i); + props.find_group_mut(mesh)?.sub_mut("deform")?.children.push(node); + Some(()) +} + fn set_pin(s: &mut Session, p: &Value) -> Result { let cmd = "puppet.setPin"; let fields: Vec<(&str, KV)> = [("scale", "scale"), ("rotation", "rotation"), ("amount", "amount"), ("extent", "extent"), ("inFront", "in_front")] @@ -696,11 +810,19 @@ pub fn specs() -> Vec { "Add Puppet Pin", [], None, - "{layer?, kind?: position|advanced|bend|starch|overlap, position: [x,y] (effect space), time? (s) | frame?, mesh?: uid, newMesh?, density?, expansion?, triangles?}", + "{layer?, kind?: position|advanced|bend|starch|overlap, position: [x,y] (effect space), time? (s) | frame?, mesh?: uid, newMesh?, density?, expansion?, triangles?, merge?}", 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.movePin", + "Move Puppet Pin", + [], + None, + "{layer?, pin: uid | name, position: [x,y], time? | frame?, merge?, place?, madeMesh?: uid (the mesh the press that placed the pin made; removed when the placement leaves it empty)}", + has_comp, + move_pin + ), cmd!( "puppet.setPin", "Edit Puppet Pin", diff --git a/crates/engine/src/tests/paint.rs b/crates/engine/src/tests/paint.rs index ecabc0f7e..462d68373 100644 --- a/crates/engine/src/tests/paint.rs +++ b/crates/engine/src/tests/paint.rs @@ -679,3 +679,55 @@ fn a_puppet_rig_saved_before_the_solver_version_keeps_its_look() { assert_eq!(version(&again), Some(SOLVER_ORIGINAL)); assert_eq!(deformed(&mut again, 1.0), first); } + +/// A drag maps its release point through the rest mesh only for Starch and Overlap pins; the other +/// kinds are decided from the stored kind, with no deformation evaluated. +#[test] +fn dragged_rest_maps_only_starch_and_overlap_pins() { + 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 (cid, t) = (s.active_comp_id().unwrap(), Tick::from_seconds_f64(0.0)); + let lid = effectcraft_project::LayerId(id); + for (kind, maps) in [("position", false), ("advanced", false), ("bend", false), ("starch", true), ("overlap", true)] { + let pin = s.execute("puppet.addPin", json!({"layer": id, "kind": kind, "position": [50, 30]})).unwrap()["pin"].as_u64().unwrap(); + let rest = crate::commands::puppet::dragged_rest(&s, cid, lid, pin, t, [60.0, 30.0]); + assert_eq!(rest.is_some(), maps, "{kind}: {rest:?}"); + if let Some(r) = rest { + assert!((r[0] - 60.0).abs() < 1.5 && (r[1] - 30.0).abs() < 1.5, "{kind}: undeformed mesh maps to itself: {r:?}"); + } + } +} + +/// A Starch or Overlap pin's drag maps the pointer through its own mesh only (it is asked on every +/// pointer move), and the layer's other meshes do not change where the pin rests: the same point +/// as building and deforming every mesh without the pin. +#[test] +fn dragged_rest_solves_only_the_pins_own_mesh() { + use effectcraft_effects::puppet; + let (mut s, id) = setup(); + for x in [[0, 30], [60, 100]] { + s.execute("mask.new", json!({"layer": id, "vertices": [[x[0], 0], [x[1], 0], [x[1], 60], [x[0], 60]], "closed": true})).unwrap(); + } + // Two meshes, each bent by its own pins. + for (at, to) in [([10, 30], None), ([25, 30], Some([35, 45])), ([80, 30], None), ([90, 50], Some([110, 40]))] { + let pin = s.execute("puppet.addPin", json!({"layer": id, "position": at})).unwrap()["pin"].as_u64().unwrap(); + if let Some(to) = to { + s.execute("puppet.movePin", json!({"layer": id, "pin": pin, "position": to})).unwrap(); + } + } + assert_eq!(mesh_count(&mut s, id), 2); + let pin = s.execute("puppet.addPin", json!({"layer": id, "kind": "starch", "position": [15, 30]})).unwrap(); + let (starch, owner, fu) = (pin["pin"].as_u64().unwrap(), pin["mesh"].as_u64().unwrap(), pin["effect"].as_u64().unwrap()); + let (cid, t, lid) = (s.active_comp_id().unwrap(), Tick::from_seconds_f64(0.0), effectcraft_project::LayerId(id)); + let to = [22.0, 38.0]; + let rest = crate::commands::puppet::dragged_rest(&s, cid, lid, starch, t, to).unwrap(); + let (buf, params) = crate::commands::puppet::puppet_eval(&s, cid, lid, fu, t).unwrap(); + let all = puppet::overlay_without(&buf, ¶ms, Some(starch)); + assert_eq!(all.len(), 2); + let (_, mesh, def, _) = all.iter().find(|(m, ..)| *m == owner).unwrap(); + assert_eq!(rest, puppet::unmap(mesh, def, to), "the same rest as through every mesh"); + assert!((rest[0] - to[0]).hypot(rest[1] - to[1]) > 0.5, "the bend moves the rest off the pointer: {rest:?}"); + let one = puppet::overlay_of_pin(&buf, ¶ms, starch).unwrap(); + assert_eq!((one.0, &one.2), (owner, def), "only the pin's own mesh, deformed the same"); +} diff --git a/crates/ui-egui/src/panels/puppet_tool.rs b/crates/ui-egui/src/panels/puppet_tool.rs index ac2186bf8..79d286f9b 100644 --- a/crates/ui-egui/src/panels/puppet_tool.rs +++ b/crates/ui-egui/src/panels/puppet_tool.rs @@ -104,6 +104,30 @@ pub fn takes_pin(app: &EffectcraftApp, ectx: &EvalCtx, layer: &Layer, cpt: [f64; effectcraft_engine::commands::puppet::places_pin(&app.session, ectx.comp_id, layer.id, [p.x, p.y], ectx.time) } +/// Add a `kind` pin to `layer` at comp point `cpt` (`puppet.addPin`), selecting it and keeping +/// its Position in view. `merge` folds the add into the gesture's undo step: a press-drag that +/// places the pin and then moves it is one step. Returns the new pin's uid and, when the add made +/// a mesh for it, that mesh's uid; `None` (with the error in the status bar) when no pin was placed. +pub fn add_pin(app: &mut EffectcraftApp, ectx: &EvalCtx, layer: &Layer, kind: &str, cpt: [f64; 2], merge: Option<&str>) -> Option<(u64, Option)> { + let inv = fx2c(ectx, layer).inverse()?; + let lp = inv.apply(gv2(cpt[0], cpt[1])); + let mut q = serde_json::json!({"layer": layer.id.0, "kind": kind, "position": [lp.x, lp.y]}); + if let Some(m) = merge { + q["merge"] = serde_json::json!(m); + } + match app.session.execute("puppet.addPin", q) { + Ok(r) => { + let pin = r["pin"].as_u64()?; + reveal_pin(app, layer.id, pin); + Some((pin, r["mesh"].as_u64().filter(|_| r["newMesh"].as_bool().unwrap_or(false)))) + } + Err(e) => { + app.ui.status = e.to_string(); + None + } + } +} + /// Keep a pin's keyframed Position in view in the Timeline after placing, moving or recording the /// pin in the viewer (#273). pub fn reveal_pin(app: &mut EffectcraftApp, layer: LayerId, pin: u64) { diff --git a/crates/ui-egui/src/panels/viewer.rs b/crates/ui-egui/src/panels/viewer.rs index 117d7212f..f1a52282c 100644 --- a/crates/ui-egui/src/panels/viewer.rs +++ b/crates/ui-egui/src/panels/viewer.rs @@ -1190,6 +1190,13 @@ fn led_by_a_moved_ancestor(comp: &Comp, layers: &[MoveLayer]) -> Vec { /// Starts the gesture a new primary drag begins (pan, move, scale, a handle, a vertex, a marquee), /// unless an overlay claimed the press. +/// The Puppet layer a pin tool's click at comp point `cpt` puts a pin on: the one whose mesh is +/// under it, else one whose art is under it and takes a pin there. A press, a click and the end of +/// a drag that placed a pin all ask this, so they agree on where a pin goes. +fn puppet_click_layer(app: &EffectcraftApp, ectx: &EvalCtx, layers: &[(&Layer, super::puppet_tool::Overlay)], cpt: [f64; 2]) -> Option { + super::puppet_tool::target(ectx, layers, cpt, |l| layers_at(ectx, cpt).any(|h| h.id == l.id) && super::puppet_tool::takes_pin(app, ectx, l, cpt)) +} + fn phase_dragstart(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, resp: &egui::Response, v: &mut Vw<'_>) { let comp_rect = v.comp_rect; let zoom = v.zoom; @@ -1218,9 +1225,7 @@ fn phase_dragstart(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, if puppet_layers.is_empty() { return pick(app, ectx, cpt, false); } - super::puppet_tool::target(ectx, &puppet_layers, cpt, |l| { - layers_at(ectx, cpt).any(|h| h.id == l.id) && super::puppet_tool::takes_pin(app, ectx, l, cpt) - }) + puppet_click_layer(app, ectx, &puppet_layers, cpt) }; if resp.drag_started() && !text_owns @@ -1298,7 +1303,24 @@ fn phase_dragstart(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, t if t.puppet_kind().is_some() && super::puppet_tool::hit(&pin_hits, press).is_none() => { // Off the pins: Alt or a press outside the art drags a marquee that selects pins. Asked // of where the button went down: the pointer may be over the art by the time this is a drag. - (mods.alt || puppet_layer(app, map.to_comp(press)).is_none()).then_some(Gesture::PinMarquee { start: press }) + let at = map.to_comp(press); + match if mods.alt { None } else { puppet_layer(app, at) } { + None => Some(Gesture::PinMarquee { start: press }), + // ⌘/Ctrl records an existing pin; on the art it places nothing. + Some(_) if mods.command => None, + // On the art (After Effects): the pin goes down where the button did and follows + // the pointer while it is held, so placing and moving it is one gesture and one + // undo step (`merge`). Starch and Overlap pins are placed where the drag ends, on the + // mesh there; a Bend pin has no position to drag and stays where it was placed. + Some(l) => comp.layer(l).zip(t.puppet_kind()).and_then(|(l, kind)| { + // A key left over from the previous drag would fold this pin into that drag's undo step. + app.session.history.merge_key = None; + let merge = drag_merge_key(ui); + let (pin, made_mesh) = super::puppet_tool::add_pin(app, ectx, l, kind, at, Some(&merge))?; + let inv = fx2c(ectx, l).inverse()?; + (kind != "bend").then_some(Gesture::PuppetPin { layer: l.id, pin, inv, place: matches!(kind, "starch" | "overlap"), made_mesh }) + }), + } } t if t.puppet_kind().is_some() => super::puppet_tool::hit(&pin_hits, press).and_then(|(h, part)| { use super::puppet_tool::PinPart; @@ -1327,7 +1349,7 @@ fn phase_dragstart(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, }; return Some(Gesture::PuppetRecord { layer: h.layer, pin: h.pin, others, inv, began, cti: time, samples: vec![(0.0, [lp.x, lp.y])] }); } - Some(Gesture::PuppetPin { layer: h.layer, pin: h.pin, inv }) + Some(Gesture::PuppetPin { layer: h.layer, pin: h.pin, inv, place: false, made_mesh: None }) }), // The cursor variants turn about / pan at / dolly towards the point under the press; // the engine resolves it on the first step and the drag keeps it (`pivot`). @@ -1704,7 +1726,7 @@ fn phase_drag(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, resp: app.ui.status = e.to_string(); } } - Gesture::PuppetPin { layer, pin, inv } => { + Gesture::PuppetPin { layer, pin, inv, .. } => { let lp = inv.apply(gv2(cpt[0], cpt[1])); if let Err(e) = app.session.execute("puppet.movePin", json!({"layer": layer.0, "pin": pin, "position": [lp.x, lp.y], "merge": merge})) { app.ui.status = e.to_string(); @@ -1746,6 +1768,7 @@ fn phase_stopped(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, re let gid = v.gid; let vertex_hits = std::mem::take(&mut v.vertex_hits); let pin_hits = std::mem::take(&mut v.pin_hits); + let puppet_layers = std::mem::take(&mut v.puppet_layers); let gesture = v.gesture.clone(); let comp = v.comp; if resp.drag_stopped() { @@ -1780,7 +1803,23 @@ fn phase_stopped(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, re Err(e) => app.ui.status = e.to_string(), } } - Gesture::PuppetPin { layer, pin, .. } => super::puppet_tool::reveal_pin(app, layer, pin), + Gesture::PuppetPin { layer, pin, inv, place, made_mesh } => { + let c = map.to_comp(pos); + // The new pin goes where a click at the release point would put one (the mesh + // there, or a new mesh on unmeshed art), in the gesture's undo step. Where a click + // would place nothing on this layer (off the art, on another layer), the pin + // stays on its mesh. A mesh the press made for the pin goes if the pin leaves it + // empty (`madeMesh`): a click at the release point would not have made it. + if place && puppet_click_layer(app, ectx, &puppet_layers, c) == Some(layer) { + let lp = inv.apply(gv2(c[0], c[1])); + let q = + json!({"layer": layer.0, "pin": pin, "position": [lp.x, lp.y], "place": true, "madeMesh": made_mesh, "merge": drag_merge_key(ui)}); + if let Err(e) = app.session.execute("puppet.movePin", q) { + app.ui.status = e.to_string(); + } + } + super::puppet_tool::reveal_pin(app, layer, pin) + } Gesture::ObjectMatteBox { start } => super::object_matte_tool::apply(app, ectx, &map, start, Some(pos), mods.shift), Gesture::Create { tool, start } => { let end = map.to_comp(pos); @@ -1831,6 +1870,7 @@ fn phase_stopped(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, re } v.vertex_hits = vertex_hits; v.pin_hits = pin_hits; + v.puppet_layers = puppet_layers; } /// Acts on a click in the viewer for the active tool (select, zoom, add or delete vertices), @@ -1861,9 +1901,7 @@ fn phase_clicked(app: &mut EffectcraftApp, ectx: &EvalCtx, resp: &egui::Response if puppet_layers.is_empty() { return pick(app, ectx, cpt, false); } - super::puppet_tool::target(ectx, &puppet_layers, cpt, |l| { - layers_at(ectx, cpt).any(|h| h.id == l.id) && super::puppet_tool::takes_pin(app, ectx, l, cpt) - }) + puppet_click_layer(app, ectx, &puppet_layers, cpt) }; // A press an overlay passed on in the pass before (FORWARDED_PRIMARY) is a click here. let pass = ctx.cumulative_pass_nr(); @@ -1934,17 +1972,9 @@ fn phase_clicked(app: &mut EffectcraftApp, ectx: &EvalCtx, resp: &egui::Response // Click selects the pin; Shift-click adds or removes it. let _ = app.session.execute("puppet.selectPins", json!({"layer": h.layer.0, "pins": [h.pin], "toggle": mods.shift})); } else if let Some(l) = puppet_layer(app, cpt).and_then(|l| comp.layer(l)) - && let Some(inv) = fx2c(ectx, l).inverse() + && let Some(kind) = t.puppet_kind() { - let lp = inv.apply(gv2(cpt[0], cpt[1])); - match app.session.execute("puppet.addPin", json!({"layer": l.id.0, "kind": t.puppet_kind(), "position": [lp.x, lp.y]})) { - Ok(r) => { - if let Some(pin) = r["pin"].as_u64() { - super::puppet_tool::reveal_pin(app, l.id, pin); - } - } - Err(e) => app.ui.status = e.to_string(), - } + super::puppet_tool::add_pin(app, ectx, l, kind, cpt, None); } } Tool::Selection if vertex_at(pos, false).is_some() => { diff --git a/crates/ui-egui/src/panels/viewer/gesture.rs b/crates/ui-egui/src/panels/viewer/gesture.rs index c350f2d23..9da6c3581 100644 --- a/crates/ui-egui/src/panels/viewer/gesture.rs +++ b/crates/ui-egui/src/panels/viewer/gesture.rs @@ -93,11 +93,15 @@ pub(super) enum Gesture { vertex: [f64; 2], inv: Mat3, }, - /// Dragging a Puppet pin (comp → layer matrix inverse). + /// Dragging a Puppet pin (comp → layer matrix inverse). `place`: a Starch or Overlap pin this + /// drag placed, which goes on the mesh under the release point (as a click there would). + /// `made_mesh`: the mesh the press made for that pin, removed if the pin leaves it empty. PuppetPin { layer: LayerId, pin: u64, inv: Mat3, + place: bool, + made_mesh: Option, }, /// Rotating an Advanced / Bend pin by its ring: the pin's screen centre, the pointer's last /// angle (radians) and the rotation so far (°, accumulated so it can pass a full turn). diff --git a/crates/ui-egui/tests/it/ui_viewer.rs b/crates/ui-egui/tests/it/ui_viewer.rs index a9b1e4919..8f042a616 100644 --- a/crates/ui-egui/tests/it/ui_viewer.rs +++ b/crates/ui-egui/tests/it/ui_viewer.rs @@ -1973,6 +1973,277 @@ fn puppet_press_where_the_deformed_layer_is_empty_is_a_marquee_not_a_copy() { assert_eq!(rig(&mut h), (1, 3)); } +/// A Box with no Plate behind it, the given Puppet tool active: (harness, the Box's layer id). +fn puppet_tool_harness(tool: Tool) -> (Harness<'static, EffectcraftApp>, u64) { + let mut h = harness(); + let s = &mut h.state_mut().session; + s.execute("edit.clear", json!({"layers": ["Plate"]})).unwrap(); + s.execute("layer.select", json!({"layers": ["Box"]})).unwrap(); + let id = s.state.selected_layers[0].0; + h.state_mut().ui.tool = tool; + h.run_steps(2); + (h, id) +} + +/// The Box's pins (puppet.info): (kind, rest, position) each. +fn puppet_pins(h: &mut Harness<'_, EffectcraftApp>, layer: u64) -> Vec<(String, [f64; 2], [f64; 2])> { + let info = h.state_mut().session.execute("puppet.info", json!({"layer": layer})).unwrap(); + let xy = |v: &serde_json::Value| [v[0].as_f64().unwrap_or(f64::NAN), v[1].as_f64().unwrap_or(f64::NAN)]; + info["meshes"] + .as_array() + .unwrap() + .iter() + .flat_map(|m| m["pins"].as_array().unwrap().clone()) + .map(|p| (p["kind"].as_str().unwrap().to_owned(), xy(&p["rest"]), xy(&p["position"]))) + .collect() +} + +/// A press on the art with a Puppet pin tool places the pin and, while the button stays down, +/// drags it (After Effects): one gesture, one undo step. It used to take a click to place the +/// pin and a second press to move it. Position and Advanced pins carry the mesh to the release +/// point; Starch and Overlap pins are placed there; a Bend pin (no position) stays where the +/// button went down. +#[test] +fn puppet_press_drag_on_the_art_places_and_drags_one_pin() { + let near = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).abs() < 1.5 && (a[1] - b[1]).abs() < 1.5; + for (tool, kind, label) in [ + (Tool::Puppet, "position", "Add Puppet Pin"), + (Tool::PuppetAdvanced, "advanced", "Add Puppet Pin"), + (Tool::PuppetStarch, "starch", "Add Starch Pin"), + (Tool::PuppetOverlap, "overlap", "Add Overlap Pin"), + (Tool::PuppetBend, "bend", "Add Puppet Pin"), + ] { + let (mut h, id) = puppet_tool_harness(tool); + let undo = h.state().session.history.undo.len(); + // The Box's layer (20, 20) is comp (300, 160); the drag ends on layer (60, 60). + let (from, to) = (screen(&h, [300.0, 160.0]), screen(&h, [340.0, 200.0])); + hold_drag(&mut h, from, to, Default::default()); + let pins = puppet_pins(&mut h, id); + assert_eq!(pins.len(), 1, "{kind}: one pin, placed on the press: {pins:?}"); + let (k, rest, position) = pins[0].clone(); + assert_eq!(k, kind); + match kind { + "position" | "advanced" => { + assert!(near(rest, [20.0, 20.0]), "{kind}: the pin holds the pressed point: {rest:?}"); + assert!(near(position, [60.0, 60.0]), "{kind}: and carried it to the release point: {position:?}"); + } + "bend" => assert!(near(rest, [20.0, 20.0]), "{kind}: stays where it was placed: {rest:?}"), + _ => assert!(near(rest, [60.0, 60.0]) && near(position, [60.0, 60.0]), "{kind}: placed at the release point: {rest:?} {position:?}"), + } + let pin = placed_pin(&h); + assert_eq!(h.state().session.state.selected_props, vec![(LayerId(id), pin)], "{kind}: the new pin is selected"); + let hist = &h.state().session.history; + assert_eq!(hist.undo.len(), undo + 1, "{kind}: placing and dragging is one undo step"); + assert_eq!(hist.undo.last().map(|(l, _)| l.as_str()), Some(label)); + // Undo takes the whole gesture back. + h.state_mut().session.execute("edit.undo", json!({})).unwrap(); + assert!(puppet_pins(&mut h, id).is_empty(), "{kind}: undo removes the pin"); + } +} + +/// A plain click with a Puppet pin tool still just adds a pin where it is clicked (one undo step), +/// and a second press-drag is its own undo step. +#[test] +fn puppet_click_adds_a_pin_at_the_click_and_the_next_drag_is_its_own_step() { + let near = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).abs() < 1.5 && (a[1] - b[1]).abs() < 1.5; + let (mut h, id) = puppet_tool_harness(Tool::Puppet); + let undo = h.state().session.history.undo.len(); + let at = screen(&h, [300.0, 160.0]); + click(&mut h, at); + let pins = puppet_pins(&mut h, id); + assert_eq!(pins.len(), 1, "{pins:?}"); + assert!(near(pins[0].1, [20.0, 20.0]) && near(pins[0].2, [20.0, 20.0]), "at the click, nothing moved: {pins:?}"); + assert_eq!(h.state().session.history.undo.len(), undo + 1); + // A press-drag elsewhere on the art: a second pin, a second step; the first pin stays put. + let (from, to) = (screen(&h, [350.0, 200.0]), screen(&h, [330.0, 180.0])); + hold_drag(&mut h, from, to, Default::default()); + let pins = puppet_pins(&mut h, id); + assert_eq!(pins.len(), 2, "{pins:?}"); + assert!(near(pins[0].2, [20.0, 20.0]), "the first pin stays: {pins:?}"); + assert!(near(pins[1].1, [70.0, 60.0]) && near(pins[1].2, [50.0, 40.0]), "the second followed the drag: {pins:?}"); + assert_eq!(h.state().session.history.undo.len(), undo + 2); + h.state_mut().session.execute("edit.undo", json!({})).unwrap(); + assert_eq!(puppet_pins(&mut h, id).len(), 1, "undo takes back the drag's pin only"); +} + +/// On a deformed mesh a press-drag that places a Starch or Overlap pin stores the same rest point +/// as a click at its release point: the point of the rest mesh under the pointer. The drag used to +/// store the release point itself (deformed space), off the art's own point by the deformation. +#[test] +fn puppet_starch_drag_on_a_deformed_mesh_rests_where_a_click_would() { + let near = |a: [f64; 2], b: [f64; 2], tol: f64| (a[0] - b[0]).abs() < tol && (a[1] - b[1]).abs() < tol; + for tool in [Tool::PuppetStarch, Tool::PuppetOverlap] { + let (mut h, id) = puppet_tool_harness(tool); + let s = &mut h.state_mut().session; + s.execute("puppet.addPin", json!({"layer": id, "position": [10, 40]})).unwrap(); + let b = s.execute("puppet.addPin", json!({"layer": id, "position": [70, 40]})).unwrap()["pin"].as_u64().unwrap(); + // Stretch the Box to the right (not a plain shift, so a Starch pin's stiffness changes the + // deformation): comp (380, 180), layer (100, 40), is on the stretched art. + s.execute("puppet.movePin", json!({"layer": id, "pin": b, "position": [130, 40]})).unwrap(); + h.run_steps(3); + let rest_of_new = |h: &mut Harness<'_, EffectcraftApp>| { + let pins = puppet_pins(h, id); + assert_eq!(pins.len(), 3, "{tool:?}: one new pin: {pins:?}"); + pins[2].1 + }; + let release = screen(&h, [380.0, 180.0]); + click(&mut h, release); + let clicked = rest_of_new(&mut h); + h.state_mut().session.execute("edit.undo", json!({})).unwrap(); + h.run_steps(2); + let press = screen(&h, [360.0, 180.0]); + hold_drag(&mut h, press, release, Default::default()); + let dragged = rest_of_new(&mut h); + assert!(near(dragged, clicked, 0.25), "{tool:?}: the drag rests where the click does: {dragged:?} vs {clicked:?}"); + assert!(!near(dragged, [100.0, 40.0], 1.5), "{tool:?}: not at the deformed release point: {dragged:?}"); + } +} + +/// On a layer cut into two pieces, each with its own mesh, a press-drag with the Starch or Overlap +/// tool from the first piece to the second puts the new pin on the second piece's mesh, where a +/// click at the release point would. It used to stay in the first mesh, which is not under it, so +/// it acted on nothing there. Placing it is still one undo step. +#[test] +fn puppet_starch_drag_onto_another_mesh_places_the_pin_on_that_mesh() { + let near = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).abs() < 1.5 && (a[1] - b[1]).abs() < 1.5; + for (tool, kind) in [(Tool::PuppetStarch, "starch"), (Tool::PuppetOverlap, "overlap")] { + let (mut h, id) = puppet_tool_harness(tool); + let s = &mut h.state_mut().session; + for x in [[0, 25], [55, 80]] { + s.execute("mask.new", json!({"layer": id, "vertices": [[x[0], 0], [x[1], 0], [x[1], 80], [x[0], 80]], "closed": true})).unwrap(); + } + s.execute("puppet.addPin", json!({"layer": id, "position": [12, 40]})).unwrap(); + s.execute("puppet.addPin", json!({"layer": id, "position": [68, 40]})).unwrap(); + h.run_steps(3); + let undo = h.state().session.history.undo.len(); + // The Box's layer (0, 0) is comp (280, 140): press on the left piece, release on the right + // one, beyond the left mesh's reach. + let (from, to) = (screen(&h, [292.0, 155.0]), screen(&h, [348.0, 205.0])); + hold_drag(&mut h, from, to, Default::default()); + let info = h.state_mut().session.execute("puppet.info", json!({"layer": id})).unwrap(); + let pins = |m: usize| info["meshes"][m]["pins"].as_array().unwrap().clone(); + let kinds = |m: usize| pins(m).iter().map(|p| p["kind"].as_str().unwrap().to_owned()).collect::>(); + assert_eq!(kinds(0), ["position"], "{kind}: nothing added to the pressed piece's mesh"); + assert_eq!(kinds(1), ["position", kind], "{kind}: the pin is on the released-on piece's mesh"); + let rest = &pins(1)[1]["rest"]; + let rest = [rest[0].as_f64().unwrap(), rest[1].as_f64().unwrap()]; + assert!(near(rest, [68.0, 65.0]), "{kind}: at the release point: {rest:?}"); + assert_eq!(h.state().session.history.undo.len(), undo + 1, "{kind}: one undo step"); + h.state_mut().session.execute("edit.undo", json!({})).unwrap(); + assert_eq!(puppet_pins(&mut h, id).len(), 2, "{kind}: undo takes the whole gesture back"); + } +} + +/// A press-drag with the Starch or Overlap tool from a meshed piece that ends on a piece with no +/// mesh does what a click there does: the piece gets its own mesh, and the pin rests on it at the +/// release point. The pin used to stay on the pressed piece's mesh, acting on nothing under it. +/// Still one undo step, which takes the new mesh back too. +#[test] +fn puppet_starch_drag_onto_unmeshed_art_meshes_it() { + let near = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).abs() < 1.5 && (a[1] - b[1]).abs() < 1.5; + for (tool, kind) in [(Tool::PuppetStarch, "starch"), (Tool::PuppetOverlap, "overlap")] { + let (mut h, id) = puppet_tool_harness(tool); + let s = &mut h.state_mut().session; + for x in [[0, 25], [55, 80]] { + s.execute("mask.new", json!({"layer": id, "vertices": [[x[0], 0], [x[1], 0], [x[1], 80], [x[0], 80]], "closed": true})).unwrap(); + } + // Only the left piece has a mesh. + s.execute("puppet.addPin", json!({"layer": id, "position": [12, 40]})).unwrap(); + h.run_steps(3); + let undo = h.state().session.history.undo.len(); + let (from, to) = (screen(&h, [292.0, 155.0]), screen(&h, [348.0, 205.0])); + hold_drag(&mut h, from, to, Default::default()); + let info = h.state_mut().session.execute("puppet.info", json!({"layer": id})).unwrap(); + let meshes = info["meshes"].as_array().unwrap().clone(); + assert_eq!(meshes.len(), 2, "{kind}: the released-on piece gets a mesh: {info}"); + let kinds = |m: usize| meshes[m]["pins"].as_array().unwrap().iter().map(|p| p["kind"].as_str().unwrap().to_owned()).collect::>(); + assert_eq!(kinds(0), ["position"], "{kind}: nothing added to the pressed piece's mesh"); + assert_eq!(kinds(1), [kind], "{kind}: the pin is on the new mesh"); + let rest = &meshes[1]["pins"][0]["rest"]; + let rest = [rest[0].as_f64().unwrap(), rest[1].as_f64().unwrap()]; + assert!(near(rest, [68.0, 65.0]), "{kind}: at the release point: {rest:?}"); + assert_eq!(h.state().session.history.undo.len(), undo + 1, "{kind}: one undo step"); + h.state_mut().session.execute("edit.undo", json!({})).unwrap(); + let info = h.state_mut().session.execute("puppet.info", json!({"layer": id})).unwrap(); + assert_eq!(info["meshes"].as_array().unwrap().len(), 1, "{kind}: undo takes the new mesh back"); + assert_eq!(puppet_pins(&mut h, id).len(), 1, "{kind}: and the pin"); + } +} + +/// A press-drag with the Starch or Overlap tool that ends off the art, where a click places +/// nothing, adds no mesh: the pin stays on the pressed piece's mesh. The release used to mesh the +/// unmeshed art nearest the pointer, which a click there never does. Still one undo step. +#[test] +fn puppet_starch_drag_released_off_the_art_adds_no_mesh() { + for (tool, kind) in [(Tool::PuppetStarch, "starch"), (Tool::PuppetOverlap, "overlap")] { + let (mut h, id) = puppet_tool_harness(tool); + let s = &mut h.state_mut().session; + for x in [[0, 25], [55, 80]] { + s.execute("mask.new", json!({"layer": id, "vertices": [[x[0], 0], [x[1], 0], [x[1], 80], [x[0], 80]], "closed": true})).unwrap(); + } + // Only the left piece has a mesh; the right piece is the unmeshed art nearest the release. + s.execute("puppet.addPin", json!({"layer": id, "position": [12, 40]})).unwrap(); + h.run_steps(3); + let undo = h.state().session.history.undo.len(); + // Released right of the Box (layer (130, 40)), on empty canvas. + let (from, to) = (screen(&h, [292.0, 155.0]), screen(&h, [410.0, 180.0])); + hold_drag(&mut h, from, to, Default::default()); + let info = h.state_mut().session.execute("puppet.info", json!({"layer": id})).unwrap(); + let meshes = info["meshes"].as_array().unwrap().clone(); + assert_eq!(meshes.len(), 1, "{kind}: a release off the art makes no mesh: {info}"); + let kinds: Vec = meshes[0]["pins"].as_array().unwrap().iter().map(|p| p["kind"].as_str().unwrap().to_owned()).collect(); + assert_eq!(kinds, ["position", kind], "{kind}: the pin stays on the pressed piece's mesh"); + assert_eq!(h.state().session.history.undo.len(), undo + 1, "{kind}: one undo step"); + } +} + +/// The first Starch or Overlap press-drag on a piece with no mesh makes a mesh there for the pin; +/// when the release puts the pin on another piece, that mesh is removed in the same undo step, as a +/// click at the release point never makes it. It used to stay behind, empty: Show Mesh outlined +/// it and the renderer kept rasterizing it. Two islands, with the release piece meshed and with no +/// Puppet effect at all; a mesh that was there before the gesture stays, even when left empty. +#[test] +fn puppet_starch_drag_off_unmeshed_art_leaves_no_mesh_behind() { + // (only the right piece meshed, a pinless mesh on the left before the gesture) + for (right_meshed, left_empty_mesh) in [(true, false), (false, false), (true, true)] { + for (tool, kind) in [(Tool::PuppetStarch, "starch"), (Tool::PuppetOverlap, "overlap")] { + let case = format!("{kind}, right meshed {right_meshed}, empty left mesh {left_empty_mesh}"); + let (mut h, id) = puppet_tool_harness(tool); + let s = &mut h.state_mut().session; + for x in [[0, 25], [55, 80]] { + s.execute("mask.new", json!({"layer": id, "vertices": [[x[0], 0], [x[1], 0], [x[1], 80], [x[0], 80]], "closed": true})).unwrap(); + } + if left_empty_mesh { + let pin = s.execute("puppet.addPin", json!({"layer": id, "position": [12, 40]})).unwrap()["pin"].as_u64().unwrap(); + s.execute("puppet.removePin", json!({"layer": id, "pins": [pin]})).unwrap(); + } + if right_meshed { + s.execute("puppet.addPin", json!({"layer": id, "position": [68, 40]})).unwrap(); + } + h.run_steps(3); + let meshes_before = if left_empty_mesh { 2 } else { 1 }; + let undo = h.state().session.history.undo.len(); + // Press on the left piece, release on the right one. + let (from, to) = (screen(&h, [292.0, 155.0]), screen(&h, [348.0, 205.0])); + hold_drag(&mut h, from, to, Default::default()); + let info = h.state_mut().session.execute("puppet.info", json!({"layer": id})).unwrap(); + let meshes = info["meshes"].as_array().unwrap().clone(); + assert_eq!(meshes.len(), meshes_before, "{case}: no mesh left behind on the pressed piece: {info}"); + let kinds = |m: &serde_json::Value| m["pins"].as_array().unwrap().iter().map(|p| p["kind"].as_str().unwrap().to_owned()).collect::>(); + let want: Vec<&str> = if right_meshed { vec!["position", kind] } else { vec![kind] }; + assert_eq!(kinds(meshes.last().unwrap()), want, "{case}: the pin is on the released-on piece's mesh"); + if left_empty_mesh { + assert!(kinds(&meshes[0]).is_empty(), "{case}: the earlier mesh stays, as it was: {info}"); + } + assert_eq!(h.state().session.history.undo.len(), undo + 1, "{case}: one undo step"); + h.state_mut().session.execute("edit.undo", json!({})).unwrap(); + let info = h.state_mut().session.execute("puppet.info", json!({"layer": id})).unwrap(); + let after = info["meshes"].as_array().unwrap().len(); + assert_eq!(after, usize::from(right_meshed) + usize::from(left_empty_mesh), "{case}: undo takes the whole gesture back: {info}"); + } + } +} + /// Filled circles painted this frame (flattening nested shape lists). fn circles(h: &Harness<'_, EffectcraftApp>) -> Vec { fn walk(s: &egui::Shape, out: &mut Vec) {