From 41eef74720fbe8dde8177453f4d5befa7d9118a2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 22:11:08 -0800 Subject: [PATCH] Effects: geometry effects work from bounds that hold lone anchors A geometry effect is given the object's box as its reference, for example the center a Transform effect scales and rotates about. Drawing, the preview bounds, Expand Appearance's first step, shape art, the outline check of the .ai reader and a stroke's effects before a Transform that makes the stroke a path of its own measured that box with kurbo's bounding_box, which counts only segments. A lone anchor was left out, and a path of one anchor measured a box at the origin, so it scaled about (0, 0). PathData::bounds, which the selection's box, Align, Transform Each and every later effect in the stack use, holds lone anchors. - geom: anchored_curve_bounds measures a BezPath as PathData::bounds measures the path it stands for. - render, effects and the .ai reader give geometry effects that box. Gradient reference boxes and clip regions are unchanged. --- crates/effects/src/bake.rs | 2 +- crates/effects/src/group.rs | 2 +- crates/effects/src/preview.rs | 4 +- crates/effects/src/reshape.rs | 6 +- crates/effects/src/tests.rs | 1 + crates/effects/src/tests/loneanchor.rs | 118 +++++++++++++++++++++++++ crates/eps/src/import/ai/read/ops.rs | 25 +++++- crates/geom/src/path.rs | 40 ++++++++- crates/render/src/fx/bounds.rs | 10 ++- crates/render/src/fx/tests.rs | 26 ++++++ 10 files changed, 223 insertions(+), 11 deletions(-) create mode 100644 crates/effects/src/tests/loneanchor.rs diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 13a9c5c13b..8138474736 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -82,7 +82,7 @@ pub(crate) fn apply(effects: &[vectorcraft_doc::Effect], path: &PathData, ctx: & if !has_geometry(effects) || path.is_empty() { return (path.clone(), crate::Carry::default()); } - let b = vectorcraft_geom::Shape::bounding_box(&path.to_bezpath()); + let b = path.bounds().unwrap_or_default(); apply_geometry_carrying(effects, path, b, ctx) } diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 74a24c2442..24b0e06ff3 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -350,7 +350,7 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option, nod fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node { let mut m = src.clone(); if let Some((path, rule)) = geometry(src) { - let bounds = vectorcraft_geom::Shape::bounding_box(&path.to_bezpath()); + let bounds = path.bounds().unwrap_or_default(); let (g, carry) = crate::apply_geometry_carrying(&n.appearance.effects, &path, bounds, &crate::GeomContext { doc, ..crate::GeomContext::of(n) }); m.kind = NodeKind::Path { path: g, rule, live: None, clipping: false, guide: false }; diff --git a/crates/effects/src/preview.rs b/crates/effects/src/preview.rs index 8d330a606b..9f7e36a429 100644 --- a/crates/effects/src/preview.rs +++ b/crates/effects/src/preview.rs @@ -435,7 +435,7 @@ fn reshapes(n: &Node) -> bool { fn path_art(n: &Node) -> Option { let (path, rule) = leaf_geometry(n)?; let ctx = GeomContext::of(n); - let g = apply_geometry_with(&n.appearance.effects, &path, path.to_bezpath().bounding_box(), &ctx); + let g = apply_geometry_with(&n.appearance.effects, &path, path.bounds().unwrap_or_default(), &ctx); let piece = |geometry: PathData, items: Vec| { let mut ap: Appearance = (*n.appearance).clone(); ap.items = items; @@ -454,7 +454,7 @@ fn path_art(n: &Node) -> Option { if own.is_empty() || plain.iter().any(|i| paints(i)) { pieces.push(piece(g.clone(), plain.into_iter().cloned().collect())); } - let bounds = g.to_bezpath().bounding_box(); + let bounds = g.bounds().unwrap_or_default(); for item in own { let geometry = apply_geometry_with(item.effects(), &g, bounds, &ctx.item(item)); pieces.push(piece(geometry, vec![item.clone()])); diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index ee68067d2f..baef314b43 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -20,7 +20,7 @@ use std::sync::{Arc, Mutex, OnceLock, PoisonError, Weak}; use vectorcraft_doc::live::Hooks; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, ImageObject, Node, NodeId, NodeKind}; -use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Shape, shapes}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, shapes}; use crate::{Budget, GeomContext, OutlineHook, apply_one, is_geometry, merged_params}; @@ -659,7 +659,7 @@ fn push_painted(doc: Option<&Document>, c: &Node, out: &mut Vec<(BezPath, FillRu for item in c.appearance.items.iter().filter(|i| crate::paints(i)) { let fx = item.effects(); let shape = if crate::has_geometry(fx) && !g.elements().is_empty() { - crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item)) + crate::apply_geometry_bez(fx, &g, vectorcraft_geom::path::anchored_curve_bounds(&g).unwrap_or_default(), &ctx.item(item)) } else { g.clone() }; @@ -2691,7 +2691,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt let Some((path, rule)) = leaf_geometry(leaf) else { return }; let original = leaf.clone(); let ctx = GeomContext::of(&original); - let bounds = path.to_bezpath().bounding_box(); + let bounds = path.bounds().unwrap_or_default(); // A path of the leaf's geometry painted by `items` alone, without the leaf's transparency and // object effects (the group keeps them). let piece = |items: Vec| { diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index f6afd42b7c..07efb0c8bd 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -6,6 +6,7 @@ use super::*; mod clipfx; mod imageoutline; +mod loneanchor; mod painted; mod rasterfollow; mod scale; diff --git a/crates/effects/src/tests/loneanchor.rs b/crates/effects/src/tests/loneanchor.rs new file mode 100644 index 0000000000..6b1b571364 --- /dev/null +++ b/crates/effects/src/tests/loneanchor.rs @@ -0,0 +1,118 @@ +//! Geometry effects on a path with a lone anchor work from the path's bounds with that anchor +//! included ([`PathData::bounds`]), as the selection's box, Align and Transform Each measure the +//! path, wherever the effects are applied. + +use std::sync::Arc; + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol}; + +use super::*; + +/// A 10 pt line from the origin and a lone anchor at (100, 50): its bounds are (0, 0) to +/// (100, 50), and the line alone measures (0, 0) to (10, 0). +fn marked() -> PathData { + PathData::new(vec![ + SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0)], false), + SubPath::polyline(&[Point::new(100.0, 50.0)], false), + ]) +} + +/// The Transform effect at 200%, about the center of the box it is given. +fn scale() -> Effect { + fx("distort.transform", json!({"scaleH": 200, "scaleV": 200})) +} + +/// `marked` with a 1 pt black stroke, and `scale` on the object (`on_stroke` false) or on its +/// stroke. +fn node(on_stroke: bool) -> Node { + let mut n = Node::path(NodeId(5), marked(), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)); + if on_stroke { + if let Some(s) = n.appearance.stroke_mut() { + s.effects.push(scale()); + } + } else { + n.appearance.effects.push(scale()); + } + n +} + +/// The first point of each subpath of each path under `n`. +fn starts(n: &Node, out: &mut Vec) { + if let NodeKind::Path { path, .. } = &n.kind { + out.extend(path.subpaths.iter().filter_map(|s| s.anchors.first()).map(|a| a.p)); + } + for c in n.children().into_iter().flatten() { + starts(c, out); + } +} + +/// Does a path under `n` start where the line scaled about (50, 25) starts, (-50, -25), and +/// none where the line scaled about its own center (5, 0) starts, (-5, 0)? +fn scaled_about_the_bounds(n: &Node) -> bool { + let mut pts = vec![]; + starts(n, &mut pts); + let at = |x: f64, y: f64| pts.iter().any(|p| close(p.x, x, 1e-6) && close(p.y, y, 1e-6)); + assert_eq!(apply_geometry(&[scale()], &marked(), marked().bounds().unwrap()).subpaths[0].anchors[0].p, Point::new(-50.0, -25.0)); + at(-50.0, -25.0) && !at(-5.0, 0.0) +} + +#[test] +fn expand_appearance_scales_about_bounds_with_the_lone_anchor() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + d.insert(Some(l), 0, node(false)).unwrap(); + let baked = bake_document(&d).expect("the effect bakes"); + let layer = &baked.layers[0]; + assert!(scaled_about_the_bounds(layer), "{layer:?}"); +} + +/// A stroke's Transform effect with Scale Strokes & Effects on makes the stroke a path of its own +/// when the object's own effects are reshaped, its geometry after the stroke's effects before it. +#[test] +fn a_stroke_effect_scales_about_bounds_with_the_lone_anchor() { + let mut n = node(true); + n.appearance.effects = vec![fx("distort.transform", json!({}))]; + if let Some(s) = n.appearance.stroke_mut() { + s.effects.push(fx("distort.transform", json!({"strokes": true}))); + } + let art = reshape(None, &n, None).expect("the effects make art"); + assert!(scaled_about_the_bounds(&art), "{art:?}"); +} + +#[test] +fn shape_art_scales_about_bounds_with_the_lone_anchor() { + let art = shape_art(None, &node(false), None).expect("the effect makes art"); + assert!(scaled_about_the_bounds(&art), "{art:?}"); +} + +#[test] +fn preview_art_scales_about_bounds_with_the_lone_anchor() { + let d = Document::new(200.0, 200.0); + let symbols = d.symbol_boxes(); + for on_stroke in [false, true] { + let art = crate::preview::drawn_art(&symbols, &node(on_stroke)).expect("the effect makes art"); + assert!(scaled_about_the_bounds(&art), "on the stroke {on_stroke}: {art:?}"); + } +} + +#[test] +fn an_instance_paints_its_art_scaled_about_bounds_with_the_lone_anchor() { + let mut d = Document::new(200.0, 200.0); + d.symbols.push(Symbol { dynamic: false, name: "s".into(), art: Arc::new(node(true)) }); + let mut inst = Node::new(NodeId(9), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::IDENTITY }); + inst.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into(); + if let Some(s) = inst.appearance.stroke_mut() { + s.effects.push(fx("distort.transform", json!({}))); + } + let painted = image_paint(Some(&d), &inst); + let pts: Vec = painted + .iter() + .filter_map(|(bp, _, _)| match bp.elements().first() { + Some(vectorcraft_geom::PathEl::MoveTo(p)) => Some(*p), + _ => None, + }) + .collect(); + assert!(pts.iter().any(|p| close(p.x, -50.0, 1e-6) && close(p.y, -25.0, 1e-6)), "{pts:?}"); + assert!(!pts.iter().any(|p| close(p.x, -5.0, 1e-6) && close(p.y, 0.0, 1e-6)), "{pts:?}"); +} diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 1e53f2fa57..fcdffd4580 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -1658,7 +1658,7 @@ fn draws_look_outline(object: &Node, appearance: &Appearance, look: &Node) -> bo } // The object's outline reshaped as it is drawn: its effects from its own bounds. for path in &mut ours { - let bounds = kurbo::Shape::bounding_box(&path.to_bezpath()); + let bounds = path.bounds().unwrap_or_default(); *path = vectorcraft_effects::apply_geometry(&appearance.effects, path, bounds); } let max = MAX_OUTLINE_PAIRS.isqrt(); @@ -2041,6 +2041,29 @@ mod tests { assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed()); } + /// The outline check reshapes the object as it is drawn, its effects working from its bounds + /// with its lone anchors: a 10 pt line with a lone anchor at (100, 50), scaled 200% about + /// (50, 25), matches a look of that line drawn from (-50, -25), and not one of the line scaled + /// about its own center. + #[test] + fn the_outline_check_reshapes_from_bounds_with_lone_anchors() { + use vectorcraft_geom::{Point, SubPath}; + let scale = + vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"scaleH": 200, "scaleV": 200}), visible: true }; + let path = PathData::new(vec![ + SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0)], false), + SubPath::polyline(&[Point::new(100.0, 50.0)], false), + ]); + let appearance = Appearance { effects: vec![scale], ..Appearance::basic(Paint::None, Paint::None, 0.0) }; + let object = Node::path(NodeId(1), path, appearance.clone()); + let look = |from: Point, to: Point| { + let drawn = PathData::single(SubPath::polyline(&[from, to], false)); + Node::group(NodeId(2), vec![Arc::new(Node::path(NodeId(3), drawn, Appearance::default()))]) + }; + assert!(draws_look_outline(&object, &appearance, &look(Point::new(-50.0, -25.0), Point::new(-30.0, -25.0)))); + assert!(!draws_look_outline(&object, &appearance, &look(Point::new(-5.0, 0.0), Point::new(15.0, 0.0)))); + } + /// The outline check holds for every point of the outlines, not only the points it checks: a /// 0.25 pt line whose look has only short pieces over its ends, 0.24 pt away, leaves the /// line's middle about 0.27 pt from the look, so the drawn look stays. The line drawn 0.1 pt diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index d61d8e39f5..49cc392f80 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -883,6 +883,36 @@ pub fn drawn_curve_bounds(path: &BezPath, dots: bool) -> Option { bbox } +/// The box [`PathData::bounds`] measures for the path `path` stands for: its segments, as in +/// [`curve_bounds`], and the point of each subpath that has no segment, a lone anchor, open or +/// closed. `None` for a path with no elements. +pub fn anchored_curve_bounds(path: &BezPath) -> Option { + let mut bbox = path.segments().map(segment_bounds).reduce(|bb, seg_bb| bb.union(seg_bb)); + let mut add = |p: Point| { + let lone = Rect::from_points(p, p); + bbox = Some(bbox.map_or(lone, |bb| bb.union(lone))); + }; + // The start of the current subpath while it has no segment. A `ClosePath` straight after the + // `MoveTo` adds no segment, unless the point is NaN (kurbo then closes with a line of its own, + // which `segments` measured). + let mut lone = None; + for el in path.elements() { + match el { + PathEl::MoveTo(p) => { + if let Some(q) = lone.replace(*p) { + add(q); + } + } + PathEl::ClosePath => {} + _ => lone = None, + } + } + if let Some(q) = lone { + add(q); + } + bbox +} + /// The box of `seg` as kurbo's `bounding_box` measures it (its start, end and extrema), except /// that a segment with a control point whose x or y is not finite or is larger in size than /// `f64::MAX / 16` is measured by its control points. The box then holds every point the segment @@ -938,10 +968,11 @@ mod tests { let path = proptest::collection::vec(sub, 0..4).prop_map(PathData::new); proptest!(ProptestConfig::with_cases(2000), |(pd in path)| { prop_assert_eq!(bits(pd.bounds()), bits(reference(&pd))); - // The kurbo path the anchors stand for draws the same box. + // The kurbo path the anchors stand for draws and measures the same boxes. for dots in [false, true] { prop_assert_eq!(bits(drawn_curve_bounds(&pd.to_bezpath(), dots)), bits(pd.drawn_bounds(dots))); } + prop_assert_eq!(bits(anchored_curve_bounds(&pd.to_bezpath())), bits(pd.bounds())); }); // Two lone anchors: the path has no segment, and the box spans the two points. let lone = PathData::new(vec![SubPath::polyline(&[Point::new(5.0, 5.0)], false), SubPath::polyline(&[Point::new(9.0, 1.0)], true)]); @@ -968,7 +999,14 @@ mod tests { PathData::new(vec![closed(&[nan, Point::new(3.0, 4.0), Point::new(6.0, 1.0)])]), ] { assert_eq!(bits(pd.bounds()), bits(reference(&pd))); + assert_eq!(bits(anchored_curve_bounds(&pd.to_bezpath())), bits(pd.bounds())); } + // kurbo's own box leaves out the lone anchor, and measures a path of one anchor at the origin. + assert_eq!(anchored_curve_bounds(&beside.to_bezpath()), beside.bounds()); + assert_ne!(Some(beside.to_bezpath().bounding_box()), beside.bounds()); + let one = PathData::single(SubPath::polyline(&[Point::new(7.0, 8.0)], false)); + assert_eq!(anchored_curve_bounds(&one.to_bezpath()), Some(Rect::new(7.0, 8.0, 7.0, 8.0))); + assert_eq!(anchored_curve_bounds(&BezPath::new()), None); } fn square() -> PathData { diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index dc9b8063de..be4cfb5f77 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -22,11 +22,17 @@ pub(super) fn node_bezpath(n: &Node) -> Option { } } +/// The box geometry effects on `bp` work from: the object's geometric bounds, lone anchors +/// included, as [`vectorcraft_geom::PathData::bounds`] measures them. +fn reference_box(bp: &BezPath) -> Rect { + vectorcraft_geom::path::anchored_curve_bounds(bp).unwrap_or_default() +} + pub(super) fn apply(effects: &[Effect], bp: &BezPath, ctx: &GeomContext) -> BezPath { if !effects::has_geometry(effects) || bp.elements().is_empty() { return bp.clone(); } - effects::apply_geometry_bez(effects, bp, bp.bounding_box(), ctx) + effects::apply_geometry_bez(effects, bp, reference_box(bp), ctx) } /// The object-level effected geometry of `n` (base path `bp`), with the swatches and patterns that @@ -40,7 +46,7 @@ pub(super) fn apply_carrying(effects: &[Effect], bp: &BezPath, ctx: &GeomContext if !effects::has_geometry(effects) || bp.elements().is_empty() { return (bp.clone(), effects::Carry::default()); } - effects::apply_geometry_bez_carrying(effects, bp, bp.bounding_box(), ctx) + effects::apply_geometry_bez_carrying(effects, bp, reference_box(bp), ctx) } /// [`effected_path`], and how `n`'s gradients follow its effects. diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 9a5eb976e1..757290ed1f 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -2205,3 +2205,29 @@ fn a_3d_effect_that_builds_nothing_draws_the_item_as_without_it() { } } } + +/// Geometry effects work from the object's bounds, lone anchors included, as the selection's box +/// and Expand Appearance measure them: a Transform effect that scales a 10 pt line with a lone +/// anchor at (100, 50) by 200% scales it about (50, 25), the center of the box that holds the +/// anchor, and a path of one anchor stays where it is. +#[test] +fn geometry_effects_work_from_bounds_that_hold_lone_anchors() { + use vectorcraft_geom::{PathData, PathEl, SubPath}; + let scale = Effect { id: "distort.transform".into(), params: json!({"scaleH": 200, "scaleV": 200}), visible: true }; + let line = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0)], false); + let lone = SubPath::polyline(&[Point::new(100.0, 50.0)], false); + let d = Document::new(200.0, 200.0); + for (path, first) in [(PathData::new(vec![line, lone.clone()]), Point::new(-50.0, -25.0)), (PathData::single(lone), Point::new(100.0, 50.0))] { + let mut n = Node::path(vectorcraft_doc::NodeId(1), path.clone(), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)); + n.appearance.effects.push(scale.clone()); + let bp = super::bounds::node_bezpath(&n).unwrap_or_default(); + let want = crate::effects::apply_geometry(std::slice::from_ref(&scale), &path, path.bounds().unwrap_or_default()).to_bezpath(); + let drawn = super::bounds::effected_path(&d, &n, &bp); + let (carried, _) = super::bounds::effected_path_carrying(&d, &n, &bp); + for g in [&drawn, &carried] { + assert_eq!(g, &want, "{path:?}"); + let Some(PathEl::MoveTo(p)) = g.elements().first() else { panic!("{g:?} starts with no point") }; + assert!((p.x - first.x).abs() < 1e-9 && (p.y - first.y).abs() < 1e-9, "{path:?} starts at {p:?}, not {first:?}"); + } + } +}