From 000d39b0421225e3382b3b6b30b52196990caf24 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 02:33:38 -0700 Subject: [PATCH 1/3] M4: closed vectors take corner smoothing A vector's corner smoothing was stored, imported and exported, but its rounded points were drawn as plain circular arcs, and the Design panel hid the Corner smoothing control for vectors. A vector with a closed region now draws its rounded points with the layer's corner smoothing, on the canvas, in hit testing, in PNG, SVG and PDF exports, and in the fill and stroke geometry of .fig exports. Each point keeps its own radius; a point without one stays sharp. The corner uses the profile of smoothed polygon corners, and smoothing is reduced before the radius when a corner does not fit in half of each segment. FigCraft's own rules for cases the help page does not describe: only a point between two straight segments that both bound a closed region is smoothed; points on open branches and points next to a curved segment keep the plain arc; concave corners are smoothed like convex ones. The Design panel shows Corner smoothing and its iOS (60%) button for vectors with a closed region, and not for open paths. --- crates/doc/src/geometry.rs | 21 ++- crates/doc/src/node.rs | 8 +- crates/doc/src/tests.rs | 122 +++++++++++++ crates/doc/src/vector.rs | 101 ++++++++--- crates/engine/src/canvas/shapebuilder.rs | 4 +- .../engine/src/canvas/vectoredit/regions.rs | 14 +- crates/engine/src/shapes_behaviour_tests.rs | 51 +++++- crates/format/src/fig/export/common.rs | 4 +- crates/format/src/fig/export/shape.rs | 4 +- crates/format/src/fig/export_tests.rs | 43 +++++ crates/geom/src/lib.rs | 168 ++++++++++++------ crates/geom/src/tests.rs | 47 +++++ crates/pdf/src/draw.rs | 4 +- crates/pdf/src/tests.rs | 21 +++ crates/render/src/draw.rs | 14 +- crates/svg/src/lib.rs | 4 +- crates/ui-egui/src/corner_individual_tests.rs | 33 ++++ crates/ui-egui/src/panels/right/paints.rs | 2 +- docs/gaps.md | 4 +- docs/target-app-parity.md | 2 +- 20 files changed, 559 insertions(+), 112 deletions(-) diff --git a/crates/doc/src/geometry.rs b/crates/doc/src/geometry.rs index 0e06d2941..3dbbce6d4 100644 --- a/crates/doc/src/geometry.rs +++ b/crates/doc/src/geometry.rs @@ -28,8 +28,9 @@ pub fn shape_path(n: &Node) -> Option { p } NodeKind::Vector { network } => { - let f = network.fill_path(); - if f.elements().is_empty() { network.stroke_path() } else { f } + let net = drawn_network(network, c.smoothing); + let f = net.fill_path(); + if f.elements().is_empty() { net.stroke_path() } else { f } } NodeKind::Text(_) => figcraft_geom::rounded_rect(w, h, [0.0; 4], 0.0), NodeKind::Page { .. } | NodeKind::Group | NodeKind::BooleanOp { .. } => return None, @@ -39,11 +40,21 @@ pub fn shape_path(n: &Node) -> Option { /// The open/closed path strokes follow (vector networks stroke every segment, filled or not). pub fn stroke_geometry(n: &Node) -> Option { match &n.kind { - NodeKind::Vector { network } => Some(network.stroke_path()), + NodeKind::Vector { network } => Some(drawn_network(network, n.corners.smoothing).stroke_path()), _ => shape_path(n), } } +/// A vector's `network` as the layer draws it: rounded points drawn in with the layer's corner +/// `smoothing` (see [`VectorNetwork::rounded_smoothed`](crate::VectorNetwork::rounded_smoothed)), +/// or the network itself when no point is rounded. +pub fn drawn_network(network: &crate::VectorNetwork, smoothing: f64) -> std::borrow::Cow<'_, crate::VectorNetwork> { + match network.rounded_smoothed(smoothing) { + Some(r) => std::borrow::Cow::Owned(r), + None => std::borrow::Cow::Borrowed(network), + } +} + /// Whether the shape's path is closed (fills apply). pub fn is_closed(n: &Node) -> bool { match &n.kind { @@ -75,8 +86,8 @@ fn hits_node_itself(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, o n.local_rect().inflate(tol_l, tol_l).contains(lp) } NodeKind::Vector { network } if network.regions.iter().any(|r| r.fills.is_some() || r.paint_space.is_some()) => { - let rounded = network.rounded(); - let net = rounded.as_ref().unwrap_or(network); + let drawn = drawn_network(network, n.corners.smoothing); + let net = drawn.as_ref(); if !outline { for (i, region) in net.regions.iter().enumerate().rev() { let paints = region.fills.as_deref().unwrap_or(&n.fills); diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 6ec7e8245..21241cf0f 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -416,9 +416,13 @@ impl NodeKind { self.has_corner_radius() && !matches!(self, NodeKind::Polygon { .. } | NodeKind::Star { .. } | NodeKind::Vector { .. }) } - /// Kinds whose rounded corners are drawn with corner smoothing (a vector's rounded points are drawn without it). + /// Kinds whose rounded corners are drawn with corner smoothing: a vector only when its network + /// has a closed region (an open path's rounded points are drawn without it). pub fn has_corner_smoothing(&self) -> bool { - self.has_corner_radius() && !matches!(self, NodeKind::Vector { .. }) + match self { + NodeKind::Vector { network } => !network.regions.is_empty(), + _ => self.has_corner_radius(), + } } pub fn text(&self) -> Option<&TextData> { diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index a0e3e17b0..2eb912f45 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -665,6 +665,128 @@ fn two_segment_closed_loop_rounded_corners() { assert_eq!(r.regions[0].loops[0].len(), 4, "both arcs are in the loop"); let path = net.fill_path(); assert!(!path.elements().is_empty()); + // Both points sit next to the curved segment, so smoothing keeps their plain arcs. + assert_eq!(net.rounded_smoothed(0.6), net.rounded(), "a corner next to a curve keeps the plain arc"); +} + +/// A closed 100 × 100 square whose corners (top left, top right, bottom right, bottom left) have +/// radii `radii`. +fn rounded_square(radii: [f64; 4]) -> VectorNetwork { + let pts = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)]; + let mut net = VectorNetwork::from_points(&pts, true); + for (v, r) in net.vertices.iter_mut().zip(radii) { + v.radius = r; + } + net +} + +/// The area a closed path encloses, whichever way it runs. +fn area_of(p: &figcraft_geom::BezPath) -> f64 { + use figcraft_geom::Shape; + p.area().abs() +} + +#[test] +fn closed_vectors_smooth_each_rounded_point_with_its_own_radius() { + use figcraft_geom::Shape; + use figcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest}; + // (point radii, smoothing, derivation): a closed square draws the smoothed rectangle's corners, + // each point keeping its own radius and a point without one staying sharp. + let rows: Vec<([f64; 4], f64, &str)> = vec![ + ([20.0; 4], 0.6, "one radius on every point"), + ([30.0, 0.0, 10.0, 0.0], 0.6, "each point keeps its own radius; points without one stay sharp"), + ([12.0; 4], 1.0, "full smoothing"), + ([40.0; 4], 0.6, "a corner too large for its edges loses smoothing first"), + ]; + for (radii, s, why) in rows { + let net = rounded_square(radii); + let smoothed = net.rounded_smoothed(s).unwrap().fill_path(); + // The rectangle's corners take [top left, top right, bottom right, bottom left] radii. + let want = area_of(&figcraft_geom::rounded_rect(100.0, 100.0, radii, s)); + let got = area_of(&smoothed); + assert!((got - want).abs() < 0.1, "{why}: {got} vs the smoothed rectangle's {want}"); + assert!((got - area_of(&net.fill_path())).abs() > 1.0, "{why}: smoothing changes the outline"); + let b = smoothed.bounding_box(); + assert!(b.x0 >= -1e-6 && b.y0 >= -1e-6 && b.x1 <= 100.0 + 1e-6 && b.y1 <= 100.0 + 1e-6, "{why}: {b:?}"); + } + // The sharp points stay on the outline, and the outline has no kinks at the rounded points. + let smoothed = rounded_square([30.0, 0.0, 10.0, 0.0]).rounded_smoothed(0.6).unwrap(); + let path = smoothed.fill_path(); + for p in [Point::new(100.0, 0.0), Point::new(0.0, 100.0)] { + let d = path.segments().map(|seg| seg.nearest(p, 1e-9).distance_sq).fold(f64::INFINITY, f64::min); + assert!(d < 1e-12, "the sharp point {p:?} stays a corner"); + } + let segs: Vec<_> = path.segments().filter(|seg| seg.arclen(1e-6) > 1e-6).collect(); + let mut kinks = 0; + for (i, seg) in segs.iter().enumerate() { + let next = segs[(i + 1) % segs.len()]; + let out = (seg.eval(1.0) - seg.eval(1.0 - 1e-6)).normalize(); + let into = (next.eval(1e-6) - next.eval(0.0)).normalize(); + if out.dot(into) < 0.999 { + kinks += 1; + } + } + assert_eq!(kinks, 2, "only the two sharp points turn without a curve"); + assert_eq!(smoothed.regions[0].loops[0].len(), smoothed.segments.len(), "the loop walks every curve once"); +} + +#[test] +fn corner_smoothing_leaves_open_paths_and_zero_alone() { + let square = rounded_square([20.0; 4]); + assert_eq!(square.rounded_smoothed(0.0), square.rounded(), "no smoothing draws the plain rounded points"); + assert_eq!(square.rounded_smoothed(f64::NAN), square.rounded(), "an unusable smoothing draws no smoothing"); + // An open path (no closed region) keeps its plain arcs. + let pts = [Point::new(200.0, 0.0), Point::new(250.0, 0.0), Point::new(250.0, 50.0)]; + let mut open = VectorNetwork::from_points(&pts, false); + for v in &mut open.vertices { + v.radius = 20.0; + } + assert!(open.regions.is_empty()); + assert_eq!(open.rounded_smoothed(0.6), open.rounded(), "an open path takes no smoothing"); + // In a network with a closed square and a separate open branch, only the square smooths. + let mut mixed = square.clone(); + let base = mixed.vertices.len(); + mixed.vertices.extend(open.vertices.iter().copied()); + mixed.segments.extend(open.segments.iter().map(|s| Segment { a: s.a + base, b: s.b + base, ..*s })); + let runs = mixed.rounded_smoothed(0.6).unwrap().stroke_runs(); + let open_run = runs.iter().find(|r| !r.closed).expect("the open branch"); + assert_eq!(open_run.path, open.rounded().unwrap().stroke_runs()[0].path, "the open branch keeps its plain arc"); + let closed_run = runs.iter().find(|r| r.closed).expect("the square"); + assert_eq!(closed_run.path, square.rounded_smoothed(0.6).unwrap().stroke_runs()[0].path, "the square smooths"); + assert_ne!(closed_run.path, square.rounded().unwrap().stroke_runs()[0].path, "the square's smoothed corners differ from its arcs"); +} + +#[test] +fn smoothed_vector_corners_stay_finite_on_awkward_networks() { + use figcraft_geom::Shape; + // A concave L, a square with a square hole, points with unusable radii and a loop that names a + // missing segment. + let l = [(0.0, 0.0), (100.0, 0.0), (100.0, 40.0), (40.0, 40.0), (40.0, 100.0), (0.0, 100.0)]; + let mut concave = VectorNetwork::from_points(&l.map(|(x, y)| Point::new(x, y)), true); + for v in &mut concave.vertices { + v.radius = 1000.0; + } + let mut holed = rounded_square([10.0; 4]); + let hole = rounded_square([5.0; 4]); + let (base, seg_base) = (holed.vertices.len(), holed.segments.len()); + holed.vertices.extend(hole.vertices.iter().map(|v| Vertex { x: 25.0 + v.x / 2.0, y: 25.0 + v.y / 2.0, ..*v })); + holed.segments.extend(hole.segments.iter().map(|s| Segment { a: s.a + base, b: s.b + base, ..*s })); + holed.regions[0].loops.push((seg_base..seg_base + hole.segments.len()).collect()); + holed.regions[0].winding = WindingRule::EvenOdd; + let mut odd = rounded_square([f64::INFINITY, 10.0, f64::NAN, 10.0]); + odd.regions[0].loops[0].push(99); + for (net, s, why) in [(&concave, 1.0, "concave"), (&holed, 0.6, "holed"), (&odd, 0.6, "odd radii")] { + let drawn = net.rounded_smoothed(s).unwrap(); + let b = drawn.fill_path().bounding_box(); + assert!([b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()), "{why}: {b:?}"); + assert!(b.x0 >= -1e-6 && b.y0 >= -1e-6 && b.x1 <= 100.0 + 1e-6 && b.y1 <= 100.0 + 1e-6, "{why}: {b:?}"); + assert!(!drawn.stroke_path().elements().is_empty(), "{why}"); + } + let concave_path = concave.rounded_smoothed(1.0).unwrap().fill_path(); + assert_ne!(concave_path, concave.fill_path(), "the concave L smooths"); + assert!(concave_path.winding(Point::new(20.0, 60.0)) != 0, "the L stays filled"); + let holed_net = holed.rounded_smoothed(0.6).unwrap(); + assert!(!holed_net.fill_contains(Point::new(50.0, 50.0)) && holed_net.fill_contains(Point::new(12.0, 50.0)), "the hole stays a hole"); } #[test] diff --git a/crates/doc/src/vector.rs b/crates/doc/src/vector.rs index 5ae01a089..f53ad4408 100644 --- a/crates/doc/src/vector.rs +++ b/crates/doc/src/vector.rs @@ -129,9 +129,10 @@ impl Region { } } -/// A rounded point as drawn: point `v` moves to `a` (on segment `s1`), segment `s2` starts again -/// at `b`, and an arc with handles `ta`/`tb` joins them. `cut1`/`cut2`: where each segment is cut, -/// in its own parameter (curved segments keep the rest of their curve). +/// A rounded point as drawn: point `v` moves to `a` (on segment `s1`), and the curves of `chain` +/// lead from there to where segment `s2` starts again (one arc, or a smoothed corner's easing +/// curves and arc). `cut1`/`cut2`: where each segment is cut, in its own parameter (curved +/// segments keep the rest of their curve). struct Corner { v: usize, s1: usize, @@ -139,13 +140,19 @@ struct Corner { s2: usize, s2_at_a: bool, a: Point, - b: Point, - ta: (f64, f64), - tb: (f64, f64), + chain: Vec, cut1: f64, cut2: f64, } +/// One curve of a rounded point: its handles at its start (`ta`) and its end (`tb`), relative to +/// those ends, and the point it ends at. +struct CornerCurve { + ta: (f64, f64), + tb: (f64, f64), + end: Point, +} + /// Accuracy of arc lengths along curved segments (local units). const ARCLEN_ACC: f64 = 1e-6; @@ -382,9 +389,19 @@ impl VectorNetwork { /// the rest of its curve, the arc leaving along its direction there. `None` when no point is /// rounded. pub fn rounded(&self) -> Option { + self.rounded_smoothed(0.0) + } + + /// [`Self::rounded`] with the layer's corner smoothing (0..=1): a rounded point between two + /// straight segments that both belong to a region's loops gets a smoothed corner, drawn with + /// the profile of a smoothed polygon's corners (`figcraft_geom::smoothed_corner`). Other + /// rounded points (on open branches, or next to a curved segment) keep the plain arc, and a + /// point without a radius stays sharp. Without smoothing this is [`Self::rounded`]. + pub fn rounded_smoothed(&self, smoothing: f64) -> Option { if !self.vertices.iter().any(|v| v.radius > 0.0) { return None; } + let smoothing = if smoothing.is_finite() { smoothing.clamp(0.0, 1.0) } else { 0.0 }; let mut incident: Vec> = vec![Vec::new(); self.vertices.len()]; for (i, s) in self.segments.iter().enumerate() { for (v, at_a) in [(s.a, true), (s.b, false)] { @@ -393,7 +410,14 @@ impl VectorNetwork { } } } - let corners: Vec = (0..self.vertices.len()).filter_map(|v| self.corner(v, incident.get(v)?)).collect(); + // The segments that bound a closed region, where corners take smoothing. + let mut on_loop = vec![false; if smoothing > 0.0 { self.segments.len() } else { 0 }]; + for &i in self.regions.iter().flat_map(|r| r.loops.iter().flatten()) { + if let Some(x) = on_loop.get_mut(i) { + *x = true; + } + } + let corners: Vec = (0..self.vertices.len()).filter_map(|v| self.corner(v, incident.get(v)?, smoothing, &on_loop)).collect(); let mut out = self.clone(); for v in &mut out.vertices { v.radius = 0.0; @@ -420,26 +444,33 @@ impl VectorNetwork { s.ta = (q.p1.x - q.p0.x, q.p1.y - q.p0.y); s.tb = (q.p2.x - q.p3.x, q.p2.y - q.p3.y); } - let mut by_vertex: std::collections::BTreeMap = std::collections::BTreeMap::new(); + // Each rounded point's curves in order from `s1`'s side, by point. + let mut by_vertex: std::collections::BTreeMap)> = std::collections::BTreeMap::new(); for c in corners { if let Some(v) = out.vertices.get_mut(c.v) { (v.x, v.y) = (c.a.x, c.a.y); } - out.vertices.push(Vertex::new(c.b.x, c.b.y)); - let nb = out.vertices.len() - 1; + let mut from = c.v; + let mut arcs = Vec::with_capacity(c.chain.len()); + for CornerCurve { ta, tb, end } in c.chain { + out.vertices.push(Vertex::new(end.x, end.y)); + let to = out.vertices.len() - 1; + out.segments.push(Segment { a: from, b: to, ta, tb }); + arcs.push(out.segments.len() - 1); + from = to; + } if let Some(s) = out.segments.get_mut(c.s2) { if c.s2_at_a { - s.a = nb; + s.a = from; } else { - s.b = nb; + s.b = from; } } - out.segments.push(Segment { a: c.v, b: nb, ta: c.ta, tb: c.tb }); - let arc = out.segments.len() - 1; - by_vertex.insert(c.v, arc); + by_vertex.insert(c.v, (c.s1, arcs)); } - // The arc goes between the two segments wherever a loop walks through the point. Each loop - // is rebuilt in one pass, so a polygon with many rounded corners isn't quadratic. + // The curves go between the two segments wherever a loop walks through the point, in the + // order the loop meets them. Each loop is rebuilt in one pass, so a polygon with many + // rounded corners isn't quadratic. for lp in out.regions.iter_mut().flat_map(|r| r.loops.iter_mut()) { let Some(&first_idx) = lp.first() else { continue }; let start_v = match (self.segments.get(first_idx), lp.get(1).and_then(|&i| self.segments.get(i))) { @@ -453,8 +484,12 @@ impl VectorNetwork { rebuilt.push(x); let Some(s) = self.segments.get(x) else { continue }; cur = if s.a == cur { s.b } else { s.a }; - if let Some(&arc) = by_vertex.get(&cur) { - rebuilt.push(arc); + if let Some((s1, arcs)) = by_vertex.get(&cur) { + if x == *s1 { + rebuilt.extend(arcs.iter().copied()); + } else { + rebuilt.extend(arcs.iter().rev().copied()); + } } } *lp = rebuilt; @@ -463,8 +498,9 @@ impl VectorNetwork { } /// How point `v` (its `incident` segments) is rounded, if it is: not where the two segments - /// run on smoothly or fold back. - fn corner(&self, v: usize, incident: &[(usize, bool)]) -> Option { + /// run on smoothly or fold back. With `smoothing`, a point between two straight segments that + /// are both `on_loop` gets a smoothed corner. + fn corner(&self, v: usize, incident: &[(usize, bool)], smoothing: f64, on_loop: &[bool]) -> Option { let r = self.vertices.get(v)?.radius; let [(s1, a1), (s2, a2)] = *incident else { return None }; if !(r > 0.0 && r.is_finite()) || s1 == s2 { @@ -480,6 +516,24 @@ impl VectorNetwork { if !(l1 > 1e-9 && l2 > 1e-9) { return None; } + let own = |at_a: bool, t: f64| if at_a { t } else { 1.0 - t }; + let closed = |s: usize| on_loop.get(s).copied().unwrap_or(false); + if smoothing > 0.0 + && is_line(&c1) + && is_line(&c2) + && closed(s1) + && closed(s2) + && let Some(curves) = figcraft_geom::smoothed_corner(c1.p0, u1, u2, l1.min(l2) / 2.0, r, smoothing) + && let (Some(first), Some(last)) = (curves.first(), curves.last()) + { + let (a, b) = (first.p0, last.p3); + let chain = curves + .iter() + .map(|q| CornerCurve { ta: (q.p1.x - q.p0.x, q.p1.y - q.p0.y), tb: (q.p2.x - q.p3.x, q.p2.y - q.p3.y), end: q.p3 }) + .collect(); + let (cut1, cut2) = ((a - c1.p0).hypot() / l1, (b - c2.p0).hypot() / l2); + return Some(Corner { v, s1, s1_at_a: a1, s2, s2_at_a: a2, a, chain, cut1: own(a1, cut1), cut2: own(a2, cut2) }); + } let t = (r / (angle / 2.0).tan()).min(l1.min(l2) / 2.0); let ((a, d1, k1), (b, d2, k2)) = (trim(&c1, t, l1), trim(&c2, t, l2)); // A cubic arc: handles of 4/3·tan(φ/4)·ρ along each end's direction, φ the turn between @@ -490,7 +544,6 @@ impl VectorNetwork { if !(k.is_finite() && a.x.is_finite() && a.y.is_finite() && b.x.is_finite() && b.y.is_finite()) { return None; } - let own = |at_a: bool, t: f64| if at_a { t } else { 1.0 - t }; Some(Corner { v, s1, @@ -498,9 +551,7 @@ impl VectorNetwork { s2, s2_at_a: a2, a, - b, - ta: (d1.x * k, d1.y * k), - tb: (d2.x * k, d2.y * k), + chain: vec![CornerCurve { ta: (d1.x * k, d1.y * k), tb: (d2.x * k, d2.y * k), end: b }], cut1: own(a1, k1), cut2: own(a2, k2), }) diff --git a/crates/engine/src/canvas/shapebuilder.rs b/crates/engine/src/canvas/shapebuilder.rs index b68f1e71d..4e6981f14 100644 --- a/crates/engine/src/canvas/shapebuilder.rs +++ b/crates/engine/src/canvas/shapebuilder.rs @@ -132,8 +132,8 @@ fn world_area(doc: &Document, part: Part) -> Option<(BezPath, bool)> { } match (&n.kind, part.region) { (NodeKind::Vector { network }, Some(i)) => { - let rounded = network.rounded(); - let net = rounded.as_ref().unwrap_or(network); + let drawn = figcraft_doc::geometry::drawn_network(network, n.corners.smoothing); + let net = drawn.as_ref(); let region = net.regions.get(i)?; let path = net.region_path(i)?; (path, if region.winding == WindingRule::EvenOdd { figcraft_render::FillRule::EvenOdd } else { figcraft_render::FillRule::Winding }) diff --git a/crates/engine/src/canvas/vectoredit/regions.rs b/crates/engine/src/canvas/vectoredit/regions.rs index 91763d3aa..6351ce824 100644 --- a/crates/engine/src/canvas/vectoredit/regions.rs +++ b/crates/engine/src/canvas/vectoredit/regions.rs @@ -56,12 +56,10 @@ fn region_filled(n: &figcraft_doc::Node, net: &VectorNetwork, i: usize) -> bool net.regions.get(i).is_some_and(|r| r.fills.as_deref().unwrap_or(&n.fills).iter().any(|f| f.visible)) } -/// The network as its fill draws it: rounded points drawn in (region indexes are kept). -fn drawn(net: &VectorNetwork) -> std::borrow::Cow<'_, VectorNetwork> { - match net.rounded() { - Some(r) => std::borrow::Cow::Owned(r), - None => std::borrow::Cow::Borrowed(net), - } +/// The network as its fill draws it: rounded points drawn in with the layer's corner `smoothing` +/// (region indexes are kept). +fn drawn(net: &VectorNetwork, smoothing: f64) -> std::borrow::Cow<'_, VectorNetwork> { + figcraft_doc::geometry::drawn_network(net, smoothing) } /// The region of the active layer under page point `p` at `zoom`: none when a point is within @@ -90,7 +88,7 @@ pub fn region_hit(doc: &Document, ve: &VectorEdit, p: Point, zoom: f64) -> Optio if (0..net.segments.len()).filter_map(|i| net.cubic(i)).any(|c| c.nearest(lp, 0.01).distance_sq.sqrt() <= sc) { return None; } - let drawn = drawn(net); + let drawn = drawn(net, node.corners.smoothing); (0..drawn.regions.len()).rev().find(|i| region_filled(node, &drawn, *i) && drawn.region_contains(*i, lp)) } @@ -221,7 +219,7 @@ pub fn region_hatch(doc: &Document, ve: &VectorEdit, regions: &[usize], view: Af let zoom = view.determinant().abs().sqrt(); let Some(spacing) = hatch_spacing(zoom).filter(|_| !regions.is_empty()) else { return Vec::new() }; let Some(net) = network(doc, ve.id) else { return Vec::new() }; - let net = drawn(net); + let net = drawn(net, doc.node(ve.id).map_or(0.0, |n| n.corners.smoothing)); let m = view * doc.world_transform(ve.id); let anchor = m * Point::ZERO; let mut out = Vec::new(); diff --git a/crates/engine/src/shapes_behaviour_tests.rs b/crates/engine/src/shapes_behaviour_tests.rs index e628e1683..ca2d16390 100644 --- a/crates/engine/src/shapes_behaviour_tests.rs +++ b/crates/engine/src/shapes_behaviour_tests.rs @@ -233,7 +233,14 @@ fn corner_smoothing_follows_the_documented_rules() { (NodeKind::Frame, true, "frames"), (NodeKind::Polygon { count: 5 }, true, "polygons"), (NodeKind::Star { count: 5, inner_ratio: 0.4 }, true, "stars"), - (NodeKind::Vector { network: Default::default() }, false, "documented for closed vectors; their points round without it here"), + ( + NodeKind::Vector { + network: figcraft_doc::VectorNetwork::from_points(&[Point::ZERO, Point::new(10.0, 0.0), Point::new(10.0, 10.0)], true), + }, + true, + "vector networks that are closed shapes", + ), + (NodeKind::Vector { network: Default::default() }, false, "an open vector has no closed shape to smooth"), (NodeKind::Line, false, "lines take no radius, so no smoothing"), ]; for (kind, smoothing, why) in doc_rows { @@ -241,6 +248,48 @@ fn corner_smoothing_follows_the_documented_rules() { } } +#[test] +fn closed_vectors_take_corner_smoothing() { + // "Vector networks that are closed shapes" take corner smoothing, which applies to the entire + // shape; a single open stroke does not. + let mut s = Session::new(); + let closed = create(&mut s, "vector.create", json!({"points": [[0, 0], [100, 0], [100, 100], [0, 100]], "closed": true})); + let open = create(&mut s, "vector.create", json!({"points": [[200, 0], [300, 0], [300, 100]], "closed": false})); + ex(&mut s, "node.set", json!({"ids": [closed, open], "props": {"cornerRadius": 20}})); + let outline = |s: &Session, id: NodeId| figcraft_doc::geometry::shape_path(&node(s, id)).unwrap(); + let svg = |s: &Session, id: NodeId| figcraft_svg::export_svg(s.doc().unwrap(), &[id], &figcraft_svg::SvgOptions::default()).unwrap(); + let render = |s: &Session, id: NodeId| figcraft_render::node_outline(s.doc().unwrap(), &node(s, id)).unwrap().0; + let (round, open_round, svg_round, drawn_round) = (outline(&s, closed), outline(&s, open), svg(&s, closed), render(&s, closed)); + ex(&mut s, "node.set", json!({"ids": [closed, open], "props": {"cornerSmoothing": 0.6}})); + let smooth = outline(&s, closed); + // The smoothed corner reaches 1.6 radii along each edge, as a smoothed rectangle's does. + let want = figcraft_geom::rounded_rect(100.0, 100.0, [20.0; 4], 0.6).area().abs(); + assert!((smooth.area().abs() - want).abs() < 0.1, "the closed vector smooths: {} vs {want}", smooth.area().abs()); + assert!((smooth.area().abs() - round.area().abs()).abs() > 1.0, "smoothing changes the closed vector's outline"); + assert_ne!(svg(&s, closed), svg_round, "SVG export draws the smoothed corners"); + assert_ne!(render(&s, closed), drawn_round, "the canvas draws the smoothed corners"); + assert_eq!(outline(&s, open), open_round, "an open vector keeps its plain rounded points"); + let stroke = figcraft_doc::geometry::stroke_geometry(&node(&s, closed)).unwrap(); + assert!((stroke.area().abs() - want).abs() < 0.1, "the stroke follows the smoothed outline"); + // Smoothing needs a radius, and undo restores the plain corners in one step. + s.undo().unwrap(); + assert_eq!(outline(&s, closed), round, "one undo step"); + ex(&mut s, "node.set", json!({"ids": [closed], "props": {"cornerRadius": 0}})); + let sharp = outline(&s, closed); + ex(&mut s, "node.set", json!({"ids": [closed], "props": {"cornerSmoothing": 0.6}})); + assert_eq!(outline(&s, closed), sharp, "smoothing needs a radius"); + // A vector whose region has paints of its own draws the smoothed corners too, on the canvas + // and in SVG. + ex(&mut s, "node.set", json!({"ids": [closed], "props": {"cornerRadius": 20}})); + if let NodeKind::Vector { network } = &mut s.doc_mut().unwrap().get_mut(closed).unwrap().kind { + network.regions[0].fills = Some(vec![figcraft_color::Paint::solid(figcraft_color::Color::BLACK)]); + } + let (region_svg, region_path) = (svg(&s, closed), render(&s, closed)); + assert!((region_path.area().abs() - want).abs() < 0.5, "region paints follow the smoothed outline: {}", region_path.area().abs()); + ex(&mut s, "node.set", json!({"ids": [closed], "props": {"cornerSmoothing": 0}})); + assert_ne!(svg(&s, closed), region_svg, "SVG export draws the region's smoothed corners"); +} + #[test] fn rounded_vector_points_are_drawn() { // A converted 100 × 100 square: a point's radius rounds that corner only (it wasn't drawn). diff --git a/crates/format/src/fig/export/common.rs b/crates/format/src/fig/export/common.rs index 4a97eecb9..ee7293dc9 100644 --- a/crates/format/src/fig/export/common.rs +++ b/crates/format/src/fig/export/common.rs @@ -34,10 +34,10 @@ pub(super) fn outlined(n: &Node) -> Option<(Node, String)> { } let path = figcraft_doc::geometry::stroke_geometry(n)?; let net = match &n.kind { - NodeKind::Vector { network } => Some(network), + NodeKind::Vector { network } => Some(figcraft_doc::geometry::drawn_network(network, n.corners.smoothing)), _ => None, }; - let area = figcraft_pathops::stroke_outline_of(&path, sp, figcraft_doc::geometry::is_closed(n), net); + let area = figcraft_pathops::stroke_outline_of(&path, sp, figcraft_doc::geometry::is_closed(n), net.as_deref()); if area.elements().is_empty() || area.elements().len() > MAX_NETWORK / 4 { return None; } diff --git a/crates/format/src/fig/export/shape.rs b/crates/format/src/fig/export/shape.rs index 03c82cfb1..6627935ca 100644 --- a/crates/format/src/fig/export/shape.rs +++ b/crates/format/src/fig/export/shape.rs @@ -257,7 +257,7 @@ impl<'d> Exporter<'d> { if net.regions.iter().any(|r| r.winding != winding) { self.warn("vectors whose filled areas use different winding rules use the first one's in their outline"); } - self.geometry("fillGeometry", &net.fill_path(), winding, f); + self.geometry("fillGeometry", &figcraft_doc::geometry::drawn_network(net, n.corners.smoothing).fill_path(), winding, f); } } @@ -309,7 +309,7 @@ impl<'d> Exporter<'d> { self.geometry("strokeGeometry", &ring, WindingRule::EvenOdd, f); } else if sp.align == StrokeAlign::Center { let path = match &n.kind { - NodeKind::Vector { network } => Some(network.stroke_path()), + NodeKind::Vector { .. } => figcraft_doc::geometry::stroke_geometry(n), NodeKind::Text(_) => None, _ => figcraft_doc::geometry::shape_path(n), }; diff --git a/crates/format/src/fig/export_tests.rs b/crates/format/src/fig/export_tests.rs index 5b4bcb991..45f6866f3 100644 --- a/crates/format/src/fig/export_tests.rs +++ b/crates/format/src/fig/export_tests.rs @@ -912,6 +912,49 @@ fn written_files_decode_and_list_parents_first() { } } +#[test] +fn closed_vector_geometry_is_written_with_its_corner_smoothing() { + // A closed vector with rounded points: its written fill and stroke outlines take the layer's + // corner smoothing, and the smoothing and each point's radius come back on import. + let mut doc = Document::new("smoothing"); + let page = doc.first_page().unwrap(); + let mut network = VectorNetwork::from_points(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| Point::new(x, y)), true); + for (v, r) in network.vertices.iter_mut().zip([20.0, 0.0, 10.0, 0.0]) { + v.radius = r; + } + let id = doc.create(page, NodeKind::Vector { network }, "V", 0.0, 0.0, 100.0, 100.0).unwrap(); + doc.node_mut(id).unwrap().strokes = vec![Paint::solid(Color::BLACK)]; + // The vector's written fill and stroke outlines. + let outlines = |doc: &Document| -> Vec> { + let (bytes, _) = export(doc, None).unwrap(); + let archive = Archive::open(&bytes).unwrap(); + let (schema, message) = decode_canvas(&archive.canvas).unwrap(); + let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap(); + let blobs = msg.get("blobs").unwrap().list(); + let changes = msg.get("nodeChanges").unwrap().list(); + let nc = changes.iter().find(|nc| nc.get("type").and_then(Kv::str) == Some("VECTOR")).unwrap(); + ["fillGeometry", "strokeGeometry"] + .iter() + .map(|key| { + let paths = nc.get(key).map(Kv::list).unwrap_or_default(); + let blob = paths.first().unwrap_or_else(|| panic!("{key} is written")).get("commandsBlob").unwrap().f64().unwrap() as usize; + blobs[blob].get("bytes").and_then(Kv::bytes).unwrap().to_vec() + }) + .collect() + }; + let plain = outlines(&doc); + doc.node_mut(id).unwrap().corners.smoothing = 0.6; + let smoothed = outlines(&doc); + assert_ne!(smoothed[0], plain[0], "the fill outline takes the smoothing"); + assert_ne!(smoothed[1], plain[1], "the stroke outline takes the smoothing"); + let (back, _) = round_trip(&doc, "smoothed vector"); + let v = back.nodes().find(|n| matches!(n.kind, NodeKind::Vector { .. })).unwrap(); + assert!((v.corners.smoothing - 0.6).abs() < 1e-6, "smoothing comes back: {}", v.corners.smoothing); + let NodeKind::Vector { network } = &v.kind else { panic!("vector") }; + let radii: Vec = network.vertices.iter().map(|x| x.radius).collect(); + assert_eq!(radii, vec![20.0, 0.0, 10.0, 0.0], "each point keeps its own radius"); +} + #[test] fn the_written_schema_parses_and_round_trips() { let schema = Schema::parse(export::SCHEMA).unwrap(); diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 012fca429..d63d84397 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -249,67 +249,133 @@ pub fn smoothed_polygon(points: &[Point], radius: f64, smoothing: f64) -> BezPat }; let (v1, v2) = (*prev - *cur, *next - *cur); let (l1, l2) = (v1.hypot(), v2.hypot()); - let angle = if l1 < 1e-9 || l2 < 1e-9 { 0.0 } else { (v1 / l1).dot(v2 / l2).clamp(-1.0, 1.0).acos() }; - if angle < 1e-6 || (PI - angle) < 1e-6 { + let corner = if l1 < 1e-9 || l2 < 1e-9 { None } else { smooth_corner(*cur, v1 / l1, v2 / l2, l1.min(l2) / 2.0, radius, s) }; + let Some(k) = corner else { line_or_move(&mut path, *cur); continue; + }; + line_or_move(&mut path, k.start); + match k.ease_in { + Some((h1, h2)) => path.curve_to(h1, h2, k.p3), + None => path.line_to(k.p3), } - let (u1, u2) = (v1 / l1, v2 / l2); - // The plain corner's length along each edge, then the fit: smoothing first, then the radius. - let max_p = l1.min(l2) / 2.0; - let mut r = radius; - let mut t = r / (angle / 2.0).tan(); - let mut sm = s; - if (1.0 + sm) * t > max_p { - sm = (max_p / t - 1.0).clamp(0.0, sm); + if k.sweep.abs() > 1e-9 { + kurbo::Arc::new(k.center, (k.r, k.r), k.a0, k.sweep, 0.0).to_cubic_beziers(0.01, |p1, p2, q| path.curve_to(p1, p2, q)); } - if t > max_p { - r *= max_p / t; - t = max_p; - } - let p = ((1.0 + sm) * t).min(max_p); - // Each easing curve covers `beta` of the turn and ends on the arc at `back` along the edge - // and `side` across it; its last handle points along the arc there. - let beta = (PI - angle) * sm / 2.0; - let back = t - r * beta.sin(); - let side = r * (1.0 - beta.cos()); - let c = r * (beta / 2.0).tan() * beta.cos(); - let b = ((p - back - c) / 3.0).max(0.0); - let a = 2.0 * b; - let bisector = (u1 + u2).normalize(); - let center = *cur + bisector * (r / (angle / 2.0).sin()); - // A point `along` an edge from the vertex and `across` it toward the arc's center. - let at = |u: Vec2, along: f64, across: f64| *cur + u * along + (bisector - u * bisector.dot(u)).normalize() * across; - line_or_move(&mut path, at(u1, p, 0.0)); - let p3 = at(u1, back, side); - let p4 = at(u2, back, side); - if a + b + c > 1e-9 { - path.curve_to(at(u1, p - a, 0.0), at(u1, p - a - b, 0.0), p3); - } else { - path.line_to(p3); - } - let a0 = (p3 - center).atan2(); - let mut sweep = (p4 - center).atan2() - a0; - while sweep <= -PI { - sweep += TAU; - } - while sweep > PI { - sweep -= TAU; - } - if sweep.abs() > 1e-9 { - kurbo::Arc::new(center, (r, r), a0, sweep, 0.0).to_cubic_beziers(0.01, |p1, p2, q| path.curve_to(p1, p2, q)); - } - let end = at(u2, p, 0.0); - if a + b + c > 1e-9 { - path.curve_to(at(u2, p - a - b, 0.0), at(u2, p - a, 0.0), end); - } else { - path.line_to(end); + match k.ease_out { + Some((h1, h2)) => path.curve_to(h1, h2, k.end), + None => path.line_to(k.end), } } path.close_path(); path } +/// One smoothed corner as [`smoothed_polygon`] draws it: it starts at `start` on the first edge, +/// eases into a circular arc at `p3` (through handles `ease_in`, or straight when `None`), follows +/// the arc of radius `r` about `center` from angle `a0` through `sweep` to `p4`, and eases out to +/// `end` on the second edge. +struct SmoothCorner { + start: Point, + ease_in: Option<(Point, Point)>, + p3: Point, + center: Point, + r: f64, + a0: f64, + sweep: f64, + p4: Point, + ease_out: Option<(Point, Point)>, + end: Point, +} + +/// The smoothed corner at `cur` between edges that leave it along unit directions `u1` and `u2`, +/// with `max_p` of room along each: `None` where the edges run straight on or fold back. +fn smooth_corner(cur: Point, u1: Vec2, u2: Vec2, max_p: f64, radius: f64, s: f64) -> Option { + let angle = u1.dot(u2).clamp(-1.0, 1.0).acos(); + if angle < 1e-6 || (PI - angle) < 1e-6 { + return None; + } + // The plain corner's length along each edge, then the fit: smoothing first, then the radius. + let mut r = radius; + let mut t = r / (angle / 2.0).tan(); + let mut sm = s; + if (1.0 + sm) * t > max_p { + sm = (max_p / t - 1.0).clamp(0.0, sm); + } + if t > max_p { + r *= max_p / t; + t = max_p; + } + let p = ((1.0 + sm) * t).min(max_p); + // Each easing curve covers `beta` of the turn and ends on the arc at `back` along the edge + // and `side` across it; its last handle points along the arc there. + let beta = (PI - angle) * sm / 2.0; + let back = t - r * beta.sin(); + let side = r * (1.0 - beta.cos()); + let c = r * (beta / 2.0).tan() * beta.cos(); + let b = ((p - back - c) / 3.0).max(0.0); + let a = 2.0 * b; + let bisector = (u1 + u2).normalize(); + let center = cur + bisector * (r / (angle / 2.0).sin()); + // A point `along` an edge from the vertex and `across` it toward the arc's center. + let at = |u: Vec2, along: f64, across: f64| cur + u * along + (bisector - u * bisector.dot(u)).normalize() * across; + let p3 = at(u1, back, side); + let p4 = at(u2, back, side); + let eased = a + b + c > 1e-9; + let a0 = (p3 - center).atan2(); + let mut sweep = (p4 - center).atan2() - a0; + while sweep <= -PI { + sweep += TAU; + } + while sweep > PI { + sweep -= TAU; + } + Some(SmoothCorner { + start: at(u1, p, 0.0), + ease_in: eased.then(|| (at(u1, p - a, 0.0), at(u1, p - a - b, 0.0))), + p3, + center, + r, + a0, + sweep, + p4, + ease_out: eased.then(|| (at(u2, p - a - b, 0.0), at(u2, p - a, 0.0))), + end: at(u2, p, 0.0), + }) +} + +/// The curves of one corner rounded by `radius` with corner smoothing (0..=1) at `corner`, between +/// two straight edges that leave it along unit directions `u1` and `u2` with `max_p` of room along +/// each. The curves follow the profile of [`smoothed_polygon`], with the circular part as one +/// cubic, and run from the point on the `u1` edge to the point on the `u2` edge; a straight piece +/// has its handles on its ends. As in the polygon, smoothing is reduced first when the corner does +/// not fit, then the radius. `None` for a corner that is not rounded, or where the edges run +/// straight on or fold back. +pub fn smoothed_corner(corner: Point, u1: Vec2, u2: Vec2, max_p: f64, radius: f64, smoothing: f64) -> Option> { + let (s, radius, max_p) = (finite(smoothing).clamp(0.0, 1.0), finite(radius).max(0.0), finite(max_p).max(0.0)); + let usable = |u: Vec2| u.x.is_finite() && u.y.is_finite() && u.hypot() > 1e-9; + if radius <= 0.0 || max_p <= 0.0 || !usable(u1) || !usable(u2) || !(corner.x.is_finite() && corner.y.is_finite()) { + return None; + } + let k = smooth_corner(corner, u1 / u1.hypot(), u2 / u2.hypot(), max_p, radius, s)?; + let piece = |p0: Point, handles: Option<(Point, Point)>, p3: Point| { + let (h1, h2) = handles.unwrap_or((p0, p3)); + kurbo::CubicBez::new(p0, h1, h2, p3) + }; + let mut out = vec![piece(k.start, k.ease_in, k.p3)]; + if k.sweep.abs() > 1e-9 { + // The arc as one cubic: handles of 4/3·tan(θ/4)·r along the circle's tangents at its ends. + let h = 4.0 / 3.0 * (k.sweep.abs() / 4.0).tan() * k.r * k.sweep.signum(); + let tangent = |a: f64| Vec2::new(-a.sin(), a.cos()); + out.push(kurbo::CubicBez::new(k.p3, k.p3 + tangent(k.a0) * h, k.p4 - tangent(k.a0 + k.sweep) * h, k.p4)); + } + out.push(piece(k.p4, k.ease_out, k.end)); + out.retain(|q| (q.p3 - q.p0).hypot() > 1e-9 || (q.p1 - q.p0).hypot() > 1e-9 || (q.p2 - q.p3).hypot() > 1e-9); + let finite_point = |p: &Point| p.x.is_finite() && p.y.is_finite(); + let ok = out.iter().all(|q| [q.p0, q.p1, q.p2, q.p3].iter().all(finite_point)); + (ok && !out.is_empty()).then_some(out) +} + /// Starts `path` at `p`, or continues it there with a straight segment. fn line_or_move(path: &mut BezPath, p: Point) { if path.elements().is_empty() { diff --git a/crates/geom/src/tests.rs b/crates/geom/src/tests.rs index 37e6ccab7..1a2391a35 100644 --- a/crates/geom/src/tests.rs +++ b/crates/geom/src/tests.rs @@ -52,6 +52,53 @@ fn degenerate_inputs_dont_panic() { let _ = smoothed_polygon(&polygon_points(10.0, 10.0, 5), f64::INFINITY, f64::NAN); let _ = smoothed_polygon(&polygon_points(10.0, 10.0, 5), 3.0, f64::INFINITY); let _ = ellipse(f64::NAN, 10.0, f64::NAN, 100.0, 2.0); + // (corner, first edge, second edge, room, radius, smoothing): none of these is a corner to round. + let x = Vec2::new(1.0, 0.0); + let rows = [ + (Point::ZERO, x, Vec2::new(0.0, 1.0), 10.0, 0.0, 0.6), + (Point::ZERO, x, Vec2::new(0.0, 1.0), 0.0, 5.0, 0.6), + (Point::ZERO, x, x, 10.0, 5.0, 0.6), + (Point::ZERO, x, -x, 10.0, 5.0, 0.6), + (Point::ZERO, Vec2::ZERO, x, 10.0, 5.0, 0.6), + (Point::ZERO, Vec2::new(f64::NAN, 0.0), x, 10.0, 5.0, 0.6), + (Point::new(f64::INFINITY, 0.0), x, Vec2::new(0.0, 1.0), 10.0, 5.0, 0.6), + ]; + for (corner, u1, u2, room, r, s) in rows { + assert!(smoothed_corner(corner, u1, u2, room, r, s).is_none(), "{corner:?} {u1:?} {u2:?} {room} {r} {s}"); + } +} + +#[test] +fn smoothed_corner_draws_the_polygon_corner() { + use kurbo::ParamCurve; + // The corner of a square drawn by itself follows the smoothed polygon's corner and joins its + // edges and its own pieces without a kink. + for s in [0.0, 0.6, 1.0] { + let curves = smoothed_corner(Point::ZERO, Vec2::new(0.0, 1.0), Vec2::new(1.0, 0.0), 50.0, 20.0, s).unwrap(); + let mut path = BezPath::new(); + path.move_to(curves[0].p0); + for q in &curves { + path.curve_to(q.p1, q.p2, q.p3); + } + path.line_to((100.0, 0.0)); + path.line_to((100.0, 100.0)); + path.line_to((0.0, 100.0)); + path.close_path(); + let want = area(&rounded_rect(100.0, 100.0, [20.0, 0.0, 0.0, 0.0], s)); + assert!((area(&path) - want).abs() < 0.05, "s={s}: {} vs {want}", area(&path)); + assert!((curves[0].p0 - Point::new(0.0, 20.0 * (1.0 + s))).hypot() < 1e-9, "s={s}: it starts 1 + smoothing radii along the edge"); + let last = curves[curves.len() - 1]; + assert!((last.p3 - Point::new(20.0 * (1.0 + s), 0.0)).hypot() < 1e-9, "s={s}: and ends as far along the other"); + let dir = |c: &kurbo::CubicBez, t: f64| { + let d = if t < 0.5 { c.eval(1e-6) - c.eval(0.0) } else { c.eval(1.0) - c.eval(1.0 - 1e-6) }; + d.normalize() + }; + assert!(dir(&curves[0], 0.0).dot(Vec2::new(0.0, -1.0)) > 0.999, "s={s}: it leaves along the first edge"); + assert!(dir(&last, 1.0).dot(Vec2::new(1.0, 0.0)) > 0.999, "s={s}: it arrives along the second edge"); + for pair in curves.windows(2) { + assert!(dir(&pair[0], 1.0).dot(dir(&pair[1], 0.0)) > 0.999, "s={s}: its pieces join smoothly"); + } + } } #[test] diff --git a/crates/pdf/src/draw.rs b/crates/pdf/src/draw.rs index eb1b8aaf1..2ae6e366c 100644 --- a/crates/pdf/src/draw.rs +++ b/crates/pdf/src/draw.rs @@ -338,8 +338,8 @@ impl<'a> Exporter<'a> { if let NodeKind::Vector { network } = &n.kind && network.regions.iter().any(|r| r.fills.is_some() || r.paint_space.is_some()) { - let rounded = network.rounded(); - let net = rounded.as_ref().unwrap_or(network); + let drawn = figcraft_doc::geometry::drawn_network(network, n.corners.smoothing); + let net = drawn.as_ref(); for (i, region) in net.regions.iter().enumerate() { let paints = region.fills.as_deref().unwrap_or(&n.fills); if let Some(mut region_path) = net.region_path(i) { diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index cdd85d6bd..110bfa736 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -82,6 +82,27 @@ fn pdf_vector_region_paints_emit_independent_colors() { assert!(content.contains("1 0 0 rg") && content.contains("0 0 1 rg"), "{content}"); } +#[test] +fn pdf_vector_region_paints_draw_smoothed_corners() { + // A closed vector with rounded points and paints on its region: corner smoothing changes the + // exported outline, as on the canvas. + let corners = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| figcraft_geom::Point::new(x, y)); + let mut network = VectorNetwork::from_points(&corners, true); + for v in &mut network.vertices { + v.radius = 20.0; + } + network.regions[0].fills = Some(vec![Paint::solid(Color::from_hex("FF0000").unwrap())]); + let mut d = Document::new("smoothing"); + let p = d.first_page().unwrap(); + let id = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 100.0, 100.0).unwrap(); + let content = |d: &Document| inflated(&export_pdf(d, &[id], &PdfOptions::default()).unwrap()); + let plain = content(&d); + d.get_mut(id).unwrap().corners.smoothing = 0.6; + let smoothed = content(&d); + assert!(smoothed.contains("1 0 0 rg"), "{smoothed}"); + assert_ne!(smoothed, plain, "the region's outline takes the smoothing"); +} + /// A page with two frames: shapes, gradients, an image, strokes, a mask, a boolean, effects, text. pub(crate) fn sample_doc() -> (Document, Vec) { let mut d = Document::new("sample"); diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index f48899aea..74512ef4f 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -274,7 +274,9 @@ fn cached_stroke_outline(n: &Node, path: &BezPath, closed: bool) -> Arc if let Some(p) = locked(stroke_cache()).get(key) { return p; } - let out = Arc::new(figcraft_pathops::stroke_outline_of(path, props, closed, net)); + // Points with styles of their own are stroked on the network as drawn (smoothed corners in). + let drawn = net.map(|network| figcraft_doc::geometry::drawn_network(network, n.corners.smoothing)); + let out = Arc::new(figcraft_pathops::stroke_outline_of(path, props, closed, drawn.as_deref())); locked(stroke_cache()).insert(key, out.clone()); out } @@ -334,9 +336,9 @@ fn node_outline_at(doc: &Document, n: &Node, depth: usize) -> Option<(BezPath, F Some((p, FillRule::Winding)) } NodeKind::Vector { network } => { + let drawn = figcraft_doc::geometry::drawn_network(network, n.corners.smoothing); + let net = drawn.as_ref(); if network.regions.iter().any(|r| r.fills.is_some() || r.paint_space.is_some()) { - let rounded = network.rounded(); - let net = rounded.as_ref().unwrap_or(network); let mut areas = BezPath::new(); for (i, region) in net.regions.iter().enumerate() { let paints = region.fills.as_deref().unwrap_or(&n.fills); @@ -357,7 +359,7 @@ fn node_outline_at(doc: &Document, n: &Node, depth: usize) -> Option<(BezPath, F } let rule = if network.regions.iter().any(|r| r.winding == figcraft_doc::WindingRule::EvenOdd) { FillRule::EvenOdd } else { FillRule::Winding }; - Some((network.fill_path(), rule)) + Some((net.fill_path(), rule)) } _ => figcraft_doc::geometry::shape_path(n).map(|p| (p, FillRule::Winding)), } @@ -849,8 +851,8 @@ fn region_painted(n: &Node) -> Option<&figcraft_doc::VectorNetwork> { /// Each region of a vector with region paints, filled with its own paints (or the layer's) in its /// own paint frame. fn fill_vector_regions(ctx: &Ctx, pix: &mut Pixmap, n: &Node, network: &figcraft_doc::VectorNetwork, xf: Affine) { - let rounded = network.rounded(); - let net = rounded.as_ref().unwrap_or(network); + let drawn = figcraft_doc::geometry::drawn_network(network, n.corners.smoothing); + let net = drawn.as_ref(); for (i, region) in net.regions.iter().enumerate() { let paints = region.fills.as_deref().unwrap_or(&n.fills); if let Some(mut path) = net.region_path(i) { diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index de98795d3..b5047cec4 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -537,8 +537,8 @@ impl W<'_> { if let NodeKind::Vector { network } = &n.kind && network.regions.iter().any(|r| r.fills.is_some() || r.paint_space.is_some()) { - let rounded = network.rounded(); - let net = rounded.as_ref().unwrap_or(network); + let drawn = figcraft_doc::geometry::drawn_network(network, n.corners.smoothing); + let net = drawn.as_ref(); for (i, region) in net.regions.iter().enumerate() { let paints = region.fills.as_deref().unwrap_or(&n.fills); let fr = if region.winding == figcraft_doc::WindingRule::EvenOdd { " fill-rule=\"evenodd\"" } else { "" }; diff --git a/crates/ui-egui/src/corner_individual_tests.rs b/crates/ui-egui/src/corner_individual_tests.rs index e76f2f57e..281ab6f2a 100644 --- a/crates/ui-egui/src/corner_individual_tests.rs +++ b/crates/ui-egui/src/corner_individual_tests.rs @@ -184,3 +184,36 @@ fn polygons_and_stars_take_corner_smoothing() { assert_eq!(u.app.session.undo_depth().0, history + 1, "{cmd}: one undo step"); } } + +/// A closed vector shows the same Corner smoothing control, and its iOS button sets 60% in one +/// undo step; an open vector, which has no closed shape to smooth, shows no smoothing control. +#[test] +fn closed_vectors_take_corner_smoothing() { + let rows = [(true, json!([[0, 0], [120, 0], [120, 120], [0, 120]])), (false, json!([[0, 0], [120, 0], [120, 120]]))]; + for (closed, points) in rows { + let mut s = Session::new(); + let id = NodeId(s.execute("vector.create", &json!({"points": points, "closed": closed})).unwrap()["id"].as_u64().unwrap()); + s.execute("node.set", &json!({"ids": [id], "props": {"cornerRadius": 8}})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let mut u = Ui::new(s); + u.ctx.enable_accesskit(); + u.frame(vec![]); + let out = u.frame_output(vec![]); + let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes; + let toggle = nodes.iter().any(|(_, n)| n.role() == Role::Button && n.label() == Some("Corner smoothing")); + assert_eq!(toggle, closed, "closed {closed}: the Corner smoothing button shows only for a closed vector"); + if !closed { + continue; + } + let t = named_button(&mut u, "Corner smoothing"); + click(&mut u, t); + assert!((0..4).all(|k| u.ctx.read_response(Id::unique(("corner", k)).with("field")).is_none()), "no field per corner"); + assert!(u.ctx.read_response(Id::unique("smoothing").with("field")).is_some(), "the smoothing field shows"); + let history = u.app.session.undo_depth().0; + let ios = named_button(&mut u, "iOS"); + click(&mut u, ios); + let n = u.app.session.doc().unwrap().node(id).unwrap().clone(); + assert!((n.corners.smoothing - 0.6).abs() < 1e-9, "iOS sets 60%: {}", n.corners.smoothing); + assert_eq!(u.app.session.undo_depth().0, history + 1, "one undo step"); + } +} diff --git a/crates/ui-egui/src/panels/right/paints.rs b/crates/ui-egui/src/panels/right/paints.rs index 58423d252..10301a85e 100644 --- a/crates/ui-egui/src/panels/right/paints.rs +++ b/crates/ui-egui/src/panels/right/paints.rs @@ -53,7 +53,7 @@ pub(super) fn appearance(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[N let radius_ok = crate::selection_cache::every(doc, sel, |n| n.kind.has_corner_radius()); // Only rectangles and frames round each corner on its own. let indep_ok = radius_ok && crate::selection_cache::every(doc, sel, |n| n.kind.has_independent_corners()); - // For polygons and stars the same panel holds only the Corner smoothing row. + // For polygons, stars and closed vectors the same panel holds only the Corner smoothing row. let smooth_ok = radius_ok && crate::selection_cache::every(doc, sel, |n| n.kind.has_corner_smoothing()); let r = common(doc, sel, |n| n.corners.uniform().map(|r| (r * 100.0).round() / 100.0)); widgets::sublabels(ui, tr("Opacity"), radius_ok.then_some(tr("Corner radius"))); diff --git a/docs/gaps.md b/docs/gaps.md index 5437c6766..b3685c912 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -384,8 +384,8 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe - **Landed (2026-10-12):** several Bezier handles selected with Shift-click and dragged together, sharp points beside curved segments rounded, a stroke cap and join per point (canvas, PNG, SVG, PDF, outline stroke), the Pen outside edit mode connecting to its own points and continuing a - selected open path. Left: corner smoothing on vectors, corner radius and smoothing on boolean - groups that contain rectangles, per-point caps and joins on dashed, variable-width and brush + selected open path. Left: corner radius and smoothing on boolean groups that contain + rectangles, per-point caps and joins on dashed, variable-width and brush strokes. - **Landed (2026-10-11):** boolean groups are clicked where their result is (a click in a subtracted hole reaches what's behind; with the group or an operand selected its operands are diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 489c0e7da..2775c41d2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -99,7 +99,7 @@ Breadth: does it exist. Ready: depth, correctness and fidelity for real projects | 1 | Canvas & navigation | 6 | 98% | 74% | Display P3 on screen, QA at extreme zooms (behaviour suite for navigation, rulers, guides, layout grids and outline mode landed: guide selection, Auto grid counts, outline-mode clicks; outline mode's Include hidden layers and Include object bounds landed) | 1–4 | | 2 | Selection & transform | 8 | 97% | 72% | Handles, measuring and snapping checked tool by tool against Figma and real files (snap distance, handle reach, cursors); children turned off a right angle scale without skew, approximately (behaviour suite from the documentation, rotated groups and mixed selections, equal spacing snapping, Cmd/Ctrl to ignore constraints and marquees inside frames landed) | 3–5 | | 3 | Layers panel | 5 | 99% | 85% | QA with long real files (behaviour suite from the documentation, Rename layers dialog, sweeping eyes and padlocks, page dragging and dividers, several layers dropped together, keyboard box selection, F2 rename, Shift+F10 context menu and 10k-layer timings landed) | 1–2 | -| 4 | Shapes & vector | 8 | 99% | 73% | Corner smoothing on vectors, corner radius and smoothing on boolean groups that contain rectangles; per-point caps and joins on dashed, variable-width and brush strokes; vector QA with real files (behaviour suites from the documentation, corner radius and star ratio handles, corner smoothing on polygons and stars, rounded vector points drawn, also beside curved segments, a cap and join per point, several handles dragged together, cut and paint bucket drags, delete and heal along the curve, a boolean group's look by operation and the miter angle landed) | 1–3 | +| 4 | Shapes & vector | 8 | 99% | 73% | Corner radius and smoothing on boolean groups that contain rectangles; per-point caps and joins on dashed, variable-width and brush strokes; vector QA with real files (behaviour suites from the documentation, corner radius and star ratio handles, corner smoothing on polygons, stars and closed vectors, rounded vector points drawn, also beside curved segments, a cap and join per point, several handles dragged together, cut and paint bucket drags, delete and heal along the curve, a boolean group's look by operation and the miter angle landed) | 1–3 | | 5 | Paint | 7 | 90% | 71% | Video fills, wide-gamut canvas, HEIC images; plus darker in PDF (behaviour suite from the documentation, pass-through and isolating groups, clipping frames that don't isolate, plus darker, animated GIF fills, TIFF images and embedded image colour profiles landed) | 2–5 | | 6 | Strokes | 3 | 95% | 75% | Stroke QA with real files (colour styles on strokes, stroke weight and per-side weight variables, brush strokes landed, see 20) | 1–2 | | 7 | Effects | 4 | 100% | 75% | Glass and progressive blur tuned side by side (behaviour suite from the documentation, inner shadows and background blur on groups, shadows hidden behind translucent layers on the canvas and in every export landed) | 2–5 | From f56e30e7e3bf992d747881b7d0b0d21ed8e16efd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 02:42:39 -0700 Subject: [PATCH 2/3] Hit testing: clicks on a closed vector follow its smoothed corners A vector without region paints tested a click against its plain rounded fill while the canvas drew the smoothed corners, so a click between the two could select a layer where no fill is drawn or miss fill that is drawn. The inside test now uses the network as drawn, keeping the even-odd rule. --- crates/doc/src/geometry.rs | 5 +++-- crates/doc/src/tests.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/geometry.rs b/crates/doc/src/geometry.rs index 3dbbce6d4..189e06192 100644 --- a/crates/doc/src/geometry.rs +++ b/crates/doc/src/geometry.rs @@ -107,10 +107,11 @@ fn hits_node_itself(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, o } /// Whether the fill of `n`, drawn as `path`, covers `lp` (vectors follow the rule of -/// [`VectorNetwork::fill_contains`](crate::VectorNetwork::fill_contains): even-odd when any region asks for it). +/// [`VectorNetwork::fill_contains`](crate::VectorNetwork::fill_contains) on the network as drawn: even-odd when any +/// region asks for it). fn fills_point(n: &Node, path: &BezPath, lp: Point) -> bool { match &n.kind { - NodeKind::Vector { network } => network.fill_contains(lp), + NodeKind::Vector { network } => drawn_network(network, n.corners.smoothing).fill_contains(lp), _ => path.winding(lp) != 0, } } diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 2eb912f45..7dbc8cc94 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -789,6 +789,33 @@ fn smoothed_vector_corners_stay_finite_on_awkward_networks() { assert!(!holed_net.fill_contains(Point::new(50.0, 50.0)) && holed_net.fill_contains(Point::new(12.0, 50.0)), "the hole stays a hole"); } +#[test] +fn clicks_on_a_smoothed_vector_corner_follow_the_drawn_fill() { + // A closed square with rounded points and smoothing: a click between the plain arc and the + // smoothed corner selects the layer only where the smoothed fill is drawn. + let pts = [Point::new(0.0, 0.0), Point::new(1000.0, 0.0), Point::new(1000.0, 1000.0), Point::new(0.0, 1000.0)]; + let mut net = VectorNetwork::from_points(&pts, true); + for v in &mut net.vertices { + v.radius = 200.0; + } + let smoothed = net.rounded_smoothed(1.0).unwrap(); + let mut d = Document::new("x"); + let p = page(&d); + let v = d.create(p, NodeKind::Vector { network: net.clone() }, "V", 0.0, 0.0, 1000.0, 1000.0).unwrap(); + let n = d.node_mut(v).unwrap(); + n.corners.smoothing = 1.0; + n.strokes.clear(); + // Walk the row 20 units below the top edge inward to where each outline starts covering it. + let first_inside = |inside: &dyn Fn(Point) -> bool| (0..5_000).map(|i| f64::from(i) * 0.1).find(|&x| inside(Point::new(x, 20.0))); + let plain = first_inside(&|pt| net.fill_contains(pt)).unwrap(); + let drawn = first_inside(&|pt| smoothed.fill_contains(pt)).unwrap(); + assert!((plain - drawn).abs() > 5.0, "smoothing moves the corner: plain {plain}, smoothed {drawn}"); + let pt = Point::new((plain + drawn) / 2.0, 20.0); + assert_ne!(net.fill_contains(pt), smoothed.fill_contains(pt)); + assert_eq!(d.hit_test(p, pt, 0.0, None).is_some(), smoothed.fill_contains(pt), "the click follows the smoothed corner at {pt:?}"); + assert_eq!(d.hit_test(p, Point::new(500.0, 500.0), 0.0, None), Some(v)); +} + #[test] fn stored_variable_ids_resolve_only_their_exact_collection() { let mut vars = crate::proto_expr_tests::vars(); From 099cc0375455a63803b49739183583163ef36bf9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 03:21:43 -0700 Subject: [PATCH 3/3] Vector: simplify, offset and Penpot export keep a closed vector's smoothed corners vector.simplify and vector.offset rebuild a closed vector from its rounded outline with the layer's corner smoothing, as the canvas draws it. A vector whose regions have paints of their own was rebuilt from its sharp points before; it now keeps its rounded corners. The Penpot export writes a stroked vector's path with its smoothed corners. --- crates/engine/src/cmd/structure.rs | 13 ++++--- crates/engine/src/vector_behaviour_tests.rs | 39 +++++++++++++++++++++ crates/format/src/penpot/export.rs | 4 ++- crates/format/src/penpot/export_tests.rs | 26 ++++++++++++++ 4 files changed, 77 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/structure.rs b/crates/engine/src/cmd/structure.rs index 52b4a415d..5a79d0a24 100644 --- a/crates/engine/src/cmd/structure.rs +++ b/crates/engine/src/cmd/structure.rs @@ -751,8 +751,11 @@ fn simplify(s: &mut Session, p: &Value) -> Result { for i in req_targets("vector.simplify", s, p)? { let doc = s.doc_mut()?; let n = doc.get_mut(i)?; + let smoothing = n.corners.smoothing; if let NodeKind::Vector { network } = &mut n.kind { let source = network.clone(); + // The regions as the layer draws them: rounded points with the layer's corner smoothing. + let drawn = figcraft_doc::geometry::drawn_network(&source, smoothing); let mut net = VectorNetwork::default(); let legacy = source.regions.iter().all(|region| region.fills.is_none() && region.paint_space.is_none()); if legacy && !source.regions.is_empty() { @@ -761,7 +764,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result { } else { WindingRule::NonZero }; - let path = source.fill_path(); + let path = drawn.fill_path(); let path = figcraft_geom::kurbo::simplify::simplify_bezpath(path.iter(), tol, &Default::default()); let (path, output_winding) = match figcraft_pathops::simplify_with_rule(&path, winding == WindingRule::EvenOdd) { Ok(path) => (path, WindingRule::EvenOdd), @@ -771,7 +774,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result { append_region_path(&mut net, &path, &combined, output_winding); } else { for (index, region) in source.regions.iter().enumerate() { - let Some(path) = source.region_path(index) else { continue }; + let Some(path) = drawn.region_path(index) else { continue }; let path = figcraft_geom::kurbo::simplify::simplify_bezpath(path.iter(), tol, &Default::default()); let path = figcraft_pathops::simplify_with_rule(&path, region.winding == WindingRule::EvenOdd).unwrap_or(path); append_region_path(&mut net, &path, region, region.winding); @@ -859,8 +862,10 @@ fn offset_path(s: &mut Session, p: &Value) -> Result { nm.height = bb.height(); continue; } + // The regions as the layer draws them: rounded points with the layer's corner smoothing. + let drawn = figcraft_doc::geometry::drawn_network(source, n.corners.smoothing); if legacy { - let path = source.fill_path(); + let path = drawn.fill_path(); let even_odd = source.regions.iter().any(|region| region.winding == WindingRule::EvenOdd); let path = figcraft_pathops::simplify_with_rule(&path, even_odd).map_err(|error| bad("vector.offset", error.to_string()))?; let ring = figcraft_pathops::stroke_center(&path, d.abs() * 2.0, &props); @@ -880,7 +885,7 @@ fn offset_path(s: &mut Session, p: &Value) -> Result { append_network(&mut net, part); } else { for (index, region) in source.regions.iter().enumerate() { - let Some(path) = source.region_path(index) else { continue }; + let Some(path) = drawn.region_path(index) else { continue }; let mut paint_region = region.clone(); let (paint_width, paint_height, paint_transform) = region.paint_frame(n.width, n.height); paint_region.paint_space = Some(RegionPaintSpace { width: paint_width, height: paint_height, transform: paint_transform }); diff --git a/crates/engine/src/vector_behaviour_tests.rs b/crates/engine/src/vector_behaviour_tests.rs index 83e585ea0..c990ad348 100644 --- a/crates/engine/src/vector_behaviour_tests.rs +++ b/crates/engine/src/vector_behaviour_tests.rs @@ -278,6 +278,45 @@ fn legacy_evenodd_holes_survive_bucket_offset_and_flatten() { assert!(!net(&s, flattened).fill_contains(Point::new(100.0, 100.0)), "flatten retains the even-odd hole"); } +#[test] +fn simplify_and_offset_keep_a_closed_vectors_smoothed_corners() { + // A closed 100 × 100 vector with radius 20 on every point and corner smoothing 0.6 draws a + // smoothed rectangle's outline; simplify and offset rebuild it from that outline. + let drawn = figcraft_geom::rounded_rect(100.0, 100.0, [20.0; 4], 0.6); + let plain = figcraft_geom::rounded_rect(100.0, 100.0, [20.0; 4], 0.0).area().abs(); + let (area, d) = (drawn.area().abs(), 2.0); + // Offsetting a convex outline by d adds its perimeter times d and a circle of radius d. + let grown = area + drawn.perimeter(1e-6) * d + std::f64::consts::PI * d * d; + assert!((area - plain).abs() > 10.0, "smoothing changes the outline: {area} vs {plain}"); + // (command, params, region paints of its own, expected area, tolerance: the offset ring is + // flattened before the union) + let rows = [ + ("vector.simplify", json!({"tolerance": 0.01}), false, area, 1.0), + ("vector.simplify", json!({"tolerance": 0.01}), true, area, 1.0), + ("vector.offset", json!({"offset": d}), false, grown, 4.0), + ("vector.offset", json!({"offset": d}), true, grown, 4.0), + ]; + let mut wrong = Vec::new(); + for (cmd, mut params, painted, expected, tolerance) in rows { + let mut s = Session::new(); + let id = id_of(&ex(&mut s, "vector.create", json!({"points": [[0, 0], [100, 0], [100, 100], [0, 100]], "closed": true}))["id"]).unwrap(); + ex(&mut s, "node.set", json!({"ids": [id], "props": {"cornerRadius": 20}})); + ex(&mut s, "node.set", json!({"ids": [id], "props": {"cornerSmoothing": 0.6}})); + if painted { + let doc = s.doc_mut().unwrap(); + let NodeKind::Vector { network } = &mut doc.get_mut(id).unwrap().kind else { panic!("expected vector fixture") }; + network.regions[0].fills = Some(vec![figcraft_color::Paint::solid(figcraft_color::Color::BLACK)]); + } + params["ids"] = json!([id]); + ex(&mut s, cmd, params); + let got = net(&s, id).fill_path().area().abs(); + if (got - expected).abs() >= tolerance { + wrong.push(format!("{cmd} (region paints: {painted}): {got} vs {expected}")); + } + } + assert!(wrong.is_empty(), "simplify and offset keep the smoothed corners: {wrong:?}"); +} + /// Give vector `id` a painted region, converting a plain shape to a vector first. fn ex_to_vector(doc: &mut figcraft_doc::Document, id: NodeId) { let n = doc.get(id).unwrap(); diff --git a/crates/format/src/penpot/export.rs b/crates/format/src/penpot/export.rs index cacafd0d9..d0b9d3046 100644 --- a/crates/format/src/penpot/export.rs +++ b/crates/format/src/penpot/export.rs @@ -713,7 +713,9 @@ impl<'a> Exporter<'a> { } } } - NodeKind::Vector { network } if node.fills.is_empty() || !node.strokes.is_empty() => self.doc.world_transform(id) * network.stroke_path(), + NodeKind::Vector { network } if node.fills.is_empty() || !node.strokes.is_empty() => { + self.doc.world_transform(id) * figcraft_doc::geometry::drawn_network(network, node.corners.smoothing).stroke_path() + } _ => match figcraft_doc::geometry::shape_path(node) { Some(p) => self.doc.world_transform(id) * p, None => BezPath::new(), diff --git a/crates/format/src/penpot/export_tests.rs b/crates/format/src/penpot/export_tests.rs index 4dacd4eae..1e9e95638 100644 --- a/crates/format/src/penpot/export_tests.rs +++ b/crates/format/src/penpot/export_tests.rs @@ -174,6 +174,32 @@ fn rectangles_ellipses_and_paths_keep_their_geometry() { assert!(matches!(back.node(named(&back, "Circle")).unwrap().kind, NodeKind::Ellipse { .. })); } +#[test] +fn stroked_closed_vectors_are_written_with_their_corner_smoothing() { + // A stroked closed 100 × 100 vector with radius 20 on every point and corner smoothing 0.6 is + // written as the smoothed outline it draws. + let mut doc = Document::new("Smoothed vector"); + let p = page(&doc); + let corners = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)]; + let mut network = VectorNetwork::from_points(&corners, true); + for v in &mut network.vertices { + v.radius = 20.0; + } + let id = add(&mut doc, p, NodeKind::Vector { network }, "Smoothed", 0.0, 0.0, 100.0, 100.0); + { + let n = doc.node_mut(id).unwrap(); + n.fills = vec![Paint::solid(Color::BLACK)]; + n.strokes = vec![Paint::solid(Color::BLACK)]; + n.corners.smoothing = 0.6; + } + let want = figcraft_doc::geom::rounded_rect(100.0, 100.0, [20.0; 4], 0.6).area().abs(); + let plain = figcraft_doc::geom::rounded_rect(100.0, 100.0, [20.0; 4], 0.0).area().abs(); + assert!((want - plain).abs() > 10.0, "smoothing changes the outline: {want} vs {plain}"); + let (back, _, _) = roundtrip(&doc); + let written = figcraft_doc::geometry::shape_path(back.node(named(&back, "Smoothed")).unwrap()).unwrap().area().abs(); + assert!((written - want).abs() < 0.5, "the written path keeps the smoothed corners: {written} vs {want}"); +} + #[test] fn fills_and_strokes_keep_their_order_and_styles() { let mut doc = Document::new("Paints");