diff --git a/crates/engine/src/cmd/addons/pathtools/bounding.rs b/crates/engine/src/cmd/addons/pathtools/bounding.rs index 6881eea005..d84eb62488 100644 --- a/crates/engine/src/cmd/addons/pathtools/bounding.rs +++ b/crates/engine/src/cmd/addons/pathtools/bounding.rs @@ -4,9 +4,10 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind, SymbolBoxes}; +use vectorcraft_geom::kurbo::ParamCurveExtrema; use vectorcraft_geom::{Affine, CubicBez, FillRule, ParamCurve, PathSeg, Point, Rect, shapes}; -use super::super::super::edit::{no_symbol_part, selected_roots}; +use super::super::super::edit::{no_symbol_part, selected_roots_to_transform}; use super::super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or}; use crate::sanity::rect_in_range; use crate::{Result, Session}; @@ -30,7 +31,7 @@ pub(super) fn specs() -> Vec { "Add Bounding Rectangle", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{each?: bool (default false: one rectangle around the whole selection; true: one around each selected object), offset?: pt (0 or more; default 0: added on every side)} draw a live rectangle on the geometric bounding box of the selected objects (strokes and effects left out), with the current paint, on top of the current layer or of the isolated group, as other new art; the rectangles are selected; one undo step. An object whose box has no width or no height (a straight horizontal or vertical line) gets no rectangle unless `offset` is more than 0, nor does an object with no bounds (an empty group); with `each` the result's `skipped` counts them. It is an error when no rectangle is left (\"the shape would have no size\" when a rectangle with no size was left out, else \"nothing to enclose\") and when an edge of a rectangle would lie more than 4,000,000 pt from the origin along either axis (\"the shape would reach past the edge of the canvas\"). The menu item Add Bounding Rectangle… opens a dialog with Offset and One per Object (`each`) and a Preview → {id: the first rectangle, ids, skipped?}", + "{each?: bool (default false: one rectangle around the whole selection; true: one around each selected object), offset?: pt (0 or more; default 0: added on every side)} draw a live rectangle on the geometric bounding box of the selected objects (strokes and effects left out; a path of a compound path selected on its own counts as an object), with the current paint, on top of the current layer or of the isolated group, as other new art; the rectangles are selected; one undo step. An object whose box has no width or no height (a straight horizontal or vertical line) gets no rectangle unless `offset` is more than 0, nor does an object with no bounds (an empty group); with `each` the result's `skipped` counts them. It is an error when no rectangle is left (\"the shape would have no size\" when a rectangle with no size was left out, else \"nothing to enclose\") and when an edge of a rectangle would lie more than 4,000,000 pt from the origin along either axis (\"the shape would reach past the edge of the canvas\"). The menu item Add Bounding Rectangle… opens a dialog with Offset and One per Object (`each`) and a Preview → {id: the first rectangle, ids, skipped?}", whole_objects, bounding_rectangle ), @@ -39,7 +40,7 @@ pub(super) fn specs() -> Vec { "Add Bounding Circle", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{each?: bool (default false: one circle around the whole selection; true: one around each selected object), offset?: pt (0 or more; default 0: added to the radius)} draw the smallest live circle that holds the outlines of the selected objects (paths and compound paths by their curves, clip groups and sublayers that clip their contents by their clipping paths, other sublayers by their shown objects, images by their corners, type and other objects by the corners of their bounding box; strokes and effects left out), with the radius 0.01 pt larger so it holds the curves themselves, with the current paint, on top of the current layer or of the isolated group, as other new art; the circles are selected; one undo step. An object at a single point gets no circle unless `offset` is more than 0, nor does an object with no outline (an empty group); with `each` the result's `skipped` counts them. It is an error when no circle is left (\"the shape would have no size\" when a circle with no size was left out, else \"nothing to enclose\") and when an edge of a circle's bounding box would lie more than 4,000,000 pt from the origin along either axis (\"the shape would reach past the edge of the canvas\"). The menu item Add Bounding Circle… opens a dialog with Offset and One per Object (`each`) and a Preview → {id: the first circle, ids, skipped?}", + "{each?: bool (default false: one circle around the whole selection; true: one around each selected object), offset?: pt (0 or more; default 0: added to the radius)} draw the smallest live circle that holds the outlines of the selected objects (paths and compound paths by their curves, clip groups and sublayers that clip their contents by their clipping paths, other sublayers by their shown objects, images by their corners, type and other objects by the corners of their bounding box; strokes and effects left out; a path of a compound path selected on its own counts as an object), with the radius 0.01 pt larger so it holds the curves themselves, with the current paint, on top of the current layer or of the isolated group, as other new art; the circles are selected; one undo step. An object at a single point gets no circle unless `offset` is more than 0, nor does an object with no outline (an empty group); with `each` the result's `skipped` counts them. It is an error when no circle is left (\"the shape would have no size\" when a circle with no size was left out, else \"nothing to enclose\") and when an edge of a circle's bounding box would lie more than 4,000,000 pt from the origin along either axis (\"the shape would reach past the edge of the canvas\"). The menu item Add Bounding Circle… opens a dialog with Offset and One per Object (`each`) and a Preview → {id: the first circle, ids, skipped?}", whole_objects, bounding_circle ), @@ -47,7 +48,7 @@ pub(super) fn specs() -> Vec { } /// Enabled with a selection that is not an object of a symbol instance's art, which -/// [`selected_roots`] refuses. +/// [`selected_roots_to_transform`] refuses. fn whole_objects(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; no_symbol_part(s) @@ -78,7 +79,8 @@ fn add(s: &mut Session, p: &Value, kind: Kind) -> Result { if !(offset.is_finite() && offset >= 0.0) { return Err(bad(c, "`offset` must be 0 or more")); } - let roots = selected_roots(s)?; + // The objects `object.transform` moves: a path of a compound path selected on its own is one. + let roots = selected_roots_to_transform(s)?; let d = &s.doc()?.doc; let symbols = d.symbol_boxes(); let groups: Vec> = if each { roots.iter().map(|id| vec![*id]).collect() } else { vec![roots] }; @@ -86,8 +88,11 @@ fn add(s: &mut Session, p: &Value, kind: Kind) -> Result { // Objects that get no shape: no outline, or a shape with no size. let mut skipped = 0; let mut no_size = false; + // Each shape gets the same share of the halvings, so the shape around one object does not + // depend on the other objects. + let splits = TOTAL_SPLITS / groups.len().max(1); for ids in &groups { - match shape_around(d, &symbols, ids, kind, offset) { + match shape_around(d, &symbols, ids, kind, offset, splits) { Around::Shape(live) => made.push(live), Around::NoOutline => skipped += 1, Around::NoSize => { @@ -134,8 +139,9 @@ enum Around { PastCanvas, } -/// The live rectangle or circle around `ids`, grown by `offset`. -fn shape_around(d: &Document, symbols: &SymbolBoxes, ids: &[NodeId], kind: Kind, offset: f64) -> Around { +/// The live rectangle or circle around `ids`, grown by `offset`. A circle halves its curves +/// `splits` times at most in all. +fn shape_around(d: &Document, symbols: &SymbolBoxes, ids: &[NodeId], kind: Kind, offset: f64, splits: usize) -> Around { match kind { Kind::Rectangle => { let Some(r) = d.bounds_of_with(ids, false, symbols) else { return Around::NoOutline }; @@ -157,6 +163,7 @@ fn shape_around(d: &Document, symbols: &SymbolBoxes, ids: &[NodeId], kind: Kind, } Kind::Circle => { let mut gathered = Gathered::new(); + gathered.splits = splits; for n in ids.iter().filter_map(|id| d.node(*id)) { outline_points(n, symbols, &mut gathered, 0); gathered.compact(); @@ -177,10 +184,10 @@ fn shape_around(d: &Document, symbols: &SymbolBoxes, ids: &[NodeId], kind: Kind, /// Adds to `out` points on the outline of `n`, as its geometric bounds measure it: the points of /// its paths ([`curve_points`]); the clipping path of a clip group or of a sublayer that clips its -/// contents; the shown contents of a sublayer; the corners of an image; and the corners of the -/// geometric bounding box of anything else. A group or layer `depth` levels below the selected -/// object that is nested deeper than a document holds ([`vectorcraft_doc::MAX_DEPTH`]) counts by -/// the corners of its geometric bounding box. +/// contents; the shown contents of a sublayer (a layer that an opened file put inside a group); the +/// corners of an image; and the corners of the geometric bounding box of anything else. A group or +/// layer `depth` levels below the selected object that is nested deeper than a document holds +/// ([`vectorcraft_doc::MAX_DEPTH`]) counts by the corners of its geometric bounding box. fn outline_points(n: &Node, symbols: &SymbolBoxes, out: &mut Gathered, depth: usize) { let nests = matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. } | NodeKind::Compound { .. }); if nests && depth >= vectorcraft_doc::MAX_DEPTH { @@ -197,7 +204,7 @@ fn outline_points(n: &Node, symbols: &SymbolBoxes, out: &mut Gathered, depth: us for seg in path.to_bezpath().segments() { match seg { PathSeg::Line(l) => out.points.extend([l.p0, l.p1]), - _ => curve_points(seg.to_cubic(), 0, &mut out.points), + _ => curve_points(seg.to_cubic(), 0, &mut out.points, &mut out.splits), } out.compact(); } @@ -223,39 +230,86 @@ fn outline_points(n: &Node, symbols: &SymbolBoxes, out: &mut Gathered, depth: us } /// Adds to `out` points whose convex hull, grown by [`FLATNESS`], holds the curve `c`: the ends of -/// pieces whose control points lie within [`FLATNESS`] of their chord, and the control points of -/// pieces still curved after [`MAX_SPLITS`] halvings, which hold their piece. A curve with a point -/// that is not finite adds nothing. -fn curve_points(c: CubicBez, depth: u32, out: &mut Vec) { +/// pieces whose control points lie within [`FLATNESS`] of their chord, and for pieces still curved +/// after [`MAX_SPLITS`] halvings, or once `splits` is used up, the corners of [`held`]. A flat piece +/// that ends where it starts adds its control points too, so a small loop is not taken for a single +/// point. A curve with a point that is not finite adds nothing. +fn curve_points(c: CubicBez, depth: u32, out: &mut Vec, splits: &mut usize) { if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()) { return; } let flat = [c.p1, c.p2].iter().all(|p| distance_to_segment(*p, c.p0, c.p3) <= FLATNESS); if flat { out.extend([c.p0, c.p3]); - } else if depth >= MAX_SPLITS { - out.extend([c.p0, c.p1, c.p2, c.p3]); + if c.p0 == c.p3 { + out.extend([c.p1, c.p2]); + } + } else if depth >= MAX_SPLITS || *splits == 0 { + out.extend(held(c)); } else { + *splits -= 1; let (a, b) = c.subdivide(); - curve_points(a, depth + 1, out); - curve_points(b, depth + 1, out); + curve_points(a, depth + 1, out, splits); + curve_points(b, depth + 1, out, splits); } } +/// The corners of the convex hull of `c`'s control points cut down to `c`'s bounding box. Each of +/// the two holds the curve, so the part they share holds it too. When the cut leaves nothing, which +/// rounding can cause, it gives the box's corners. +fn held(c: CubicBez) -> Vec { + let b = ParamCurveExtrema::bounding_box(&c); + let mut poly = shapes::convex_hull(vec![c.p0, c.p1, c.p2, c.p3]); + for (x, bound, below) in [(true, b.x0, false), (true, b.x1, true), (false, b.y0, false), (false, b.y1, true)] { + poly = clip(&poly, x, bound, below); + } + if poly.is_empty() { corners(b).to_vec() } else { poly } +} + +/// The convex polygon `poly` cut at `bound` on the x axis (`x`) or the y axis: the part at or below +/// `bound` when `below`, else at or above it. +fn clip(poly: &[Point], x: bool, bound: f64, below: bool) -> Vec { + let v = |p: Point| if x { p.x } else { p.y }; + let inside = |p: Point| if below { v(p) <= bound } else { v(p) >= bound }; + let mut out = vec![]; + for (&a, &b) in poly.iter().zip(poly.iter().cycle().skip(1)) { + if inside(a) { + out.push(a); + } + if inside(a) != inside(b) { + let mut p = a.lerp(b, (bound - v(a)) / (v(b) - v(a))); + if x { + p.x = bound; + } else { + p.y = bound; + } + out.push(p); + } + } + out +} + +/// How many halvings [`curve_points`] makes for one command in all, over every curve it measures; +/// with `each`, every shape gets an equal share. +const TOTAL_SPLITS: usize = 1 << 20; + /// How many points [`outline_points`] gathers before it keeps only the corners of their convex hull. const COMPACT_AT: usize = 1 << 16; /// Points gathered for a circle, kept down to the corners of their convex hull whenever they grow -/// past `limit`: only the hull decides the circle, so this bounds the memory a large selection of -/// curves takes. +/// past `limit`: only the hull decides the circle. The points held stay within about twice the +/// hull's corners, and grow only with the anchors and objects measured and the [`TOTAL_SPLITS`] +/// halvings. struct Gathered { points: Vec, limit: usize, + /// The halvings [`curve_points`] may still make ([`TOTAL_SPLITS`] at first). + splits: usize, } impl Gathered { fn new() -> Self { - Self { points: vec![], limit: COMPACT_AT } + Self { points: vec![], limit: COMPACT_AT, splits: TOTAL_SPLITS } } /// Keeps only the hull's corners once there are more than `limit` points; the next time waits diff --git a/crates/engine/src/cmd/addons/pathtools/bounding/tests.rs b/crates/engine/src/cmd/addons/pathtools/bounding/tests.rs index fb30d1f918..79d0766209 100644 --- a/crates/engine/src/cmd/addons/pathtools/bounding/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/bounding/tests.rs @@ -1,11 +1,11 @@ //! Add Bounding Rectangle and Add Bounding Circle: the box and the smallest circle, the current //! paint and placement on top of the current layer or the isolated group, `each` and `skipped`, -//! shapes of no size, clip groups and clipping sublayers, huge curves, and the errors that leave -//! the document as it was. +//! shapes of no size, clip groups and clipping sublayers, paths of compound paths, huge curves and +//! small loops, and the errors that leave the document as it was. use serde_json::{Value, json}; use vectorcraft_doc::{LiveShape, Node, NodeId, NodeKind}; -use vectorcraft_geom::{Point, Rect, Vec2, shapes}; +use vectorcraft_geom::{CubicBez, Point, Rect, Vec2, shapes}; use super::{CIRCLE, COMPACT_AT, Gathered, RECTANGLE}; use crate::Session; @@ -265,7 +265,8 @@ fn clip_groups_count_by_their_clipping_paths() { } /// A sublayer that clips its contents counts by its clipping path, and the hidden objects of a -/// sublayer are left out. +/// sublayer are left out; a sublayer inside a selected group (as an opened file can put one there) +/// counts the same way. #[test] fn sublayers_count_by_their_clipping_path_and_shown_art() { let mut s = session(); @@ -296,6 +297,89 @@ fn sublayers_count_by_their_clipping_path_and_shown_art() { super::outline_points(&sub_node, &d.symbol_boxes(), &mut g, 0); let (center, r) = shapes::enclosing_circle(&g.points).unwrap(); assert!(center.distance(Point::new(25.0, 25.0)) < 1e-9 && (r - 5.0 * 2f64.sqrt()).abs() < 1e-9, "{center:?} {r}"); + + let group = s + .edit("Group", |d, _| { + let layer = d.remove(sub)?; + let id = d.alloc_id(); + d.insert(Some(top), usize::MAX, Node::group(id, vec![layer]))?; + Ok(id) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + let b = bounds(&s, c); + assert!(b.center().distance(Point::new(25.0, 25.0)) < 1e-9 && (b.width() / 2.0 - (5.0 * 2f64.sqrt() + 0.01)).abs() < 1e-9, "{b:?}"); +} + +/// A path of a compound path selected on its own is an object, as `object.transform` moves it: +/// the shape goes around that path only, and with `each` each selected path gets a shape. The +/// compound path selected whole is one object. +#[test] +fn a_path_of_a_compound_path_selected_on_its_own_is_an_object() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 10.0, 10.0); + let b = rect(&mut s, 120.0, 100.0, 10.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let members: Vec = node(&s, compound).children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(members.len(), 2); + for kind in [RECTANGLE, CIRCLE] { + s.execute("select.set", &json!({"ids": [members[0].0]})).unwrap(); + let id = id_of(&s.execute(kind, &json!({})).unwrap()); + let (got, want) = (bounds(&s, id), bounds(&s, members[0])); + if kind == RECTANGLE { + assert!(rect_near(got, want, 1e-9), "{got:?} on {want:?}"); + } else { + let d = want.width().hypot(want.height()) + 0.02; + assert!(got.center().distance(want.center()) < 1e-9 && (got.width() - d).abs() < 1e-9, "{got:?} around {want:?}"); + } + s.execute("select.set", &json!({"ids": [members[0].0, members[1].0]})).unwrap(); + assert_eq!(ids_of(&s.execute(kind, &json!({"each": true})).unwrap()).len(), 2, "{kind}"); + s.execute("select.set", &json!({"ids": [compound.0]})).unwrap(); + assert_eq!(ids_of(&s.execute(kind, &json!({"each": true})).unwrap()).len(), 1, "{kind}"); + } +} + +/// A small closed curve whose handles lie within the 0.01 pt allowance of its one anchor is not a +/// single point: it gets a circle. +#[test] +fn a_small_loop_gets_a_circle() { + let mut s = session(); + let lp = id_of(&s.execute("path.create", &json!({"d": "M 0 0 C 0.005 0 0 0.005 0 0"})).unwrap()); + s.execute("select.set", &json!({"ids": [lp.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + let LiveShape::Ellipse { w, .. } = live(&s, c) else { panic!("not a circle") }; + assert!(w > 0.02, "{w}"); +} + +/// Once the command has used up its halvings, a curve counts by its control points' hull cut down to +/// its bounding box: the points stay inside both and reach no farther than the curve along either +/// axis, while its handles may. +#[test] +fn a_curve_past_the_halvings_counts_by_its_hull_inside_its_bounding_box() { + let c = CubicBez::new((0.0, 0.0), (20.0, 400.0), (380.0, 500.0), (400.0, 0.0)); + let b = vectorcraft_geom::kurbo::ParamCurveExtrema::bounding_box(&c); + let mut out = vec![]; + super::curve_points(c, 0, &mut out, &mut 0); + assert!(out.len() >= 4 && out.iter().all(|p| b.inflate(1e-9, 1e-9).contains(*p)), "{out:?} in {b:?}"); + assert!(out.iter().any(|p| (p.y - b.y1).abs() < 1e-9), "the curve's lowest point is reached: {out:?}"); + let (center, r) = shapes::enclosing_circle(&out).unwrap(); + for i in 0..=1000 { + let p = vectorcraft_geom::ParamCurve::eval(&c, f64::from(i) / 1000.0); + assert!(p.distance(center) <= r + 1e-9, "{p:?} outside"); + } + // The handle at x = 4,000,000 stays out: the curve reaches x = 16,000,000 / 9. + let reach = CubicBez::new((0.0, 0.0), (4.0e6, 0.0), (0.0, 0.0), (0.0, 0.0)); + out.clear(); + super::curve_points(reach, 0, &mut out, &mut 0); + let far = out.iter().map(|p| p.x).fold(0.0, f64::max); + assert!((far - 16.0e6 / 9.0).abs() < 1e-6, "{far}"); + out.clear(); + let mut splits = 3; + super::curve_points(c, 0, &mut out, &mut splits); + assert_eq!(splits, 0); + assert!(out.len() > 4, "{out:?}"); } /// In an isolated group the shape goes on top of the group's art; in an isolated compound path it @@ -382,6 +466,25 @@ fn one_edge_past_the_canvas_edge_is_enough_to_refuse() { assert!(s.execute(RECTANGLE, &json!({"offset": 5})).is_ok(), "the right edge at 3,999,995 pt is inside"); } +/// A large circle close to the canvas edge, whose arcs stay curved after the most halvings, gets a +/// circle within 0.05 pt of the farthest point of its curves, which stays inside the edge. +#[test] +fn a_large_circle_near_the_canvas_edge_gets_a_close_circle() { + let mut s = session(); + let e = id_of(&s.execute("shape.ellipse", &json!({"x": 3_799_950.0, "y": 0.0, "width": 200_000.0, "height": 200_000.0})).unwrap()); + s.execute("select.set", &json!({"ids": [e.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + let LiveShape::Ellipse { w, xf, .. } = live(&s, c) else { panic!("not a circle") }; + let center = xf * Point::new(w / 2.0, w / 2.0); + let mut farthest: f64 = 0.0; + for seg in node(&s, e).path_data().unwrap().to_bezpath().segments() { + for i in 0..=4000 { + farthest = farthest.max(vectorcraft_geom::ParamCurve::eval(&seg, f64::from(i) / 4000.0).distance(center)); + } + } + assert!(w / 2.0 >= farthest && w / 2.0 < farthest + 0.05, "radius {} for curves reaching {farthest}", w / 2.0); +} + /// The commands are dimmed while an object of a symbol instance's art is selected, which they /// refuse, and available again once it is not. #[test] diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 22593c9e51..852c5e9642 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -371,37 +371,35 @@ pub fn circle_through_points(points: &[Point]) -> Option<(Point, f64)> { /// not finite are skipped; `None` when no finite point is left. One point gives a circle of /// radius 0 around it. pub fn enclosing_circle(points: &[Point]) -> Option<(Point, f64)> { - let mut hull = convex_hull(points.iter().copied().filter(|p| p.is_finite()).collect()); + let mut world = convex_hull(points.iter().copied().filter(|p| p.is_finite()).collect()); // A fixed shuffle keeps the expected work linear for any order of the points, and the same // points always give the same circle. let mut seed: u64 = 0x9E37_79B9_7F4A_7C15; - for i in (1..hull.len()).rev() { + for i in (1..world.len()).rev() { seed ^= seed << 13; seed ^= seed >> 7; seed ^= seed << 17; - hull.swap(i, (seed % (i as u64 + 1)) as usize); + world.swap(i, (seed % (i as u64 + 1)) as usize); } // The work is done relative to one of the points, so the rounding allowance in `holds` scales // with the size of the points' spread, not with their distance from the origin. - let origin = *hull.first()?; - for p in &mut hull { - *p = (*p - origin).to_point(); - } + let origin = *world.first()?; + let rel = |p: &Point| (*p - origin).to_point(); let first = Point::ORIGIN; let holds = |(c, r): (Point, f64), p: Point| (p - c).hypot() <= r + 1e-12 * (r + c.to_vec2().hypot()); let diameter = |a: Point, b: Point| (a.midpoint(b), (b - a).hypot() / 2.0); let mut circle = (first, 0.0); - for (i, &pi) in hull.iter().enumerate().skip(1) { + for (i, pi) in world.iter().map(rel).enumerate().skip(1) { if holds(circle, pi) { continue; } circle = (pi, 0.0); - for (j, &pj) in hull.iter().enumerate().take(i) { + for (j, pj) in world.iter().map(rel).enumerate().take(i) { if holds(circle, pj) { continue; } circle = diameter(pi, pj); - for &pk in &hull[..j] { + for pk in world[..j].iter().map(rel) { if holds(circle, pk) { continue; } @@ -414,10 +412,10 @@ pub fn enclosing_circle(points: &[Point]) -> Option<(Point, f64)> { } } } - // The radius reaches the farthest point exactly, whatever rounding the steps above left. - let center = circle.0; - let radius = hull.iter().map(|p| (*p - center).hypot()).fold(0.0, f64::max); - let center = center + origin.to_vec2(); + // The radius reaches the farthest point from the center returned, whatever rounding the steps + // above and the move back from `origin` left. + let center = circle.0 + origin.to_vec2(); + let radius = world.iter().map(|p| (*p - center).hypot()).fold(0.0, f64::max); (center.is_finite() && radius.is_finite()).then_some((center, radius)) } @@ -929,6 +927,11 @@ mod tests { // Small art far from the origin keeps its smallest circle. let far = [Point::new(1.0e12, 5.0), Point::new(1.0e12 + 1.0, 5.0)]; assert_eq!(enclosing_circle(&far), Some((Point::new(1.0e12 + 0.5, 5.0), 0.5))); + // Where the center rounds on its way back from the first point, the radius still reaches + // every point from the center returned. + let wide = [Point::new(2f64.powi(53), 0.0), Point::new(2f64.powi(53) + 2.0, 0.0)]; + let (center, r) = enclosing_circle(&wide).unwrap(); + assert!(wide.iter().all(|p| p.distance(center) <= r), "{center:?} {r}"); let one = Point::new(3.0, 4.0); assert_eq!(enclosing_circle(&[one, one, Point::new(f64::NAN, 1.0)]), Some((one, 0.0))); assert_eq!(enclosing_circle(&[]), None); diff --git a/docs/mcp.md b/docs/mcp.md index f5fce28e07..9a24ec6698 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13711,12 +13711,14 @@ Commands: their corners, and type and other objects by the corners of their bounding box. It splits each curve into pieces until every piece's control points lie within 0.01 pt of its chord, fits the circle to the ends of the pieces, and makes the radius 0.01 pt larger, so the circle holds the curves themselves. A curve is split into 1,024 pieces at - most; a piece that still bends more counts by its control points, which can make the circle slightly larger than the - smallest one. `offset` (0 or more, default 0) adds space: a rectangle grows by `offset` on each side and a circle's - radius grows by `offset`. `each: true` draws one shape around each selected object instead of one around the whole - selection. The menu items Add Bounding Rectangle… and Add Bounding Circle… open a dialog with Offset (0 to 4,000,000 - pt, default 0), One per Object (`each`, default off) and Preview; OK draws the shapes as one undo step, and Cancel - removes the preview without a step of history. + most, and one command splits its curves 1,048,576 times at most in all (with `each`, shared equally among the + shapes); a piece that still bends more counts by the hull of its control points cut down to its bounding box, + which can make the circle slightly larger than the smallest one. A path of a compound path selected on its own + counts as an object, as `object.transform` moves it. `offset` (0 or more, default 0) adds space: a rectangle grows + by `offset` on each side and a circle's radius grows by `offset`. `each: true` draws one shape around each selected + object instead of one around the whole selection. The menu items Add Bounding Rectangle… and Add Bounding Circle… + open a dialog with Offset (0 to 4,000,000 pt, default 0), One per Object (`each`, default off) and Preview; OK draws + the shapes as one undo step, and Cancel removes the preview without a step of history. Each shape gets the current paint and goes on top of the current layer, or of the isolated group, as other new art does; inside an isolated compound path it goes beside the compound path and does not join it. The new shapes are diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2dbce0eb98..f9320d42b4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2835,7 +2835,7 @@ A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Pre ## Path Precision Tools add-on: Add Bounding Rectangle and Add Bounding Circle (2026-11-17) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle (`addon.pathtools.boundingRectangle`) draws a live rectangle on the selection's geometric bounding box, and Add Bounding Circle (`addon.pathtools.boundingCircle`) draws the [smallest enclosing circle](https://en.wikipedia.org/wiki/Smallest-circle_problem) of the selected outlines, with curves flattened to within 0.01 pt and the radius 0.01 pt larger, so the circle holds the curves. A curve is split into 1,024 pieces at most; a piece that still bends more counts by its control points, which can make the circle slightly larger than the smallest one. Both use the current paint, go on top of the current layer or the isolated group, and are one undo step; shapes with no size are skipped (#6966). The commands take `each` (one shape per object) and `offset`, and the menu items Add Bounding Rectangle… and Add Bounding Circle… open a dialog with Offset, One per Object and Preview. Tests: `shapes::tests` in `vectorcraft-geom` (`enclosing`, `convex_hull`), `cmd::addons::pathtools::bounding::tests` in `vectorcraft-engine` and `addons::pathtools::tests` in `vectorcraft-ui-egui` (`add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object`). Commands: `docs/mcp.md` › Path Precision Tools add-on. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle (`addon.pathtools.boundingRectangle`) draws a live rectangle on the selection's geometric bounding box, and Add Bounding Circle (`addon.pathtools.boundingCircle`) draws the [smallest enclosing circle](https://en.wikipedia.org/wiki/Smallest-circle_problem) of the selected outlines, with curves flattened to within 0.01 pt and the radius 0.01 pt larger, so the circle holds the curves. A curve is split into 1,024 pieces at most, and one command splits its curves 1,048,576 times at most in all (shared equally among the shapes); a piece that still bends more counts by the hull of its control points cut down to its bounding box, which can make the circle slightly larger than the smallest one. Both use the current paint, go on top of the current layer or the isolated group, and are one undo step; shapes with no size are skipped (#6966). The commands take `each` (one shape per object) and `offset`, and the menu items Add Bounding Rectangle… and Add Bounding Circle… open a dialog with Offset, One per Object and Preview. Tests: `shapes::tests` in `vectorcraft-geom` (`enclosing`, `convex_hull`), `cmd::addons::pathtools::bounding::tests` in `vectorcraft-engine` and `addons::pathtools::tests` in `vectorcraft-ui-egui` (`add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object`). Commands: `docs/mcp.md` › Path Precision Tools add-on. ## Path Precision Tools add-on: Expand Dashes into Paths (2026-11-01)