Export a rectangle or ellipse only when the path is that shape.

A bowtie or a repeated corner stays a path, and ellipse handles must sit within a fraction of the radius, so a small bad curve is not rewritten as a circle. resvg renders of a real rectangle, circle, and ellipse match the canvas.
This commit is contained in:
Vikram Bhaskaran committed 2026-10-13 13:30:16 +11:00
1 parent 7bed916595
commit 1420507809
2 files changed
+116 -11

No files matched your search

+37 -11
View File
@@ -989,14 +989,39 @@ fn primitive_tag(path: &PathData, xf: Affine, mut num: impl FnMut(f64) -> String
fn upright_rect(path: &PathData) -> Option<Rect> {
let ([sp], Some(b)) = (path.subpaths.as_slice(), path.bounds()) else { return None };
let corner = |p: Point| ((p.x - b.x0).abs() < 1e-3 || (p.x - b.x1).abs() < 1e-3) && ((p.y - b.y0).abs() < 1e-3 || (p.y - b.y1).abs() < 1e-3);
(sp.closed
&& sp.anchors.len() == 4
&& (0..sp.segment_count()).all(|i| sp.segment_is_line(i))
&& sp.anchors.iter().all(|a| corner(a.p))
&& b.width() > 0.0
&& b.height() > 0.0)
.then_some(b)
if !sp.closed || sp.anchors.len() != 4 || b.width() <= 0.0 || b.height() <= 0.0 {
return None;
}
if (0..4).any(|i| !sp.segment_is_line(i)) {
return None;
}
let pts: [Point; 4] = std::array::from_fn(|i| sp.anchors[i].p);
// Four distinct corners. A repeated corner (a triangle stored as four anchors) is not a rect.
for i in 0..4 {
for j in (i + 1)..4 {
if pts[i].distance(pts[j]) <= 1e-3 {
return None;
}
}
}
let on = |a: f64, b: f64| (a - b).abs() <= 1e-3;
let mut horizontal = [false; 4];
for i in 0..4 {
let (a, c) = (pts[i], pts[(i + 1) % 4]);
let h = on(a.y, c.y) && !on(a.x, c.x);
let v = on(a.x, c.x) && !on(a.y, c.y);
if h == v {
// Diagonal, or a zero-length edge. A bowtie's crossing edges fail here.
return None;
}
horizontal[i] = h;
}
// Edges alternate horizontal and vertical, so the outline is the bounds, not a zigzag.
if (0..4).any(|i| horizontal[i] == horizontal[(i + 1) % 4]) {
return None;
}
let corner = |p: Point| (on(p.x, b.x0) || on(p.x, b.x1)) && (on(p.y, b.y0) || on(p.y, b.y1));
pts.iter().all(|p| corner(*p)).then_some(b)
}
/// A closed four-cubic ellipse whose anchors sit on the cardinal points.
@@ -1011,11 +1036,12 @@ fn axis_ellipse(path: &PathData) -> Option<(f64, f64, f64, f64)> {
return None;
}
let card = [Point::new(cx + rx, cy), Point::new(cx, cy + ry), Point::new(cx - rx, cy), Point::new(cx, cy - ry)];
let tol = 0.02 * rx.max(ry);
// Tight against the radii. A fixed 0.75 pt floor turned a 1 pt circle with bad handles into a circle.
let tol = 1e-3 * rx.max(ry);
let mut used = [false; 4];
let mut order = [0usize; 4];
for (i, a) in sp.anchors.iter().enumerate() {
let j = card.iter().position(|c| c.distance(a.p) <= tol.max(0.05))?;
let j = card.iter().position(|c| c.distance(a.p) <= tol)?;
if used[j] {
return None;
}
@@ -1043,7 +1069,7 @@ fn axis_ellipse(path: &PathData) -> Option<(f64, f64, f64, f64)> {
};
Point::new(card[order[i]].x + ox, card[order[i]].y + oy)
};
if a.h_out.distance(toward(order[(i + 1) % 4])) > tol.max(0.75) || a.h_in.distance(toward(order[(i + 3) % 4])) > tol.max(0.75) {
if a.h_out.distance(toward(order[(i + 1) % 4])) > tol || a.h_in.distance(toward(order[(i + 3) % 4])) > tol {
return None;
}
}
+79
View File
@@ -0,0 +1,79 @@
//! A rectangle, circle, or ellipse exports as that element only when the path is that shape.
//! A bowtie, a repeated corner, and a near-ellipse stay paths. resvg must paint the real shapes
//! the way the canvas does.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use kurbo::Vec2;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node};
use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes};
use vectorcraft_svg::{ExportOptions, export};
use vectorcraft_testkit::raster::{Image, assert_similar, render_artboard};
fn filled(path: PathData) -> Document {
let mut d = Document::new(120.0, 90.0);
let n = Node::path(
d.alloc_id(),
path,
Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::BLACK)))], ..Default::default() },
);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, n).unwrap();
d
}
fn resvg_render(svg: &str) -> Image {
let tree = resvg::usvg::Tree::from_str(svg, &resvg::usvg::Options::default()).expect("parse");
let mut pm = resvg::tiny_skia::Pixmap::new(120, 90).unwrap();
pm.fill(resvg::tiny_skia::Color::WHITE);
resvg::render(&tree, resvg::tiny_skia::Transform::identity(), &mut pm.as_mut());
Image { width: 120, height: 90, rgba: pm.data().to_vec() }
}
fn paints_like_the_canvas(doc: &Document, svg: &str) {
assert_similar(&render_artboard(doc), &resvg_render(svg), 24.0, 0.002);
}
#[test]
fn a_rectangle_circle_and_ellipse_export_as_those_elements() {
let rect = filled(shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 40.0)));
let rect_svg = export(&rect, &ExportOptions::default());
assert!(rect_svg.contains("<rect "), "{rect_svg}");
paints_like_the_canvas(&rect, &rect_svg);
let circle = filled(shapes::ellipse(Rect::new(20.0, 15.0, 70.0, 65.0)));
let circle_svg = export(&circle, &ExportOptions::default());
assert!(circle_svg.contains("<circle "), "{circle_svg}");
paints_like_the_canvas(&circle, &circle_svg);
let ellipse = filled(shapes::ellipse(Rect::new(15.0, 20.0, 100.0, 60.0)));
let ellipse_svg = export(&ellipse, &ExportOptions::default());
assert!(ellipse_svg.contains("<ellipse "), "{ellipse_svg}");
paints_like_the_canvas(&ellipse, &ellipse_svg);
}
#[test]
fn a_bowtie_a_repeated_corner_and_a_near_ellipse_stay_paths() {
let bowtie = filled(PathData::single(SubPath::polyline(
&[Point::new(10.0, 10.0), Point::new(60.0, 40.0), Point::new(60.0, 10.0), Point::new(10.0, 40.0)],
true,
)));
let bowtie_svg = export(&bowtie, &ExportOptions::default());
assert!(bowtie_svg.contains("<path "), "{bowtie_svg}");
assert!(!bowtie_svg.contains("<rect "), "{bowtie_svg}");
let triangle = filled(PathData::single(SubPath::polyline(
&[Point::new(10.0, 10.0), Point::new(60.0, 10.0), Point::new(60.0, 40.0), Point::new(60.0, 40.0)],
true,
)));
let triangle_svg = export(&triangle, &ExportOptions::default());
assert!(triangle_svg.contains("<path "), "{triangle_svg}");
assert!(!triangle_svg.contains("<rect "), "{triangle_svg}");
let mut path = shapes::ellipse(Rect::new(40.0, 40.0, 42.0, 42.0));
path.subpaths[0].anchors[0].h_out += Vec2::new(0.75, 0.0);
let near = filled(path);
let near_svg = export(&near, &ExportOptions::default());
assert!(near_svg.contains("<path "), "{near_svg}");
assert!(!near_svg.contains("<circle ") && !near_svg.contains("<ellipse "), "{near_svg}");
}