Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

refactor(svg): replace sampled geometry with kurbo

ldm0aa8cd2ecb3f4
diff --git a/Cargo.lock b/Cargo.lock
index ea7b5f060..88127357f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2715,6 +2715,7 @@ dependencies = [
name = "moli-svg"
version = "0.1.0"
dependencies = [
+ "kurbo",
"moli-css-parse",
"svgtypes",
]
diff --git a/moli-svg/Cargo.toml b/moli-svg/Cargo.toml
index 601269935..b3f12d0db 100644
--- a/moli-svg/Cargo.toml
+++ b/moli-svg/Cargo.toml
@@ -5,6 +5,7 @@ version = "0.1.0"
edition = "2024"
[dependencies]
+kurbo = "=0.13.1"
moli-css-parse = { path = "../moli-css-parse" }
svgtypes = "0.16.1"
diff --git a/moli-svg/src/geometry.rs b/moli-svg/src/geometry.rs
index f3fe8f74f..449d6959d 100644
--- a/moli-svg/src/geometry.rs
+++ b/moli-svg/src/geometry.rs
@@ -1,5 +1,13 @@
use crate::helpers::svg_number_list;
-use crate::path::path_geometry_segments;
+use crate::path::path_geometry;
+use kurbo::{
+ Arc, BezPath, Circle, Ellipse, ParamCurve, ParamCurveArclen, ParamCurveExtrema,
+ ParamCurveNearest, PathEl, PathSeg, Point, Rect, Shape,
+};
+
+const SHAPE_PATH_TOLERANCE: f64 = 0.1;
+const ARC_LENGTH_ACCURACY: f64 = 1e-6;
+const FILL_BOUNDARY_EPSILON: f64 = 1e-9;
#[derive(Clone, Copy, Debug)]
pub struct SvgGeometryPoint {
@@ -15,17 +23,16 @@ impl SvgGeometryPoint {
#[derive(Clone, Copy, Debug)]
pub struct SvgGeometrySegment {
- start: SvgGeometryPoint,
- end: SvgGeometryPoint,
+ inner: PathSeg,
}
impl SvgGeometrySegment {
- pub(crate) fn new(start: SvgGeometryPoint, end: SvgGeometryPoint) -> Self {
- Self { start, end }
+ fn new(inner: PathSeg) -> Self {
+ Self { inner }
}
pub fn length(&self) -> f64 {
- (self.end.x - self.start.x).hypot(self.end.y - self.start.y)
+ self.inner.arclen(ARC_LENGTH_ACCURACY)
}
}
@@ -75,113 +82,41 @@ pub enum SvgGeometryElement {
}
pub fn segments_for_element(element: SvgGeometryElement) -> Vec<SvgGeometrySegment> {
- match element {
- SvgGeometryElement::Circle { cx, cy, r } => circle_segments(cx, cy, r),
- SvgGeometryElement::Ellipse { cx, cy, rx, ry } => ellipse_segments(cx, cy, rx, ry),
- SvgGeometryElement::Line { x1, y1, x2, y2 } => {
- vec![SvgGeometrySegment::new(
- SvgGeometryPoint::new(x1, y1),
- SvgGeometryPoint::new(x2, y2),
- )]
- }
- SvgGeometryElement::Path { d } => path_geometry_segments(&d).unwrap_or_default(),
- SvgGeometryElement::Polygon { points } => {
- poly_points_geometry_segments(&points, true).unwrap_or_default()
- }
- SvgGeometryElement::Polyline { points } => {
- poly_points_geometry_segments(&points, false).unwrap_or_default()
- }
- SvgGeometryElement::Rect {
- x,
- y,
- width,
- height,
- rx,
- ry,
- } => rect_segments(x, y, width, height, rx, ry),
- }
+ geometry_path(&element)
+ .unwrap_or_default()
+ .segments()
+ .map(SvgGeometrySegment::new)
+ .collect()
}
pub fn bounding_box_for_segments(segments: &[SvgGeometrySegment]) -> Option<SvgGeometryBox> {
- let first = segments.first()?;
- let mut min_x = first.start.x.min(first.end.x);
- let mut min_y = first.start.y.min(first.end.y);
- let mut max_x = first.start.x.max(first.end.x);
- let mut max_y = first.start.y.max(first.end.y);
- for segment in &segments[1..] {
- min_x = min_x.min(segment.start.x).min(segment.end.x);
- min_y = min_y.min(segment.start.y).min(segment.end.y);
- max_x = max_x.max(segment.start.x).max(segment.end.x);
- max_y = max_y.max(segment.start.y).max(segment.end.y);
- }
+ let mut segments = segments.iter();
+ let first = segments.next()?;
+ let bounds = segments.fold(
+ ParamCurveExtrema::bounding_box(&first.inner),
+ |bounds, segment| bounds.union(ParamCurveExtrema::bounding_box(&segment.inner)),
+ );
Some(SvgGeometryBox {
- x: min_x,
- y: min_y,
- width: max_x - min_x,
- height: max_y - min_y,
+ x: bounds.x0,
+ y: bounds.y0,
+ width: bounds.width(),
+ height: bounds.height(),
})
}
pub fn is_point_in_fill(element: &SvgGeometryElement, point: SvgGeometryPoint) -> bool {
- match element {
- SvgGeometryElement::Circle { cx, cy, r } => {
- *r > 0.0 && (point.x - cx).hypot(point.y - cy) <= *r
- }
- SvgGeometryElement::Ellipse { cx, cy, rx, ry } => {
- if *rx <= 0.0 || *ry <= 0.0 {
- return false;
- }
- let x = (point.x - cx) / rx;
- let y = (point.y - cy) / ry;
- x * x + y * y <= 1.0
- }
- SvgGeometryElement::Line { .. } => false,
- SvgGeometryElement::Path { d } => path_geometry_segments(d)
- .is_some_and(|segments| is_point_in_closed_segments(&segments, point)),
- SvgGeometryElement::Polygon { points } => poly_points_geometry_segments(points, true)
- .is_some_and(|segments| is_point_in_closed_segments(&segments, point)),
- SvgGeometryElement::Polyline { points } => poly_points_geometry_segments(points, false)
- .is_some_and(|segments| is_point_in_closed_segments(&segments, point)),
- SvgGeometryElement::Rect {
- x,
- y,
- width,
- height,
- rx,
- ry,
- } => {
- if *width <= 0.0
- || *height <= 0.0
- || point.x < *x
- || point.x > *x + *width
- || point.y < *y
- || point.y > *y + *height
- {
- return false;
- }
- let (rx, ry) = normalized_rect_radii(*width, *height, *rx, *ry);
- if rx == 0.0 || ry == 0.0 {
- return true;
- }
- let corner_center_x = if point.x < *x + rx {
- *x + rx
- } else if point.x > *x + *width - rx {
- *x + *width - rx
- } else {
- return true;
- };
- let corner_center_y = if point.y < *y + ry {
- *y + ry
- } else if point.y > *y + *height - ry {
- *y + *height - ry
- } else {
- return true;
- };
- let dx = (point.x - corner_center_x) / rx;
- let dy = (point.y - corner_center_y) / ry;
- dx * dx + dy * dy <= 1.0
- }
+ if matches!(element, SvgGeometryElement::Line { .. }) {
+ return false;
}
+ geometry_path(element).is_some_and(|path| {
+ let path = close_subpaths_for_fill(&path);
+ let point = Point::new(point.x, point.y);
+ path.winding(point) != 0
+ || path.segments().any(|segment| {
+ segment.nearest(point, FILL_BOUNDARY_EPSILON).distance_sq
+ <= FILL_BOUNDARY_EPSILON.powi(2)
+ })
+ })
}
pub fn point_at_length(segments: &[SvgGeometrySegment], distance: f64) -> SvgGeometryPoint {
@@ -189,7 +124,7 @@ pub fn point_at_length(segments: &[SvgGeometrySegment], distance: f64) -> SvgGeo
return SvgGeometryPoint::new(0.0, 0.0);
};
if distance <= 0.0 {
- return first.start;
+ return svg_point(first.inner.start());
}
let mut remaining = distance;
for segment in segments {
@@ -198,75 +133,58 @@ pub fn point_at_length(segments: &[SvgGeometrySegment], distance: f64) -> SvgGeo
continue;
}
if remaining <= length {
- let t = remaining / length;
- return SvgGeometryPoint::new(
- segment.start.x + (segment.end.x - segment.start.x) * t,
- segment.start.y + (segment.end.y - segment.start.y) * t,
- );
+ let parameter = segment.inner.inv_arclen(remaining, ARC_LENGTH_ACCURACY);
+ return svg_point(segment.inner.eval(parameter));
}
remaining -= length;
}
segments
.last()
- .map(|segment| segment.end)
+ .map(|segment| svg_point(segment.inner.end()))
.unwrap_or(SvgGeometryPoint::new(0.0, 0.0))
}
-fn circle_segments(cx: f64, cy: f64, r: f64) -> Vec<SvgGeometrySegment> {
- if r <= 0.0 {
- return Vec::new();
- }
- sampled_closed_parametric_segments(64, |theta| {
- SvgGeometryPoint::new(cx + r * theta.cos(), cy + r * theta.sin())
- })
-}
-
-fn ellipse_segments(cx: f64, cy: f64, rx: f64, ry: f64) -> Vec<SvgGeometrySegment> {
- if rx <= 0.0 || ry <= 0.0 {
- return Vec::new();
- }
- sampled_closed_parametric_segments(96, |theta| {
- SvgGeometryPoint::new(cx + rx * theta.cos(), cy + ry * theta.sin())
- })
-}
-
-fn sampled_closed_parametric_segments(
- steps: usize,
- point_at_angle: impl Fn(f64) -> SvgGeometryPoint,
-) -> Vec<SvgGeometrySegment> {
- let mut points = Vec::with_capacity(steps);
- for index in 0..steps {
- let theta = (index as f64 / steps as f64) * std::f64::consts::TAU;
- points.push(point_at_angle(theta));
+fn geometry_path(element: &SvgGeometryElement) -> Option<BezPath> {
+ match element {
+ SvgGeometryElement::Circle { cx, cy, r } => Some(if *r > 0.0 {
+ Circle::new(Point::new(*cx, *cy), *r).to_path(SHAPE_PATH_TOLERANCE)
+ } else {
+ BezPath::new()
+ }),
+ SvgGeometryElement::Ellipse { cx, cy, rx, ry } => Some(if *rx > 0.0 && *ry > 0.0 {
+ Ellipse::new(Point::new(*cx, *cy), (*rx, *ry), 0.0).to_path(SHAPE_PATH_TOLERANCE)
+ } else {
+ BezPath::new()
+ }),
+ SvgGeometryElement::Line { x1, y1, x2, y2 } => {
+ let mut path = BezPath::new();
+ path.move_to((*x1, *y1));
+ path.line_to((*x2, *y2));
+ Some(path)
+ }
+ SvgGeometryElement::Path { d } => path_geometry(d),
+ SvgGeometryElement::Polygon { points } => poly_points_geometry_path(points, true),
+ SvgGeometryElement::Polyline { points } => poly_points_geometry_path(points, false),
+ SvgGeometryElement::Rect {
+ x,
+ y,
+ width,
+ height,
+ rx,
+ ry,
+ } => Some(rect_path(*x, *y, *width, *height, *rx, *ry)),
}
- segments_from_points(&points, true)
}
-fn rect_segments(
- x: f64,
- y: f64,
- width: f64,
- height: f64,
- rx: f64,
- ry: f64,
-) -> Vec<SvgGeometrySegment> {
+fn rect_path(x: f64, y: f64, width: f64, height: f64, rx: f64, ry: f64) -> BezPath {
if width <= 0.0 || height <= 0.0 {
- return Vec::new();
+ return BezPath::new();
}
let (rx, ry) = normalized_rect_radii(width, height, rx, ry);
if rx > 0.0 && ry > 0.0 {
- return rounded_rect_segments(x, y, width, height, rx, ry);
+ return rounded_rect_path(x, y, width, height, rx, ry);
}
- let top_left = SvgGeometryPoint::new(x, y);
- let top_right = SvgGeometryPoint::new(x + width, y);
- let bottom_right = SvgGeometryPoint::new(x + width, y + height);
- let bottom_left = SvgGeometryPoint::new(x, y + height);
- vec![
- SvgGeometrySegment::new(top_left, top_right),
- SvgGeometrySegment::new(top_right, bottom_right),
- SvgGeometrySegment::new(bottom_right, bottom_left),
- SvgGeometrySegment::new(bottom_left, top_left),
- ]
+ Rect::new(x, y, x + width, y + height).to_path(SHAPE_PATH_TOLERANCE)
}
fn normalized_rect_radii(width: f64, height: f64, rx: f64, ry: f64) -> (f64, f64) {
@@ -276,145 +194,87 @@ fn normalized_rect_radii(width: f64, height: f64, rx: f64, ry: f64) -> (f64, f64
(rx.min(width / 2.0), ry.min(height / 2.0))
}
-fn rounded_rect_segments(
- x: f64,
- y: f64,
- width: f64,
- height: f64,
- rx: f64,
- ry: f64,
-) -> Vec<SvgGeometrySegment> {
- let mut points = vec![
- SvgGeometryPoint::new(x + rx, y),
- SvgGeometryPoint::new(x + width - rx, y),
- ];
- push_rounded_rect_corner_points(&mut points, x + width - rx, y + ry, -90.0, 0.0, rx, ry);
- points.push(SvgGeometryPoint::new(x + width, y + height - ry));
- push_rounded_rect_corner_points(
- &mut points,
- x + width - rx,
- y + height - ry,
- 0.0,
- 90.0,
- rx,
- ry,
- );
- points.push(SvgGeometryPoint::new(x + rx, y + height));
- push_rounded_rect_corner_points(&mut points, x + rx, y + height - ry, 90.0, 180.0, rx, ry);
- points.push(SvgGeometryPoint::new(x, y + ry));
- push_rounded_rect_corner_points(&mut points, x + rx, y + ry, 180.0, 270.0, rx, ry);
- segments_from_points(&points, true)
+fn rounded_rect_path(x: f64, y: f64, width: f64, height: f64, rx: f64, ry: f64) -> BezPath {
+ let mut path = BezPath::new();
+ path.move_to((x + rx, y));
+ path.line_to((x + width - rx, y));
+ append_quarter_ellipse(&mut path, x + width - rx, y + ry, rx, ry, -90.0);
+ path.line_to((x + width, y + height - ry));
+ append_quarter_ellipse(&mut path, x + width - rx, y + height - ry, rx, ry, 0.0);
+ path.line_to((x + rx, y + height));
+ append_quarter_ellipse(&mut path, x + rx, y + height - ry, rx, ry, 90.0);
+ path.line_to((x, y + ry));
+ append_quarter_ellipse(&mut path, x + rx, y + ry, rx, ry, 180.0);
+ path.close_path();
+ path
}
-fn push_rounded_rect_corner_points(
- points: &mut Vec<SvgGeometryPoint>,
+fn append_quarter_ellipse(
+ path: &mut BezPath,
cx: f64,
cy: f64,
- start_degrees: f64,
- end_degrees: f64,
rx: f64,
ry: f64,
+ start_degrees: f64,
) {
- const ROUNDED_RECT_ARC_STEPS: usize = 8;
- for step in 1..=ROUNDED_RECT_ARC_STEPS {
- let t = step as f64 / ROUNDED_RECT_ARC_STEPS as f64;
- let angle = (start_degrees + (end_degrees - start_degrees) * t).to_radians();
- points.push(SvgGeometryPoint::new(
- cx + rx * angle.cos(),
- cy + ry * angle.sin(),
- ));
- }
+ path.extend(
+ Arc::new(
+ Point::new(cx, cy),
+ (rx, ry),
+ start_degrees.to_radians(),
+ std::f64::consts::FRAC_PI_2,
+ 0.0,
+ )
+ .append_iter(SHAPE_PATH_TOLERANCE),
+ );
}
-pub(crate) fn poly_points_geometry_segments(
- raw: &str,
- close: bool,
-) -> Option<Vec<SvgGeometrySegment>> {
+fn poly_points_geometry_path(raw: &str, close: bool) -> Option<BezPath> {
let coordinates = svg_number_list(raw)?;
if coordinates.len() < 4 || !coordinates.len().is_multiple_of(2) {
return None;
}
- let mut points = Vec::with_capacity(coordinates.len() / 2);
- for pair in coordinates.chunks_exact(2) {
- points.push(SvgGeometryPoint::new(pair[0], pair[1]));
+ let mut coordinates = coordinates.chunks_exact(2);
+ let first = coordinates.next()?;
+ let mut path = BezPath::new();
+ path.move_to((first[0], first[1]));
+ for pair in coordinates {
+ path.line_to((pair[0], pair[1]));
}
- Some(segments_from_points(&points, close))
-}
-
-fn is_point_in_closed_segments(segments: &[SvgGeometrySegment], point: SvgGeometryPoint) -> bool {
- if segments.is_empty() {
- return false;
- }
- if segments
- .iter()
- .any(|segment| point_is_on_segment(point, segment))
- {
- return true;
- }
-
- let mut inside = false;
- for segment in segments {
- toggle_ray_crossing(segment, point, &mut inside);
- }
- if let Some(closing_segment) = closing_segment_for_segments(segments) {
- toggle_ray_crossing(&closing_segment, point, &mut inside);
- }
- inside
-}
-
-fn closing_segment_for_segments(segments: &[SvgGeometrySegment]) -> Option<SvgGeometrySegment> {
- let first = segments.first()?;
- let last = segments.last()?;
- if points_are_close(last.end, first.start) {
- None
- } else {
- Some(SvgGeometrySegment::new(last.end, first.start))
+ if close {
+ path.close_path();
}
+ Some(path)
}
-fn toggle_ray_crossing(segment: &SvgGeometrySegment, point: SvgGeometryPoint, inside: &mut bool) {
- let y1 = segment.start.y;
- let y2 = segment.end.y;
- if (y1 > point.y) == (y2 > point.y) {
- return;
- }
- let x_intersection =
- segment.start.x + (point.y - y1) * (segment.end.x - segment.start.x) / (y2 - y1);
- if point.x < x_intersection {
- *inside = !*inside;
- }
-}
-
-fn point_is_on_segment(point: SvgGeometryPoint, segment: &SvgGeometrySegment) -> bool {
- const EPSILON: f64 = 1e-9;
- let dx = segment.end.x - segment.start.x;
- let dy = segment.end.y - segment.start.y;
- let cross = (point.x - segment.start.x) * dy - (point.y - segment.start.y) * dx;
- if cross.abs() > EPSILON {
- return false;
+fn close_subpaths_for_fill(path: &BezPath) -> BezPath {
+ let mut closed = BezPath::new();
+ let mut subpath_is_open = false;
+ for element in path.elements() {
+ match *element {
+ PathEl::MoveTo(point) => {
+ if subpath_is_open {
+ closed.close_path();
+ }
+ closed.move_to(point);
+ subpath_is_open = true;
+ }
+ PathEl::ClosePath => {
+ closed.close_path();
+ subpath_is_open = false;
+ }
+ element => {
+ closed.push(element);
+ subpath_is_open = true;
+ }
+ }
}
- let dot = (point.x - segment.start.x) * dx + (point.y - segment.start.y) * dy;
- if dot < -EPSILON {
- return false;
+ if subpath_is_open {
+ closed.close_path();
}
- dot <= dx * dx + dy * dy + EPSILON
+ closed
}
-fn points_are_close(a: SvgGeometryPoint, b: SvgGeometryPoint) -> bool {
- const EPSILON: f64 = 1e-9;
- (a.x - b.x).abs() <= EPSILON && (a.y - b.y).abs() <= EPSILON
-}
-
-fn segments_from_points(points: &[SvgGeometryPoint], close: bool) -> Vec<SvgGeometrySegment> {
- if points.len() < 2 {
- return Vec::new();
- }
- let mut segments = points
- .windows(2)
- .map(|pair| SvgGeometrySegment::new(pair[0], pair[1]))
- .collect::<Vec<_>>();
- if close && let Some(last) = points.last().copied() {
- segments.push(SvgGeometrySegment::new(last, points[0]));
- }
- segments
+fn svg_point(point: Point) -> SvgGeometryPoint {
+ SvgGeometryPoint::new(point.x, point.y)
}
diff --git a/moli-svg/src/lib.rs b/moli-svg/src/lib.rs
index 561d9f689..aa235e4e7 100644
--- a/moli-svg/src/lib.rs
+++ b/moli-svg/src/lib.rs
@@ -20,8 +20,6 @@ pub use transform::{
#[cfg(test)]
mod tests {
- use crate::geometry::poly_points_geometry_segments;
- use crate::path::path_geometry_segments;
use crate::{
SvgGeometryElement, SvgGeometryPoint, SvgGeometrySegment, SvgLengthUnit,
SvgMatrixComponents, SvgTransform, SvgTransformKind, bounding_box_for_segments,
@@ -30,6 +28,16 @@ mod tests {
segments_for_element, serialize_number, serialize_transform_list,
};
+ fn path_segments(raw: &str) -> Vec<SvgGeometrySegment> {
+ segments_for_element(SvgGeometryElement::Path { d: raw.to_owned() })
+ }
+
+ fn polyline_segments(raw: &str) -> Vec<SvgGeometrySegment> {
+ segments_for_element(SvgGeometryElement::Polyline {
+ points: raw.to_owned(),
+ })
+ }
+
fn assert_close(actual: f64, expected: f64) {
assert!(
(actual - expected).abs() < 1e-9,
@@ -46,7 +54,7 @@ mod tests {
#[test]
fn path_geometry_handles_line_commands_and_points() {
- let segments = path_geometry_segments("M 0 0 L 3 4 H 7 V 1").unwrap();
+ let segments = path_segments("M 0 0 L 3 4 H 7 V 1");
let total = segments.iter().map(|segment| segment.length()).sum::<f64>();
assert_close(total, 12.0);
@@ -54,7 +62,7 @@ mod tests {
assert_close(point.x, 5.0);
assert_close(point.y, 4.0);
- let compact = path_geometry_segments("M10-20l30.1.5.1-20z").unwrap();
+ let compact = path_segments("M10-20l30.1.5.1-20z");
let compact_end = point_at_length(&compact, 10_000.0);
assert_close(compact_end.x, 10.0);
assert_close(compact_end.y, -20.0);
@@ -62,7 +70,7 @@ mod tests {
#[test]
fn path_geometry_handles_relative_commands_and_close_path() {
- let segments = path_geometry_segments("m 1 1 l 3 0 v 4 h -3 z").unwrap();
+ let segments = path_segments("m 1 1 l 3 0 v 4 h -3 z");
let total = segments.iter().map(|segment| segment.length()).sum::<f64>();
assert_close(total, 14.0);
@@ -72,14 +80,14 @@ mod tests {
}
#[test]
- fn path_geometry_samples_cubic_and_quadratic_curves() {
- let cubic = path_geometry_segments("M 0 0 C 0 10 10 10 10 0").unwrap();
+ fn path_geometry_preserves_cubic_and_quadratic_curves() {
+ let cubic = path_segments("M 0 0 C 0 10 10 10 10 0");
assert!(cubic.iter().map(|segment| segment.length()).sum::<f64>() > 19.0);
let cubic_end = point_at_length(&cubic, 10_000.0);
assert_close(cubic_end.x, 10.0);
assert_close(cubic_end.y, 0.0);
- let quadratic = path_geometry_segments("M 0 0 Q 5 10 10 0 T 20 0").unwrap();
+ let quadratic = path_segments("M 0 0 Q 5 10 10 0 T 20 0");
assert!(
quadratic
.iter()
@@ -93,15 +101,15 @@ mod tests {
}
#[test]
- fn path_geometry_samples_arc_curves() {
- let arc = path_geometry_segments("M 0 0 A 10 10 0 0 1 20 0").unwrap();
+ fn path_geometry_converts_svg_arcs_to_bezier_curves() {
+ let arc = path_segments("M 0 0 A 10 10 0 0 1 20 0");
let total = arc.iter().map(|segment| segment.length()).sum::<f64>();
assert_near(total, std::f64::consts::PI * 10.0, 0.1);
let arc_end = point_at_length(&arc, 10_000.0);
assert_close(arc_end.x, 20.0);
assert_close(arc_end.y, 0.0);
- let relative_arc = path_geometry_segments("M 10 10 a 5 5 0 0 0 10 0").unwrap();
+ let relative_arc = path_segments("M 10 10 a 5 5 0 0 0 10 0");
let relative_end = point_at_length(&relative_arc, 10_000.0);
assert_close(relative_end.x, 20.0);
assert_close(relative_end.y, 10.0);
@@ -123,7 +131,7 @@ mod tests {
assert_close(rect_box.width, 30.0);
assert_close(rect_box.height, 40.0);
- let path = path_geometry_segments("M 0 0 L 3 4 H 7 V 1").unwrap();
+ let path = path_segments("M 0 0 L 3 4 H 7 V 1");
let path_box = bounding_box_for_segments(&path).unwrap();
assert_close(path_box.x, 0.0);
assert_close(path_box.y, 0.0);
@@ -132,7 +140,7 @@ mod tests {
}
#[test]
- fn rounded_rect_geometry_samples_corner_arcs() {
+ fn rounded_rect_geometry_uses_elliptical_corner_arcs() {
let rect = segments_for_element(SvgGeometryElement::Rect {
x: 0.0,
y: 0.0,
@@ -142,7 +150,7 @@ mod tests {
ry: 50.0,
});
let length = rect.iter().map(SvgGeometrySegment::length).sum::<f64>();
- assert_near(length, 913.65, 0.1);
+ assert_near(length, 600.0 + std::f64::consts::PI * 100.0, 0.1);
let bbox = bounding_box_for_segments(&rect).unwrap();
assert_close(bbox.x, 0.0);
assert_close(bbox.y, 0.0);
@@ -172,8 +180,20 @@ mod tests {
ry: 0.0,
};
assert!(is_point_in_fill(&rect, SvgGeometryPoint::new(25.0, 30.0)));
+ assert!(is_point_in_fill(&rect, SvgGeometryPoint::new(10.0, 30.0)));
+ assert!(is_point_in_fill(&rect, SvgGeometryPoint::new(40.0, 30.0)));
+ assert!(is_point_in_fill(&rect, SvgGeometryPoint::new(25.0, 20.0)));
+ assert!(is_point_in_fill(&rect, SvgGeometryPoint::new(25.0, 60.0)));
assert!(!is_point_in_fill(&rect, SvgGeometryPoint::new(0.0, 0.0)));
+ let line = SvgGeometryElement::Line {
+ x1: 0.0,
+ y1: 0.0,
+ x2: 10.0,
+ y2: 10.0,
+ };
+ assert!(!is_point_in_fill(&line, SvgGeometryPoint::new(5.0, 5.0)));
+
let rounded_rect = SvgGeometryElement::Rect {
x: 0.0,
y: 0.0,
@@ -215,10 +235,44 @@ mod tests {
assert!(!is_point_in_fill(&path, SvgGeometryPoint::new(2.0, 8.0)));
}
+ #[test]
+ fn fill_containment_uses_nonzero_winding_and_closes_each_subpath() {
+ let same_direction_rings = SvgGeometryElement::Path {
+ d: "M0 0H10V10H0Z M2 2H8V8H2Z".to_owned(),
+ };
+ assert!(is_point_in_fill(
+ &same_direction_rings,
+ SvgGeometryPoint::new(5.0, 5.0)
+ ));
+
+ let open_subpaths = SvgGeometryElement::Path {
+ d: "M0 0L10 0L10 10 M20 0L30 0L30 10".to_owned(),
+ };
+ assert!(is_point_in_fill(
+ &open_subpaths,
+ SvgGeometryPoint::new(8.0, 2.0)
+ ));
+ assert!(is_point_in_fill(
+ &open_subpaths,
+ SvgGeometryPoint::new(28.0, 2.0)
+ ));
+ }
+
+ #[test]
+ fn curve_bounding_box_uses_bezier_extrema() {
+ let path = path_segments("M0 0 C100 100 100-100 200 0");
+ let bounds = bounding_box_for_segments(&path).unwrap();
+ let y_extent = 50.0 / 3.0 * 3.0_f64.sqrt();
+ assert_near(bounds.x, 0.0, 1e-9);
+ assert_near(bounds.y, -y_extent, 1e-9);
+ assert_near(bounds.width, 200.0, 1e-9);
+ assert_near(bounds.height, y_extent * 2.0, 1e-9);
+ }
+
#[test]
fn poly_points_geometry_rejects_odd_coordinates() {
- assert!(poly_points_geometry_segments("0 0 10", false).is_none());
- let compact = poly_points_geometry_segments("0,0 10-5 20.5.5", false).unwrap();
+ assert!(polyline_segments("0 0 10").is_empty());
+ let compact = polyline_segments("0,0 10-5 20.5.5");
assert_eq!(compact.len(), 2);
let compact_end = point_at_length(&compact, 10_000.0);
assert_close(compact_end.x, 20.5);
@@ -251,7 +305,7 @@ mod tests {
}
#[test]
- fn circle_and_ellipse_geometry_are_sampled_closed_shapes() {
+ fn circle_and_ellipse_geometry_are_bezier_paths() {
let circle = segments_for_element(SvgGeometryElement::Circle {
cx: 0.0,
cy: 0.0,
diff --git a/moli-svg/src/path.rs b/moli-svg/src/path.rs
index 32c87f080..e1f5caf9f 100644
--- a/moli-svg/src/path.rs
+++ b/moli-svg/src/path.rs
@@ -1,355 +1,25 @@
-use svgtypes::PathSegment;
-
-use crate::geometry::{SvgGeometryPoint, SvgGeometrySegment};
-
-pub(crate) fn path_geometry_segments(raw: &str) -> Option<Vec<SvgGeometrySegment>> {
- let mut parser = PathGeometryBuilder {
- current: SvgGeometryPoint::new(0.0, 0.0),
- subpath_start: SvgGeometryPoint::new(0.0, 0.0),
- last_cubic_control: None,
- last_quadratic_control: None,
- previous_command: None,
- segments: Vec::new(),
- };
- for segment in svgtypes::PathParser::from(raw) {
- parser.push_path_segment(segment.ok()?);
- }
- Some(parser.segments)
-}
-
-struct PathGeometryBuilder {
- current: SvgGeometryPoint,
- subpath_start: SvgGeometryPoint,
- last_cubic_control: Option<SvgGeometryPoint>,
- last_quadratic_control: Option<SvgGeometryPoint>,
- previous_command: Option<char>,
- segments: Vec<SvgGeometrySegment>,
-}
-
-impl PathGeometryBuilder {
- fn push_path_segment(&mut self, segment: PathSegment) {
- match segment {
- PathSegment::MoveTo { abs, x, y } => {
- let target = self.target_point(abs, x, y);
- self.current = target;
- self.subpath_start = target;
- self.clear_curve_controls();
- self.previous_command = Some(if abs { 'M' } else { 'm' });
- }
- PathSegment::LineTo { abs, x, y } => {
- let target = self.target_point(abs, x, y);
- self.push_line(target);
- self.clear_curve_controls();
- self.previous_command = Some(if abs { 'L' } else { 'l' });
- }
- PathSegment::HorizontalLineTo { abs, x } => {
- let target_x = if abs { x } else { self.current.x + x };
- self.push_line(SvgGeometryPoint::new(target_x, self.current.y));
- self.clear_curve_controls();
- self.previous_command = Some(if abs { 'H' } else { 'h' });
- }
- PathSegment::VerticalLineTo { abs, y } => {
- let target_y = if abs { y } else { self.current.y + y };
- self.push_line(SvgGeometryPoint::new(self.current.x, target_y));
- self.clear_curve_controls();
- self.previous_command = Some(if abs { 'V' } else { 'v' });
- }
- PathSegment::CurveTo {
- abs,
+use kurbo::BezPath;
+use svgtypes::{SimplePathSegment, SimplifyingPathParser};
+
+pub(crate) fn path_geometry(raw: &str) -> Option<BezPath> {
+ let mut path = BezPath::new();
+ for segment in SimplifyingPathParser::from(raw) {
+ match segment.ok()? {
+ SimplePathSegment::MoveTo { x, y } => path.move_to((x, y)),
+ SimplePathSegment::LineTo { x, y } => path.line_to((x, y)),
+ SimplePathSegment::CurveTo {
x1,
y1,
x2,
y2,
x,
y,
- } => {
- let control1 = self.target_point(abs, x1, y1);
- let control2 = self.target_point(abs, x2, y2);
- let target = self.target_point(abs, x, y);
- self.push_cubic(control1, control2, target);
- self.last_cubic_control = Some(control2);
- self.last_quadratic_control = None;
- self.previous_command = Some(if abs { 'C' } else { 'c' });
- }
- PathSegment::SmoothCurveTo { abs, x2, y2, x, y } => {
- let control1 = if self.previous_was_cubic() {
- self.last_cubic_control
- .map(|point| reflect_point(point, self.current))
- .unwrap_or(self.current)
- } else {
- self.current
- };
- let control2 = self.target_point(abs, x2, y2);
- let target = self.target_point(abs, x, y);
- self.push_cubic(control1, control2, target);
- self.last_cubic_control = Some(control2);
- self.last_quadratic_control = None;
- self.previous_command = Some(if abs { 'S' } else { 's' });
- }
- PathSegment::Quadratic { abs, x1, y1, x, y } => {
- let control = self.target_point(abs, x1, y1);
- let target = self.target_point(abs, x, y);
- self.push_quadratic(control, target);
- self.last_quadratic_control = Some(control);
- self.last_cubic_control = None;
- self.previous_command = Some(if abs { 'Q' } else { 'q' });
- }
- PathSegment::SmoothQuadratic { abs, x, y } => {
- let control = if self.previous_was_quadratic() {
- self.last_quadratic_control
- .map(|point| reflect_point(point, self.current))
- .unwrap_or(self.current)
- } else {
- self.current
- };
- let target = self.target_point(abs, x, y);
- self.push_quadratic(control, target);
- self.last_quadratic_control = Some(control);
- self.last_cubic_control = None;
- self.previous_command = Some(if abs { 'T' } else { 't' });
- }
- PathSegment::EllipticalArc {
- abs,
- rx,
- ry,
- x_axis_rotation,
- large_arc,
- sweep,
- x,
- y,
- } => {
- let target = self.target_point(abs, x, y);
- self.push_arc(rx, ry, x_axis_rotation, large_arc, sweep, target);
- self.clear_curve_controls();
- self.previous_command = Some(if abs { 'A' } else { 'a' });
- }
- PathSegment::ClosePath { abs } => {
- self.push_line(self.subpath_start);
- self.current = self.subpath_start;
- self.clear_curve_controls();
- self.previous_command = Some(if abs { 'Z' } else { 'z' });
+ } => path.curve_to((x1, y1), (x2, y2), (x, y)),
+ SimplePathSegment::Quadratic { x1, y1, x, y } => {
+ path.quad_to((x1, y1), (x, y));
}
+ SimplePathSegment::ClosePath => path.close_path(),
}
}
-
- fn target_point(&self, absolute: bool, x: f64, y: f64) -> SvgGeometryPoint {
- if absolute {
- SvgGeometryPoint::new(x, y)
- } else {
- SvgGeometryPoint::new(self.current.x + x, self.current.y + y)
- }
- }
-
- fn push_line(&mut self, target: SvgGeometryPoint) {
- self.segments
- .push(SvgGeometrySegment::new(self.current, target));
- self.current = target;
- }
-
- fn push_arc(
- &mut self,
- rx: f64,
- ry: f64,
- x_axis_rotation: f64,
- large_arc: bool,
- sweep: bool,
- target: SvgGeometryPoint,
- ) {
- let Some(arc) = SvgArcCenterParameters::from_endpoint(
- self.current,
- target,
- rx,
- ry,
- x_axis_rotation,
- large_arc,
- sweep,
- ) else {
- self.push_line(target);
- return;
- };
- let steps =
- ((arc.delta_theta.abs() / (std::f64::consts::PI / 16.0)).ceil() as usize).clamp(8, 64);
- let mut previous = self.current;
- for index in 1..=steps {
- let point = arc.point_at(index as f64 / steps as f64);
- self.segments.push(SvgGeometrySegment::new(previous, point));
- previous = point;
- }
- self.current = target;
- }
-
- fn push_cubic(
- &mut self,
- control1: SvgGeometryPoint,
- control2: SvgGeometryPoint,
- target: SvgGeometryPoint,
- ) {
- let start = self.current;
- self.push_sampled_curve(24, |t| cubic_point(start, control1, control2, target, t));
- self.current = target;
- }
-
- fn push_quadratic(&mut self, control: SvgGeometryPoint, target: SvgGeometryPoint) {
- let start = self.current;
- self.push_sampled_curve(20, |t| quadratic_point(start, control, target, t));
- self.current = target;
- }
-
- fn push_sampled_curve(&mut self, steps: usize, point_at_t: impl Fn(f64) -> SvgGeometryPoint) {
- let mut previous = self.current;
- for index in 1..=steps {
- let point = point_at_t(index as f64 / steps as f64);
- self.segments.push(SvgGeometrySegment::new(previous, point));
- previous = point;
- }
- }
-
- fn clear_curve_controls(&mut self) {
- self.last_cubic_control = None;
- self.last_quadratic_control = None;
- }
-
- fn previous_was_cubic(&self) -> bool {
- matches!(self.previous_command, Some('C' | 'c' | 'S' | 's'))
- }
-
- fn previous_was_quadratic(&self) -> bool {
- matches!(self.previous_command, Some('Q' | 'q' | 'T' | 't'))
- }
-}
-
-struct SvgArcCenterParameters {
- cx: f64,
- cy: f64,
- rx: f64,
- ry: f64,
- phi: f64,
- theta1: f64,
- delta_theta: f64,
-}
-
-impl SvgArcCenterParameters {
- fn from_endpoint(
- start: SvgGeometryPoint,
- end: SvgGeometryPoint,
- rx: f64,
- ry: f64,
- x_axis_rotation: f64,
- large_arc: bool,
- sweep: bool,
- ) -> Option<Self> {
- if (start.x == end.x && start.y == end.y) || rx == 0.0 || ry == 0.0 {
- return None;
- }
-
- let mut rx = rx.abs();
- let mut ry = ry.abs();
- let phi = x_axis_rotation.to_radians();
- let cos_phi = phi.cos();
- let sin_phi = phi.sin();
- let dx2 = (start.x - end.x) / 2.0;
- let dy2 = (start.y - end.y) / 2.0;
- let x1_prime = cos_phi * dx2 + sin_phi * dy2;
- let y1_prime = -sin_phi * dx2 + cos_phi * dy2;
-
- let radii_scale = x1_prime.powi(2) / rx.powi(2) + y1_prime.powi(2) / ry.powi(2);
- if radii_scale > 1.0 {
- let scale = radii_scale.sqrt();
- rx *= scale;
- ry *= scale;
- }
-
- let rx2 = rx.powi(2);
- let ry2 = ry.powi(2);
- let x1_prime2 = x1_prime.powi(2);
- let y1_prime2 = y1_prime.powi(2);
- let denominator = rx2 * y1_prime2 + ry2 * x1_prime2;
- if denominator == 0.0 {
- return None;
- }
- let numerator = rx2 * ry2 - rx2 * y1_prime2 - ry2 * x1_prime2;
- let sign = if large_arc == sweep { -1.0 } else { 1.0 };
- let coefficient = sign * (numerator / denominator).max(0.0).sqrt();
- let cx_prime = coefficient * (rx * y1_prime / ry);
- let cy_prime = coefficient * -(ry * x1_prime / rx);
- let cx = cos_phi * cx_prime - sin_phi * cy_prime + (start.x + end.x) / 2.0;
- let cy = sin_phi * cx_prime + cos_phi * cy_prime + (start.y + end.y) / 2.0;
-
- let start_vector =
- SvgGeometryPoint::new((x1_prime - cx_prime) / rx, (y1_prime - cy_prime) / ry);
- let end_vector =
- SvgGeometryPoint::new((-x1_prime - cx_prime) / rx, (-y1_prime - cy_prime) / ry);
- let theta1 = vector_angle(SvgGeometryPoint::new(1.0, 0.0), start_vector);
- let mut delta_theta = vector_angle(start_vector, end_vector);
- if !sweep && delta_theta > 0.0 {
- delta_theta -= std::f64::consts::TAU;
- } else if sweep && delta_theta < 0.0 {
- delta_theta += std::f64::consts::TAU;
- }
-
- Some(Self {
- cx,
- cy,
- rx,
- ry,
- phi,
- theta1,
- delta_theta,
- })
- }
-
- fn point_at(&self, t: f64) -> SvgGeometryPoint {
- let theta = self.theta1 + self.delta_theta * t;
- let cos_phi = self.phi.cos();
- let sin_phi = self.phi.sin();
- let x = self.rx * theta.cos();
- let y = self.ry * theta.sin();
- SvgGeometryPoint::new(
- self.cx + cos_phi * x - sin_phi * y,
- self.cy + sin_phi * x + cos_phi * y,
- )
- }
-}
-
-fn vector_angle(u: SvgGeometryPoint, v: SvgGeometryPoint) -> f64 {
- let dot = u.x * v.x + u.y * v.y;
- let cross = u.x * v.y - u.y * v.x;
- cross.atan2(dot)
-}
-
-fn reflect_point(point: SvgGeometryPoint, origin: SvgGeometryPoint) -> SvgGeometryPoint {
- SvgGeometryPoint::new(origin.x * 2.0 - point.x, origin.y * 2.0 - point.y)
-}
-
-fn cubic_point(
- start: SvgGeometryPoint,
- control1: SvgGeometryPoint,
- control2: SvgGeometryPoint,
- end: SvgGeometryPoint,
- t: f64,
-) -> SvgGeometryPoint {
- let mt = 1.0 - t;
- SvgGeometryPoint::new(
- mt.powi(3) * start.x
- + 3.0 * mt.powi(2) * t * control1.x
- + 3.0 * mt * t.powi(2) * control2.x
- + t.powi(3) * end.x,
- mt.powi(3) * start.y
- + 3.0 * mt.powi(2) * t * control1.y
- + 3.0 * mt * t.powi(2) * control2.y
- + t.powi(3) * end.y,
- )
-}
-
-fn quadratic_point(
- start: SvgGeometryPoint,
- control: SvgGeometryPoint,
- end: SvgGeometryPoint,
- t: f64,
-) -> SvgGeometryPoint {
- let mt = 1.0 - t;
- SvgGeometryPoint::new(
- mt.powi(2) * start.x + 2.0 * mt * t * control.x + t.powi(2) * end.x,
- mt.powi(2) * start.y + 2.0 * mt * t * control.y + t.powi(2) * end.y,
- )
+ Some(path)
}