From becf2a0a55d423b234d4e3a8640812c4ea5a0a65 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:07:44 +0100 Subject: [PATCH] svg: recognise rectangles, rounded rectangles and ellipses in scene paths (#778, #789) (#1869) tree::primitive::recognize (and Path::primitive) returns the axis-aligned basic shape a path draws: one closed contour whose points all lie on a (rounded) rectangle's or ellipse's outline and that encloses its area. usvg turns rect, circle and ellipse into paths; apps that edit them as shapes get them back from the segments. --- crates/svg/src/tree.rs | 1 + crates/svg/src/tree/document.rs | 8 ++ crates/svg/src/tree/primitive.rs | 164 +++++++++++++++++++++++++ crates/svg/src/tree/primitive_tests.rs | 116 +++++++++++++++++ 4 files changed, 289 insertions(+) create mode 100644 crates/svg/src/tree/primitive.rs create mode 100644 crates/svg/src/tree/primitive_tests.rs diff --git a/crates/svg/src/tree.rs b/crates/svg/src/tree.rs index 9cf85c3bd..99b6f73a4 100644 --- a/crates/svg/src/tree.rs +++ b/crates/svg/src/tree.rs @@ -34,6 +34,7 @@ use crate::{guard, svgz}; pub mod document; pub mod draw; +pub mod primitive; /// What one import may use. The defaults suit a desktop app that parses on a thread with a /// large stack (see the module text). diff --git a/crates/svg/src/tree/document.rs b/crates/svg/src/tree/document.rs index f77d5a8c0..838f62e98 100644 --- a/crates/svg/src/tree/document.rs +++ b/crates/svg/src/tree/document.rs @@ -89,6 +89,14 @@ pub struct Path { pub source_path: NodePath, } +impl Path { + /// The basic shape (rectangle, rounded rectangle or ellipse) this path draws, if any + /// ([`super::primitive::recognize`]). + pub fn primitive(&self) -> Option { + super::primitive::recognize(&self.segments) + } +} + /// A path segment in CSS pixels after its absolute transform. #[derive(Clone, Copy, Debug, PartialEq)] pub enum Segment { diff --git a/crates/svg/src/tree/primitive.rs b/crates/svg/src/tree/primitive.rs new file mode 100644 index 000000000..a43933ec3 --- /dev/null +++ b/crates/svg/src/tree/primitive.rs @@ -0,0 +1,164 @@ +//! Basic shapes recovered from a scene path. usvg turns `rect`, `circle` and `ellipse` into +//! paths; an app that edits them as shapes (a rectangle with corner radii, an ellipse) gets them +//! back here from the segments alone. +//! +//! A path is a primitive when it is one closed contour whose points all lie on the outline of +//! an axis-aligned (rounded) rectangle or ellipse and that encloses its area. The check works on +//! the segments as given, so use it on a [`Coordinates::Local`](super::document::Coordinates) +//! scene, where a rotated or skewed shape keeps its own axes. + +use super::document::Segment; + +/// An axis-aligned basic shape. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Primitive { + /// A rectangle, with elliptical corners of radii `rx`, `ry` (both 0 for square corners). + Rect { x: f64, y: f64, width: f64, height: f64, rx: f64, ry: f64 }, + /// An ellipse (a circle when `rx == ry`). + Ellipse { cx: f64, cy: f64, rx: f64, ry: f64 }, +} + +/// Most segments a primitive's contour has: usvg writes a rounded rectangle as 4 lines and up to +/// 4 curves per corner. +const MAX_SEGMENTS: usize = 32; +/// Points sampled on each curve, besides its ends: enough that the polygon through them +/// encloses a curved outline's area to well within the area check's 1%. +const SAMPLES: usize = 31; + +/// The curve parameters sampled between a curve's ends. +fn samples() -> impl Iterator { + (1..=SAMPLES).map(|i| i as f64 / (SAMPLES + 1) as f64) +} + +/// The basic shape `segments` draw, if they draw one. +pub fn recognize(segments: &[Segment]) -> Option { + let (ends, points) = contour(segments)?; + let (mut min, mut max) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); + for p in &points { + for axis in 0..2 { + min[axis] = min[axis].min(p[axis]); + max[axis] = max[axis].max(p[axis]); + } + } + let (width, height) = (max[0] - min[0], max[1] - min[1]); + if !(width.is_finite() && height.is_finite()) || width <= 0.0 || height <= 0.0 { + return None; + } + let tol = 1e-3 * width.max(height); + // The straight part of the top edge starts `rx` in; of the left edge, `ry` down. + let rx = ends.iter().filter(|p| (p[1] - min[1]).abs() <= tol).map(|p| p[0] - min[0]).fold(f64::INFINITY, f64::min); + let ry = ends.iter().filter(|p| (p[0] - min[0]).abs() <= tol).map(|p| p[1] - min[1]).fold(f64::INFINITY, f64::min); + let rx = snap(rx, width / 2.0, tol)?; + let ry = snap(ry, height / 2.0, tol)?; + if (rx == 0.0) != (ry == 0.0) { + return None; + } + let inner = ([min[0] + rx, min[1] + ry], [max[0] - rx, max[1] - ry]); + let on_outline = |p: &[f64; 2]| { + let q = [p[0].clamp(inner.0[0], inner.1[0]), p[1].clamp(inner.0[1], inner.1[1])]; + let d = [p[0] - q[0], p[1] - q[1]]; + if rx == 0.0 { + // Square corners: on an edge of the box. + (p[0] - min[0]).abs() <= tol || (p[0] - max[0]).abs() <= tol || (p[1] - min[1]).abs() <= tol || (p[1] - max[1]).abs() <= tol + } else if d == [0.0, 0.0] { + false + } else { + let e = (d[0] / rx).hypot(d[1] / ry); + (e - 1.0).abs() * rx.min(ry) <= tol || (d[0] == 0.0 && (d[1].abs() - ry).abs() <= tol) || (d[1] == 0.0 && (d[0].abs() - rx).abs() <= tol) + } + }; + if !points.iter().all(on_outline) { + return None; + } + // Every point is on the outline; it also has to go all the way round once. + let expected = width * height - (4.0 - std::f64::consts::PI) * rx * ry; + if (area(&points).abs() - expected).abs() > 0.01 * expected { + return None; + } + if (rx - width / 2.0).abs() <= tol && (ry - height / 2.0).abs() <= tol { + return Some(Primitive::Ellipse { cx: min[0] + width / 2.0, cy: min[1] + height / 2.0, rx: width / 2.0, ry: height / 2.0 }); + } + Some(Primitive::Rect { x: min[0], y: min[1], width, height, rx, ry }) +} + +/// `value` within `tol` of 0 or `half` is snapped there; past `half` it isn't a corner radius. +fn snap(value: f64, half: f64, tol: f64) -> Option { + if !value.is_finite() || value < -tol || value > half + tol { + return None; + } + Some(if value <= tol { + 0.0 + } else if (value - half).abs() <= tol { + half + } else { + value + }) +} + +/// Points of a contour. +type Points = Vec<[f64; 2]>; + +/// The segment ends of one closed contour, and all its points (ends and curve samples), or +/// `None` for anything else: several contours, an open one, or too many segments. +fn contour(segments: &[Segment]) -> Option<(Points, Points)> { + if segments.len() > MAX_SEGMENTS + 2 { + return None; + } + let (first, rest) = segments.split_first()?; + let Segment::MoveTo(start) = *first else { return None }; + let mut points = vec![start]; + let mut ends = vec![start]; + let mut at = start; + let mut closed = false; + for segment in rest { + if closed { + return None; + } + match *segment { + Segment::MoveTo(_) => return None, + Segment::LineTo(p) => { + points.push(p); + ends.push(p); + at = p; + } + Segment::QuadTo(c, p) => { + for t in samples() { + let u = 1.0 - t; + points.push([u * u * at[0] + 2.0 * u * t * c[0] + t * t * p[0], u * u * at[1] + 2.0 * u * t * c[1] + t * t * p[1]]); + } + points.push(p); + ends.push(p); + at = p; + } + Segment::CubicTo(c1, c2, p) => { + for t in samples() { + let u = 1.0 - t; + let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t); + points.push([a * at[0] + b * c1[0] + c * c2[0] + d * p[0], a * at[1] + b * c1[1] + c * c2[1] + d * p[1]]); + } + points.push(p); + ends.push(p); + at = p; + } + Segment::Close => closed = true, + } + } + let ends_at_start = (at[0] - start[0]).abs() < 1e-9 && (at[1] - start[1]).abs() < 1e-9; + (closed || ends_at_start).then_some((ends, points)) +} + +/// The signed area of the polygon through `points`. +fn area(points: &[[f64; 2]]) -> f64 { + let n = points.len(); + (0..n) + .map(|i| { + let (a, b) = (points[i], points[(i + 1) % n]); + a[0] * b[1] - b[0] * a[1] + }) + .sum::() + / 2.0 +} + +#[cfg(test)] +#[path = "primitive_tests.rs"] +mod tests; diff --git a/crates/svg/src/tree/primitive_tests.rs b/crates/svg/src/tree/primitive_tests.rs new file mode 100644 index 000000000..81f4c0979 --- /dev/null +++ b/crates/svg/src/tree/primitive_tests.rs @@ -0,0 +1,116 @@ +#![allow(clippy::unwrap_used, clippy::panic, clippy::indexing_slicing, clippy::float_cmp)] + +use super::*; +use crate::tree::document::{Document, Node}; +use crate::tree::{Limits, parse, usvg}; + +/// The segments usvg makes of `element`, the only shape in a document. +fn segments(element: &str) -> Vec { + let svg = format!(r#"{element}"#); + let tree = parse(svg.as_bytes(), &Limits::default(), &usvg::Options::default()).unwrap(); + let document = Document::from_tree(&tree, 16); + fn first(nodes: &[Node]) -> Option> { + nodes.iter().find_map(|n| match n { + Node::Path(p) => Some(p.segments.clone()), + Node::Group { children, .. } => first(children), + Node::Image(_) => None, + }) + } + first(&document.nodes).unwrap() +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-3 +} + +#[test] +fn a_rect_is_a_rect() { + let Some(Primitive::Rect { x, y, width, height, rx, ry }) = recognize(&segments(r#""#)) else { + panic!() + }; + assert_eq!((x, y, width, height, rx, ry), (10.0, 20.0, 30.0, 40.0, 0.0, 0.0)); +} + +#[test] +fn a_rounded_rect_keeps_its_radii() { + for (attrs, want) in [(r#"rx="5""#, (5.0, 5.0)), (r#"rx="6" ry="3""#, (6.0, 3.0)), (r#"ry="4""#, (4.0, 4.0))] { + let element = format!(r#""#); + let Some(Primitive::Rect { x, y, width, height, rx, ry }) = recognize(&segments(&element)) else { panic!("{element}") }; + assert!(near(x, 10.0) && near(y, 20.0) && near(width, 30.0) && near(height, 40.0), "{element}"); + assert!(near(rx, want.0) && near(ry, want.1), "{element}: {rx} {ry}"); + } +} + +#[test] +fn circles_and_ellipses_are_ellipses() { + for (element, want) in [ + (r#""#, (50.0, 60.0, 25.0, 25.0)), + (r#""#, (50.0, 60.0, 40.0, 10.0)), + // A rectangle whose corners meet in the middle is an ellipse too. + (r#""#, (10.0, 5.0, 10.0, 5.0)), + ] { + let Some(Primitive::Ellipse { cx, cy, rx, ry }) = recognize(&segments(element)) else { panic!("{element}") }; + assert!(near(cx, want.0) && near(cy, want.1) && near(rx, want.2) && near(ry, want.3), "{element}: {cx} {cy} {rx} {ry}"); + } +} + +#[test] +fn other_paths_are_not_primitives() { + for element in [ + // A triangle on the edges of its box encloses half of it. + r#""#, + // Open, or two contours. + r#""#, + r#""#, + // A rectangle drawn twice, a diamond, a star. + r#""#, + r#""#, + r#""#, + // A curve that bulges past a circle's outline. + r#""#, + ] { + assert_eq!(recognize(&segments(element)), None, "{element}"); + } +} + +#[test] +fn degenerate_and_oversized_input_is_refused() { + assert_eq!(recognize(&[]), None); + assert_eq!(recognize(&[Segment::LineTo([1.0, 1.0])]), None); + assert_eq!(recognize(&[Segment::MoveTo([0.0, 0.0]), Segment::LineTo([10.0, 0.0]), Segment::Close]), None, "no height"); + let nan = [Segment::MoveTo([f64::NAN, 0.0]), Segment::LineTo([1.0, 0.0]), Segment::LineTo([1.0, 1.0]), Segment::Close]; + assert_eq!(recognize(&nan), None); + let mut long = vec![Segment::MoveTo([0.0, 0.0])]; + long.extend((0..100).map(|i| Segment::LineTo([f64::from(i % 2) * 10.0, 0.0]))); + long.push(Segment::Close); + assert_eq!(recognize(&long), None); +} + +#[test] +fn hand_written_segments_are_recognised_too() { + // Square corners written clockwise from the bottom left, closed by returning to the start. + let square = [ + Segment::MoveTo([0.0, 10.0]), + Segment::LineTo([0.0, 0.0]), + Segment::LineTo([10.0, 0.0]), + Segment::LineTo([10.0, 10.0]), + Segment::LineTo([0.0, 10.0]), + ]; + assert_eq!(recognize(&square), Some(Primitive::Rect { x: 0.0, y: 0.0, width: 10.0, height: 10.0, rx: 0.0, ry: 0.0 })); + // A circle from four cubic quarters, through Path::primitive. + let k = 0.552_284_749_830_793_6 * 5.0; + let path = crate::tree::document::Path { + segments: vec![ + Segment::MoveTo([10.0, 5.0]), + Segment::CubicTo([10.0, 5.0 + k], [5.0 + k, 10.0], [5.0, 10.0]), + Segment::CubicTo([5.0 - k, 10.0], [0.0, 5.0 + k], [0.0, 5.0]), + Segment::CubicTo([0.0, 5.0 - k], [5.0 - k, 0.0], [5.0, 0.0]), + Segment::CubicTo([5.0 + k, 0.0], [10.0, 5.0 - k], [10.0, 5.0]), + Segment::Close, + ], + fill: None, + stroke: None, + source_path: crate::tree::document::NodePath::default(), + }; + assert_eq!(path.primitive(), Some(Primitive::Ellipse { cx: 5.0, cy: 5.0, rx: 5.0, ry: 5.0 })); +}