Browse / github.com/storytold/vectorcraft / patch
Width profiles run smooth between their points
Width profiles run smooth between their points ## What Width profiles currently interpolate **linearly** between their width points, so every width point is a corner: a stroke's outline kinks and the width changes direction abruptly. Illustrator's variable-width strokes ease in and out of their points. This PR makes a width profile's sides run as a **smooth C1 curve between the points**, while keeping everything else about profiles (steps between coincident points, one-sided profiles, presets, the Width tool) working as before. ## How - **Smooth interpolation** (`crates/doc/src/appearance.rs`): `WidthProfile::at_points` now eva
- Status
- open
- Score
- 0.00
- Adopters
- 0 other operators
- Author
- adambelis (imported from pull request #3145, open)
- Base
443b31b13df3a7ab611c2fe1b95e73898ed74fdd- Size
- +1001 −144 in 15 files
- Review
- pending
- Shared
- 2026-10-28
- Id
3dfebd7593c375e8a7be851f
How it went
No other operator has reported using it yet.
Diff
raw · crates/doc/src/appearance/profile.rs crates/doc/src/appearance/tests.rs crates/doc/src/reach.rs crates/effects/src/stroke/gradient.rs crates/effects/src/stroke/tests.rs crates/effects/src/stroke/tests_fit.rs crates/effects/src/stroke/tests_gradient.rs crates/effects/src/stroke/width.rs crates/engine/src/tests/outlinestroke.rs crates/engine/src/tests/widthpoints.rs crates/pathops/src/fit.rs crates/pathops/src/lib.rs crates/render/src/renderer/paint.rs crates/ui-egui/src/dialogs/width_point/tests.rs docs/target-app-parity.md
@@ -20,25 +20,39 @@ pub struct ProfilePreset { } impl WidthProfile {- /// (left, right) width factors at `t`, linear between points.+ /// (left, right) width factors at `t`: a smooth cubic between the points. pub fn at(&self, t: f64) -> (f64, f64) { Self::at_points(&self.points, t) } /// [`Self::at`] of a profile's points (a preset's or a saved profile's).+ ///+ /// The width runs as a cubic Hermite curve through the points, its slope at each one the+ /// weighted harmonic mean of the secants either side (Fritsch–Carlson). That is C1+ /// continuous and monotone between points, so it never overshoots them, a point eases into+ /// its neighbours instead of making a corner, and moving one reshapes the curve as far as its+ /// neighbours' neighbours (their slopes depend on it). The ends use the one-sided PCHIP+ /// slope, or the secant when there are only two points, so a two-point profile stays a+ /// straight taper. Two points at one `t` are still a step: the runs either side are+ /// independent and flat there. pub fn at_points(p: &[(f64, f64, f64)], t: f64) -> (f64, f64) {- if p.is_empty() {- return (1.0, 1.0);+ let (Some(first), Some(last)) = (p.first(), p.last()) else { return (1.0, 1.0) };+ if t <= first.0 {+ return (first.1, first.2); }- if t <= p[0].0 {- return (p[0].1, p[0].2);+ if t >= last.0 {+ return (last.1, last.2); }- for w in p.windows(2) {- if t <= w[1].0 {- let u = (t - w[0].0) / (w[1].0 - w[0].0).max(1e-9);- return (w[0].1 + (w[1].1 - w[0].1) * u, w[0].2 + (w[1].2 - w[0].2) * u);- }+ // The segment ending at or after `t`: a step's zero-length segment is skipped, so `t`+ // exactly at a step still reads the width just before it (as `around` documents).+ let Some(i) = p.windows(2).position(|w| t <= w[1].0) else { return (last.1, last.2) };+ let (Some(&(t0, l0, r0)), Some(&(t1, l1, r1))) = (p.get(i), p.get(i + 1)) else { return (last.1, last.2) };+ let h = t1 - t0;+ if h <= 1e-12 {+ return (l1, r1); }- p.last().map_or((1.0, 1.0), |l| (l.1, l.2))+ let u = (t - t0) / h;+ let (ml0, mr0, ml1, mr1) = (slope(p, i, false), slope(p, i, true), slope(p, i + 1, false), slope(p, i + 1, true));+ (hermite(u, h, l0, l1, ml0, ml1), hermite(u, h, r0, r1, mr0, mr1)) } /// The built-in profiles, in menu order. "uniform" is the plain stroke (no profile). pub const PRESETS: [ProfilePreset; 7] = [@@ -90,6 +104,81 @@ impl WidthProfile { } } +/// The one-sided three-point PCHIP slope at the start of a run, from the first two secants.+/// The caller uses the secant for a run of only two points; a sign change caps the slope, and a+/// slope that turns back on the first secant is flattened.+fn end_slope(h0: f64, h1: f64, d0: f64, d1: f64) -> f64 {+ let m = ((2.0 * h0 + h1) * d0 - h0 * d1) / (h0 + h1);+ if !m.is_finite() || m * d0 <= 0.0 {+ return 0.0;+ }+ if d0 * d1 < 0.0 {+ return if d0 > 0.0 { m.min(3.0 * d0) } else { m.max(3.0 * d0) };+ }+ m+}++/// The slope of the smooth width curve at `p[i]` for one side: the weighted harmonic mean of the+/// secants either side. The profile's first and last points use the one-sided three-point PCHIP+/// slope instead (or the secant when their run has only two points), so a two-point profile stays+/// a straight taper. Either side of a step, and at a local extremum, the slope is flat.+fn slope(p: &[(f64, f64, f64)], i: usize, right: bool) -> f64 {+ let value = |k: usize| p.get(k).map_or(0.0, |q| if right { q.2 } else { q.1 });+ let Some(&(t, _, _)) = p.get(i) else { return 0.0 };+ if i == 0 {+ let Some(&(t1, _, _)) = p.get(1) else { return 0.0 };+ let h0 = t1 - t;+ if h0 <= 1e-12 {+ return 0.0;+ }+ let d0 = (value(1) - value(0)) / h0;+ let Some(&(t2, _, _)) = p.get(2) else { return d0 };+ let h1 = t2 - t1;+ if h1 <= 1e-12 {+ return d0;+ }+ let d1 = (value(2) - value(1)) / h1;+ return end_slope(h0, h1, d0, d1);+ }+ if i + 1 == p.len() {+ let Some(&(tm, _, _)) = i.checked_sub(1).and_then(|k| p.get(k)) else { return 0.0 };+ let h0 = t - tm;+ if h0 <= 1e-12 {+ return 0.0;+ }+ let d0 = (value(i) - value(i - 1)) / h0;+ let Some(&(tmm, _, _)) = i.checked_sub(2).and_then(|k| p.get(k)) else { return d0 };+ let h1 = tm - tmm;+ if h1 <= 1e-12 {+ return d0;+ }+ let d1 = (value(i - 1) - value(i - 2)) / h1;+ return end_slope(h0, h1, d0, d1);+ }+ let (Some(&(tm, _, _)), Some(&(tp, _, _))) = (i.checked_sub(1).and_then(|k| p.get(k)), p.get(i + 1)) else {+ return 0.0;+ };+ let (h0, h1) = (t - tm, tp - t);+ if h0 <= 1e-12 || h1 <= 1e-12 {+ return 0.0;+ }+ let (d0, d1) = ((value(i) - value(i - 1)) / h0, (value(i + 1) - value(i)) / h1);+ if d0 * d1 <= 0.0 {+ return 0.0;+ }+ let (a, b) = (2.0 * h1 + h0, h1 + 2.0 * h0);+ let m = (a + b) / (a / d0 + b / d1);+ // A file's widths are only checked to be finite: keep a slope that overflows flat.+ if m.is_finite() { m } else { 0.0 }+}++/// A cubic Hermite from `y0` at `u = 0` to `y1` at `u = 1` over `h` (in `t`), with `m0`/`m1` the+/// slopes at its ends (width factor per `t`).+fn hermite(u: f64, h: f64, y0: f64, y1: f64, m0: f64, m1: f64) -> f64 {+ let (u2, u3) = (u * u, u * u * u);+ (2.0 * u3 - 3.0 * u2 + 1.0) * y0 + (u3 - 2.0 * u2 + u) * h * m0 + (3.0 * u2 - 2.0 * u3) * y1 + (u3 - u2) * h * m1+}+ /// Pen pressure recorded along a stroke (the Paintbrush with a graphics tablet): (position 0..1 /// along the path, pressure 0..1) samples in order, positions measured as a [`WidthProfile`]'s /// are. Calligraphic brushes with Pressure variation read it; everything else ignores it.@@ -144,10 +144,83 @@ fn strokes_without_pressure_round_trip_unchanged() { fn profile_interp() { let p = WidthProfile::lens(); assert_eq!(p.at(0.5), (1.0, 1.0));- assert_eq!(p.at(0.25), (0.5, 0.5));+ assert_eq!(p.at(0.25), (0.75, 0.75)); assert_eq!(p.at(2.0), (0.0, 0.0)); } +/// The width runs smoothly between points: it passes through them, has one slope either side+/// of one, and never overshoots the widths its points set.+#[test]+fn profile_is_smooth_between_points() {+ let p = [(0.0, 1.0, 2.0), (0.5, 0.2, 2.0), (1.0, 1.0, 2.0)];+ assert!((WidthProfile::at_points(&p, 0.5).0 - 0.2).abs() < 1e-12);+ let slope = |t: f64| (WidthProfile::at_points(&p, t + 1e-6).0 - WidthProfile::at_points(&p, t - 1e-6).0) / 2e-6;+ // A local minimum at the middle point is flat there, so the two sides agree.+ assert!(slope(0.5).abs() < 1e-3, "{}", slope(0.5));+ for k in 0..=100 {+ let w = WidthProfile::at_points(&p, k as f64 / 100.0).0;+ assert!((0.2..=1.0).contains(&w), "{w} at {k}");+ }+ // The side with no points of its own stays flat.+ for k in 0..=100 {+ assert!((WidthProfile::at_points(&p, k as f64 / 100.0).1 - 2.0).abs() < 1e-12);+ }+}++/// A run with only two points takes its secant as both end slopes, so it stays a straight+/// taper on each side instead of becoming a smoothstep.+#[test]+fn profile_two_point_runs_are_linear() {+ let p = [(0.0, 0.0, 1.0), (1.0, 1.0, 0.0)];+ for k in 0..=100 {+ let t = k as f64 / 100.0;+ let (l, r) = WidthProfile::at_points(&p, t);+ assert!((l - t).abs() < 1e-12, "left {l} at {t}");+ assert!((r - (1.0 - t)).abs() < 1e-12, "right {r} at {t}");+ }+}++/// The lens's one-sided end slopes make it a parabola: at a quarter of the way it is 0.75,+/// above the 0.5 a straight line between its points would give.+#[test]+fn profile_lens_is_convex() {+ let p = WidthProfile::lens();+ assert!((p.at(0.25).0 - 0.75).abs() < 1e-12);+ assert!((p.at(0.75).0 - 0.75).abs() < 1e-12);+ for k in 1..25 {+ let t = k as f64 / 100.0;+ assert!(p.at(t).0 > 2.0 * t, "{} at {t}", p.at(t).0);+ assert!(p.at(1.0 - t).0 > 2.0 * t, "{} at {}", p.at(1.0 - t).0, 1.0 - t);+ }+}++/// A step still steps, and the smooth runs either side meet it flat.+#[test]+fn profile_steps_stay_steps() {+ let p = [(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5, 2.0, 2.0), (1.0, 2.0, 2.0)];+ assert_eq!(WidthProfile::at_points(&p, 0.5), (1.0, 1.0));+ assert_eq!(WidthProfile::at_points(&p, 0.5 + 1e-6), (2.0, 2.0));+ assert_eq!(WidthProfile::at_points(&p, 0.5 - 1e-6), (1.0, 1.0));+ assert_eq!(WidthProfile::at_points(&p, 0.25), (1.0, 1.0));+ assert_eq!(WidthProfile::at_points(&p, 0.75), (2.0, 2.0));+}++/// Moving a point only reshapes the segments beside it (local influence), not the whole path.+#[test]+fn profile_points_only_affect_the_curve_around_them() {+ // A monotone run, so no neighbouring slope is held flat by a local extremum.+ let a = [(0.0, 0.0, 0.0), (0.25, 0.3, 0.3), (0.5, 0.5, 0.5), (0.75, 0.7, 0.7), (1.0, 1.0, 1.0)];+ let mut b = a;+ b[3] = (0.75, 0.9, 0.9);+ // Moving p[3] changes the slopes at p[2] and p[3], so p[1] and p[4] also shape the+ // curve: nothing before p[1] may move.+ for k in 0..=24 {+ let t = k as f64 / 100.0;+ assert_eq!(WidthProfile::at_points(&a, t), WidthProfile::at_points(&b, t), "at {t}");+ }+ assert_ne!(WidthProfile::at_points(&a, 0.3), WidthProfile::at_points(&b, 0.3));+}+ #[test] fn profile_presets_round_trip_their_ids() { for p in WidthProfile::PRESETS {@@ -86,10 +86,8 @@ fn head_ends(st: &StrokeLayer, bp: &BezPath) -> Vec<(Point, Vec2, bool)> { /// at `t`): the profile at that fraction of the subpath's length, or wider where an end of the /// segment is a corner. The stroke draws the sides there straight to the corner's join and inner /// meeting point, which can lie outside the exact width all along the segment.-fn profile_at(profile: &WidthProfile, segs: &[PathSeg], closed: bool, i: usize, t: f64) -> (f64, f64) {+fn profile_at(profile: &WidthProfile, segs: &[PathSeg], lens: &[f64], total: f64, closed: bool, i: usize, t: f64) -> (f64, f64) { let n = segs.len();- let lens: Vec<f64> = segs.iter().map(|s| s.arclen(ARCLEN_ACCURACY)).collect();- let total: f64 = lens.iter().sum::<f64>().max(1e-12); let before = lens[..i].iter().sum::<f64>(); let mut w = profile.at((before + segs[i].subsegment(0.0..t).arclen(ARCLEN_ACCURACY)) / total); let corner = |a: usize, b: usize| (closed || a < b) && kink(&segs[a], &segs[b]);@@ -168,7 +166,8 @@ impl StrokeLayer { /// Does this stroke along `bp` (filled with `rule`) paint within `tol` of `p`? Inside and /// outside strokes of closed paths count on their own side only (and within `tol` of the- /// path); a width profile counts at its width where `p` is nearest.+ /// path); a width profile counts at the width of every segment that can reach `p`, as the+ /// wider side of a farther one can paint past the nearest. pub fn hits(&self, bp: &BezPath, rule: FillRule, p: Point, tol: f64) -> bool { let reach = self.reach() + tol; if self.width.is_nan() || self.width <= 0.0 || !bp.bounding_box().inflate(reach, reach).contains(p) {@@ -192,17 +191,27 @@ impl StrokeLayer { let segs = drawn(&els[r]); let (half, region) = self.body(closed); let full = half * self.profile_max() * dash_caps.unwrap_or(1.0);- // The nearest point on this subpath.- let near = segs.iter().enumerate().map(|(i, s)| (i, s.nearest(p, 1e-9))).min_by(|a, b| a.1.distance_sq.total_cmp(&b.1.distance_sq));- if let Some((i, nr)) = near- && nr.distance_sq.sqrt() <= full + tol- {+ // Every segment near enough to reach `p`: with a width profile the wider side of a+ // farther segment can paint past the nearest one, so the nearest alone is not enough.+ let near = segs.iter().enumerate().filter_map(|(i, s)| {+ let nr = s.nearest(p, 1e-9);+ (nr.distance_sq.sqrt() <= full + tol).then_some((i, nr))+ });+ // The lengths are only needed when a profiled candidate reaches `p`; compute them+ // once for the whole subpath rather than once per candidate.+ let mut lengths: Option<(Vec<f64>, f64)> = None;+ for (i, nr) in near { let d = nr.distance_sq.sqrt(); let factor = if dash_caps.is_some() { full / half.max(1e-12) } else { self.profile.as_ref().map_or(1.0, |pr| {- let (l, rt) = profile_at(pr, &segs, closed, i, nr.t);+ let (lens, total) = lengths.get_or_insert_with(|| {+ let lens: Vec<f64> = segs.iter().map(|s| s.arclen(ARCLEN_ACCURACY)).collect();+ let total = lens.iter().sum::<f64>().max(1e-12);+ (lens, total)+ });+ let (l, rt) = profile_at(pr, &segs, lens, *total, closed, i, nr.t); // Nearest to a segment's end, `p` is beside a join or past a cap, which // spans the widths of both sides. let at_end = nr.t <= 1e-9 || nr.t >= 1.0 - 1e-9;@@ -16,7 +16,7 @@ use kurbo::{BezPath, Point, Shape, Vec2}; use vectorcraft_doc::color::{Gradient, GradientGeom, GradientPaint, Paint}; use vectorcraft_doc::live::{H_DOWN, H_LEFT, H_RIGHT, H_UP};-use vectorcraft_doc::{GradientMesh, LineJoin, MeshPoint, StrokeAlign, StrokeGradientMode, StrokeLayer};+use vectorcraft_doc::{GradientMesh, LineCap, LineJoin, MeshPoint, StrokeAlign, StrokeGradientMode, StrokeLayer}; use vectorcraft_geom::FillRule; use super::width::{flatten, left, length, split_at};@@ -147,7 +147,10 @@ fn strips(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64, if !(hw > 0.0 && hw.is_finite()) { return vec![]; }- let full = hw * st.profile_max();+ // A projecting cap on every dash reaches a corner half a width along the path and half across+ // from the dash's end, so the ribs reach further to cover what those dashes paint.+ let capped = st.cap == LineCap::Square && st.dash.as_ref().is_some_and(|d| d.is_dashed());+ let full = hw * st.profile_max() * if capped { std::f64::consts::SQRT_2 } else { 1.0 }; let heads = (st.head_reach(false), st.head_reach(true)); let cap = cap_extent(st.cap, 2.0 * full); let lay = Lay { st, hw, cover: full + margin, margin, ext: (cap.max(heads.0) + margin, cap.max(heads.1) + margin) };@@ -155,20 +158,21 @@ fn strips(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64, let count = subs.len(); let mut out = vec![]; for (k, (range, closed)) in subs.into_iter().enumerate() {- let (pts, corner) = flatten(&segments(&bp.elements()[range]), closed, tol.max(1e-4));- let side =- (st.align != StrokeAlign::Center && closed_path && closed).then(|| band_on_left(bp, rule, &pts, st.align, (4.0 * tol).min(hw / 2.0)));+ let segs = segments(&bp.elements()[range]);+ let flat = flatten(&segs, closed, tol.max(1e-4));+ let side = (st.align != StrokeAlign::Center && closed_path && closed)+ .then(|| band_on_left(bp, rule, &flat.pts, st.align, (4.0 * tol).min(hw / 2.0))); // Arrowheads sit on the start of the first subpath and the end of the last one. let heads = (if k == 0 { heads.0 } else { 0.0 }, if k + 1 == count { heads.1 } else { 0.0 });- let ribs = match pts.len() {+ let ribs = match flat.pts.len() { 0 => continue, // A subpath of no length: a dot (round and projecting caps paint it). 1 => { let (d, b, e) = (Vec2::new(1.0, 0.0), lay.band(0.0, side), lay.ext.0.max(lay.ext.1));- vec![Rib::square(pts[0] - d * e, d, lay.cover, 0.0, b), Rib::square(pts[0] + d * e, d, lay.cover, 0.0, b)]+ vec![Rib::square(flat.pts[0] - d * e, d, lay.cover, 0.0, b), Rib::square(flat.pts[0] + d * e, d, lay.cover, 0.0, b)] } _ => {- let total = length(&pts, closed);+ let total = length(&flat.pts, closed); if total <= 1e-12 { continue; }@@ -176,7 +180,7 @@ fn strips(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64, let profile = st.profile.iter().flat_map(|p| p.points.iter().map(|q| q.0)); let at: Vec<f64> = marks.iter().copied().chain(profile).chain((1..steps).map(|i| i as f64 / steps as f64)).map(|t| t * total).collect();- let (pts, _) = split_at(&pts, &corner, closed, &at);+ let (pts, _, _) = split_at(&flat, closed, &at, &segs); strip(&lay, &pts, closed, total, side, if closed { (0.0, 0.0) } else { heads }) } };@@ -152,14 +152,15 @@ fn line_outline_uses_the_profile_dashes_or_a_plain_stroke() { let plain = line_outline(&l, &stroke(10.0, |_| {}), 10.0, 1e-3); assert!(near(plain.area().abs(), 1000.0, 1e-6)); let lens = line_outline(&l, &stroke(10.0, |s| s.profile = Some(WidthProfile::lens())), 10.0, 1e-3);- assert!(near(lens.area().abs(), 500.0, 1e-6));+ // The smoothed sides are cubics through the profile's samples: 0.06 pt² off the polygon.+ assert!(near(lens.area().abs(), 2000.0 / 3.0, 0.1)); // Each dash takes its widths from where it sits along the lens (0 → 1 → 0): the dash over- // 0..25 averages a quarter of the width, the one over 50..75 three quarters.+ // 0..25 averages 5/12 of the width, the one over 50..75 11/12. let st = stroke(10.0, |s| { s.profile = Some(WidthProfile::lens()); s.dash = Some(dashed(&[25.0, 25.0], 0.0)); });- assert!(near(line_outline(&l, &st, 10.0, 1e-3).area().abs(), 62.5 + 187.5, 1e-6));+ assert!(near(line_outline(&l, &st, 10.0, 1e-3).area().abs(), 1000.0 / 3.0, 0.1)); assert!(line_outline(&BezPath::new(), &st, 10.0, 1e-3).elements().is_empty()); } @@ -155,9 +155,10 @@ fn each_dash_takes_its_width_from_the_profile_along_the_whole_path() { s.dash = Some(Dash { pattern: vec![10.0, 10.0], offset: 0.0, align_corners: false }); }); let o = line_outline(&line(100.0), &st, 10.0, 1e-3);- // The dash over 40..50 is near the lens's widest point; the one over 0..10 near its tip.+ // The dash over 40..50 is near the lens's widest point; the one over 0..10 near its tip,+ // where the smooth profile is thinner than a straight ramp (a parabola's first tenth). assert!(o.contains(Point::new(45.0, 4.0)) && o.contains(Point::new(45.0, -4.0)), "middle dash is wide");- assert!(!o.contains(Point::new(5.0, 2.0)) && o.contains(Point::new(5.0, 0.3)), "first dash is thin");+ assert!(o.contains(Point::new(5.0, 0.8)) && !o.contains(Point::new(5.0, 1.2)), "first dash is thin"); assert!(!o.contains(Point::new(15.0, 0.0)), "gaps stay empty"); // Dots too: a round dot near the middle is bigger than one near an end. let st = stroke(10.0, |s| {@@ -166,7 +167,7 @@ fn each_dash_takes_its_width_from_the_profile_along_the_whole_path() { s.dash = Some(Dash { pattern: vec![0.0, 10.0], offset: 0.0, align_corners: false }); }); let o = line_outline(&line(100.0), &st, 10.0, 1e-3);- assert!(o.contains(Point::new(50.0, 4.5)) && !o.contains(Point::new(10.0, 1.5)) && o.contains(Point::new(10.0, 0.5)));+ assert!(o.contains(Point::new(50.0, 4.5)) && o.contains(Point::new(10.0, 1.4)) && !o.contains(Point::new(10.0, 2.0))); } /// An L whose corner turns 90° at (100, 0), or a sharp V turning back at (100, 0).@@ -137,8 +137,8 @@ fn across_runs_from_the_left_edge_to_the_right() { let mut lens = st.clone(); lens.profile = Some(WidthProfile::lens()); let sl = slices(&line, &lens);- // A quarter of the way along, the lens is half as wide: its top edge is 2.5 up.- assert!(param(&sl, Point::new(25.0, -2.4)).unwrap() < 0.05);+ // A quarter of the way along, the lens is three quarters as wide: its top edge is 3.75 up.+ assert!(param(&sl, Point::new(25.0, -3.6)).unwrap() < 0.05); assert!((param(&sl, Point::new(50.0, -2.5)).unwrap() - 0.25).abs() < 0.02); } @@ -3,17 +3,18 @@ //! A stroke with a [`WidthProfile`] is drawn as a filled outline: each subpath is flattened, and //! at every sample the left and right offsets `width/2 · factor(t)` (t = fraction of the //! subpath's length) are placed along the normal. Corners of the path take the stroke's miter,-//! round or bevel join on their outer side (smooth points bend round), open subpaths get butt,-//! round or projecting caps (the round cap blends the two side widths), and closed subpaths become-//! two loops of opposite orientation filled with the non-zero rule. Dashes are pieces of a longer-//! subpath and read the profile where they sit along it ([`outline_spans`]).+//! round or bevel join on their outer side (smooth points offset along the curve's normal), open+//! subpaths get butt, round or projecting caps (the round cap blends the two side widths), and+//! closed subpaths become two loops of opposite orientation filled with the non-zero rule. Dashes+//! are pieces of a longer subpath and read the profile where they sit along it ([`outline_spans`]). use std::f64::consts::PI; -use kurbo::{BezPath, ParamCurve, PathEl, PathSeg, Point, Vec2};+use kurbo::{BezPath, ParamCurve, ParamCurveNearest, PathEl, PathSeg, Point, Vec2}; use vectorcraft_doc::{LineCap, LineJoin, StrokeLayer, WidthProfile};+use vectorcraft_pathops::fit_cubics; -use super::{kink, segments, subpaths, unit};+use super::{kink, segments, subpaths, tangent, unit}; /// Filled outline of `bp` stroked with `width` scaled by `profile`, with the caps, joins and miter /// limit of `st`, flattened to `tol`.@@ -25,12 +26,21 @@ pub fn width_outline(bp: &BezPath, width: f64, profile: &WidthProfile, st: &Stro /// `spans[i]` of the subpath it was cut from (see [`Dashed::spans`](super::Dashed::spans)); /// subpaths without a span are whole. pub(super) fn outline_spans(bp: &BezPath, spans: &[(f64, f64)], width: f64, profile: &WidthProfile, st: &StrokeLayer, tol: f64) -> BezPath {- let ctx = Ctx { half: width / 2.0, profile, cap: st.cap, join: st.join, miter_limit: st.miter_limit, tol: tol.max(1e-4) };+ let ctx = Ctx {+ half: width / 2.0,+ profile,+ cap: st.cap,+ join: st.join,+ miter_limit: st.miter_limit,+ tol: tol.max(1e-4),+ uniform: profile.points.first().is_some_and(|f| profile.points.iter().all(|p| p.1 == f.1 && p.2 == f.2)),+ }; let mut out = BezPath::new(); for (i, (r, closed)) in subpaths(bp).into_iter().enumerate() {- let (pts, corner) = flatten(&segments(&bp.elements()[r]), closed, ctx.tol);- if pts.len() > 1 {- ctx.subpath(&mut out, &pts, &corner, closed, spans.get(i).copied().unwrap_or((0.0, 1.0)));+ let segs = segments(&bp.elements()[r]);+ let flat = flatten(&segs, closed, ctx.tol);+ if flat.pts.len() > 1 {+ ctx.subpath(&mut out, &flat, &segs, closed, spans.get(i).copied().unwrap_or((0.0, 1.0))); } } out@@ -41,19 +51,34 @@ pub(super) fn left(t: Vec2) -> Vec2 { Vec2::new(t.y, -t.x) } +/// A flattened subpath: its points, which of them are corners, and the source segment and+/// parameter range that drew each flattened piece (so a sample added between two points can read+/// that piece's tangent instead of the chord's direction).+pub(super) struct Flat {+ pub(super) pts: Vec<Point>,+ pub(super) corner: Vec<bool>,+ pub(super) seg_of: Vec<usize>,+ /// The source segment's parameter range for each flattened piece. Restricting the tangent+ /// search to this range keeps a sample on the branch that drew it when a cubic loops back+ /// near itself.+ pub(super) param: Vec<(f64, f64)>,+}+ /// The flattened points of one subpath (consecutive duplicates removed; a closed one doesn't /// repeat its start), each marked when it is a corner of the path.-pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> (Vec<Point>, Vec<bool>) {- let Some(s0) = segs.first() else { return (vec![], vec![]) };- let (mut pts, mut corner) = (vec![s0.start()], vec![false]);- // The first and the last segment that drew something.- let (mut first, mut prev): (Option<&PathSeg>, Option<&PathSeg>) = (None, None);- for seg in segs {- let at = pts.len() - 1;+pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> Flat {+ let Some(s0) = segs.first() else { return Flat { pts: vec![], corner: vec![], seg_of: vec![], param: vec![] } };+ let mut flat = Flat { pts: vec![s0.start()], corner: vec![false], seg_of: vec![], param: vec![] };+ // The last segment that drew something, and the last parameter it reached.+ let mut prev: Option<&PathSeg> = None;+ let mut last_added: Option<(usize, f64)> = None;+ for (si, seg) in segs.iter().enumerate() {+ let at = flat.pts.len() - 1;+ let before = flat.pts.len(); let mut push = |p: Point| {- if pts.last().is_none_or(|l| l.distance(p) > 1e-9) {- pts.push(p);- corner.push(false);+ if flat.pts.last().is_none_or(|l| l.distance(p) > 1e-9) {+ flat.pts.push(p);+ flat.corner.push(false); } }; match seg {@@ -66,38 +91,137 @@ pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> (Vec<Point>, } }), }- if pts.len() > at + 1 {- match prev {- Some(p) => corner[at] = kink(p, seg),- None => first = Some(seg),+ if flat.pts.len() > before {+ let end = flat.pts.len() - 1;+ flat.seg_of.resize(end, si);+ for slot in flat.seg_of.iter_mut().take(end).skip(at) {+ *slot = si;+ }+ // Find each new point's source parameter, never going backwards. A point is on the+ // curve, so its nearest parameter is exact except at a self-intersection, where the+ // monotone search picks the branch that continues this flattened piece.+ let mut ts = Vec::with_capacity(end - at + 1);+ ts.push(0.0);+ let mut t = 0.0;+ for p in &flat.pts[at + 1..=end] {+ if t >= 1.0 - 1e-12 {+ t = 1.0;+ } else {+ let sub = seg.subsegment(t..1.0);+ let nr = sub.nearest(*p, 1e-9);+ t = (t + (1.0 - t) * nr.t).clamp(0.0, 1.0);+ }+ ts.push(t);+ }+ flat.param.extend(ts.windows(2).map(|w| (w[0], w[1])));+ last_added = ts.last().map(|t| (si, *t));+ if let Some(p) = prev {+ flat.corner[at] = kink(p, seg); } prev = Some(seg); } } if closed {- if pts.len() > 1 && pts[0].distance(pts[pts.len() - 1]) <= 1e-9 {- pts.pop();- corner.pop();+ if flat.pts.len() > 1 && flat.pts[0].distance(flat.pts[flat.pts.len() - 1]) <= 1e-9 {+ flat.pts.pop();+ flat.corner.pop();+ }+ if let (Some(a), Some(b)) = (segs.last(), segs.first()) {+ flat.corner[0] = kink(a, b); }- if let (Some(a), Some(b)) = (prev, first) {- corner[0] = kink(a, b);+ // The closing piece comes from the last source segment even when its endpoint is the+ // already-present start point and did not add a flattened point. Keep a tangent (and its+ // whole parameter range) for it.+ flat.seg_of.truncate(flat.pts.len());+ flat.param.truncate(flat.pts.len());+ if flat.seg_of.len() < flat.pts.len() {+ let last = segs.len().saturating_sub(1);+ // A closing curve with interior flattened points has already reached a parameter+ // before its end (the duplicated start point was not added); the missing piece starts+ // where it left off, not at 0.+ let start = match last_added {+ Some((si, t)) if si == last => t,+ _ => 0.0,+ };+ flat.seg_of.resize(flat.pts.len(), last);+ flat.param.resize(flat.pts.len(), (start, 1.0)); } }- (pts, corner)+ flat } -/// Insert samples where the profile has width points (so the piecewise-linear profile is exact-/// along straight runs; the two points of a discontinuous point share one sample). `span` maps the-/// subpath onto the profile (see [`outline_spans`]).-fn densify(pts: &[Point], corner: &[bool], closed: bool, profile: &WidthProfile, span: (f64, f64)) -> (Vec<Point>, Vec<bool>) {- let total = length(pts, closed);+/// Insert samples where the profile has width points and between them, so its smooth curve is+/// drawn as a smooth outline along straight runs too (the two points of a discontinuous point+/// share one sample). `span` maps the subpath onto the profile (see [`outline_spans`]).+fn densify(flat: &Flat, segs: &[PathSeg], closed: bool, profile: &WidthProfile, span: (f64, f64)) -> (Vec<Point>, Vec<bool>, Vec<Vec2>) {+ // Two samples per profile segment: the segment end plus its midpoint. The outline is fitted+ // with cubics through these points, so a smooth width curve needs far fewer samples than it+ // did when every pair of samples became a separate cubic. A profile with a strong bend gets+ // one more subdivision; a flat profile draws the same straight pieces as before.+ const SAMPLES: usize = 2;+ const MAX_SAMPLES: usize = 8;+ const BEND: f64 = 0.20;+ let total = length(&flat.pts, closed); let range = span.1 - span.0; if total <= 1e-12 || range <= 1e-12 {- return (pts.to_vec(), corner.to_vec());+ return split_at(flat, closed, &[], segs); } // Where the profile's points fall along this piece (a span past 1 wraps round a closed path).- let marks: Vec<f64> = profile.points.iter().flat_map(|p| [p.0, p.0 + 1.0]).map(|t| (t - span.0) / range * total).collect();- split_at(pts, corner, closed, &marks)+ let mut ts: Vec<f64> = profile.points.iter().flat_map(|p| [p.0, p.0 + 1.0]).collect();+ ts.sort_by(f64::total_cmp);+ ts.dedup_by(|a, b| (*a - *b).abs() <= 1e-9);+ // A flat profile draws the same straight pieces as before: sample only its points.+ let constant = profile.points.first().is_some_and(|f| profile.points.iter().all(|p| (p.1 - f.1).abs() <= 1e-12 && (p.2 - f.2).abs() <= 1e-12));+ let cap = (4096 / ts.len().max(1)).max(1);+ // A curved path's flattened points already sample the width along the subpath. On a dense+ // piece the profile's own points are enough; a straight run has only its ends, so it needs+ // the extra samples. This keeps curved, profiled art close to a uniform stroke's size.+ let pieces = if closed { flat.pts.len() } else { flat.pts.len().saturating_sub(1) }.max(1);+ let spacing = total / pieces as f64;+ let mut marks = Vec::with_capacity(ts.len() * SAMPLES);+ for w in ts.windows(2) {+ let (a, b) = (w[0], w[1]);+ let samples = if constant {+ 1+ } else {+ // `ts` has the profile both at t and t + 1 for a dash crossing a closed seam; the+ // shifted copy has the same shape, so measure its bend on the unshifted segment.+ let start = a.rem_euclid(1.0);+ let end = start + (b - a);+ let want = adaptive_samples(profile, start, end, SAMPLES, MAX_SAMPLES, BEND).min(cap);+ let existing = (b - a) * total / spacing;+ if existing >= want as f64 { 1 } else { want }+ };+ for k in 0..samples {+ marks.push(a + (b - a) * k as f64 / samples as f64);+ }+ }+ if let Some(&last) = ts.last() {+ marks.push(last);+ }+ let marks: Vec<f64> = marks.into_iter().map(|t| (t - span.0) / range * total).collect();+ split_at(flat, closed, &marks, segs)+}++/// How many pieces one profile segment needs so a cubic fit through their ends keeps the width+/// curve. A straight taper is already straight; a visible bend gets progressively more samples.+fn adaptive_samples(profile: &WidthProfile, t0: f64, t1: f64, base: usize, max: usize, bend: f64) -> usize {+ let mut samples = base;+ let (l0, r0) = profile.at(t0);+ let (l1, r1) = profile.at(t1);+ while samples < max {+ let mut dev = 0.0_f64;+ for q in [0.25, 0.5, 0.75] {+ let (l, r) = profile.at(t0 + (t1 - t0) * q);+ let want = (l0 + (l1 - l0) * q, r0 + (r1 - r0) * q);+ dev = dev.max((l - want.0).abs()).max((r - want.1).abs());+ }+ if dev <= bend {+ break;+ }+ samples *= 2;+ }+ samples } /// Length of a flattened subpath (see [`flatten`]).@@ -109,28 +233,70 @@ pub(super) fn length(pts: &[Point], closed: bool) -> f64 { /// A flattened subpath (see [`flatten`]) with points added `marks` along it (distances from its /// start; those on a point or off the subpath are ignored).-pub(super) fn split_at(pts: &[Point], corner: &[bool], closed: bool, marks: &[f64]) -> (Vec<Point>, Vec<bool>) {+pub(super) fn split_at(flat: &Flat, closed: bool, marks: &[f64], segs: &[PathSeg]) -> (Vec<Point>, Vec<bool>, Vec<Vec2>) {+ let Flat { pts, corner, seg_of, param } = flat; let n = pts.len(); let seg_count = if closed { n } else { n.saturating_sub(1) };- let mut out = (Vec::with_capacity(n + marks.len()), Vec::with_capacity(n + marks.len()));+ // The source's direction at a source parameter. The chord direction is the secant, not the+ // tangent: using it for points added inside a chord jogs the normal at every flatten vertex.+ let source_at = |si: usize, t: f64| -> Vec2 { segs.get(si).map_or(Vec2::new(1.0, 0.0), |seg| tangent(seg, t)) };+ // A point added inside a flattened piece searches only that piece's source parameter range:+ // a looping cubic can pass near itself, and a full-segment nearest would take the other+ // branch's tangent.+ let source_near = |p: Point, i: usize| -> Vec2 {+ let Some(si) = seg_of.get(i).copied() else { return Vec2::new(1.0, 0.0) };+ let Some(seg) = segs.get(si) else { return Vec2::new(1.0, 0.0) };+ let (t0, t1) = param.get(i).copied().unwrap_or((0.0, 1.0));+ if t1 - t0 > 1e-12 {+ let sub = seg.subsegment(t0..t1);+ tangent(seg, t0 + (t1 - t0) * sub.nearest(p, 1e-9).t)+ } else {+ tangent(seg, t0)+ }+ };+ // At a shared point, average the arriving and leaving directions unless it is a corner.+ let dir_at = |i: usize| -> Vec2 {+ let incoming = if i == 0 {+ if closed { seg_of.last().copied().zip(param.last().copied()) } else { None }+ } else {+ seg_of.get(i - 1).copied().zip(param.get(i - 1).copied())+ };+ let outgoing = seg_of.get(i).copied().zip(param.get(i).copied());+ let a = incoming.map(|(si, (_, t))| source_at(si, t));+ let b = outgoing.map(|(si, (t, _))| source_at(si, t));+ match (a, b) {+ (Some(a), Some(b)) if !corner[i] => {+ let sum = a + b;+ if sum.hypot() > 1e-9 { unit(sum) } else { b }+ }+ (_, Some(b)) => b,+ (Some(a), None) => a,+ (None, None) => Vec2::new(1.0, 0.0),+ }+ };+ let mut out = (Vec::with_capacity(n + marks.len()), Vec::with_capacity(n + marks.len()), Vec::with_capacity(n + marks.len())); let mut acc = 0.0; for i in 0..seg_count { let (a, b) = (pts[i], pts[(i + 1) % n]); let len = a.distance(b); out.0.push(a); out.1.push(corner[i]);+ out.2.push(dir_at(i)); let mut inner: Vec<f64> = marks.iter().copied().filter(|d| *d > acc + 1e-9 && *d < acc + len - 1e-9).collect(); inner.sort_by(f64::total_cmp); inner.dedup_by(|a, b| (*a - *b).abs() <= 1e-9); for d in inner {- out.0.push(a.lerp(b, (d - acc) / len));+ let p = a.lerp(b, (d - acc) / len);+ out.0.push(p); out.1.push(false);+ out.2.push(source_near(p, i)); } acc += len; } if !closed && n > 0 { out.0.push(pts[n - 1]); out.1.push(corner[n - 1]);+ out.2.push(dir_at(n - 1)); } out }@@ -143,6 +309,8 @@ struct Ctx<'a> { join: LineJoin, miter_limit: f64, tol: f64,+ /// The profile has one (left, right) width everywhere.+ uniform: bool, } /// A vertex of a flattened subpath: where it is, the directions in and out, the lengths of the@@ -151,14 +319,19 @@ struct Vertex { p: Point, a: Vec2, b: Vec2,+ /// The smooth tangent: the source curve's direction at this sample, or the average of its+ /// arriving and leaving directions at a smooth join. A smooth point offsets along this+ /// normal, not the chord bisector; otherwise the chord normal inside each flattened piece and+ /// the bisector at each flatten vertex alternate and the edge is scalloped.+ n: Vec2, la: f64, lb: f64, corner: bool, } impl Ctx<'_> {- fn subpath(&self, out: &mut BezPath, pts: &[Point], corner: &[bool], closed: bool, span: (f64, f64)) {- let (pts, corner) = densify(pts, corner, closed, self.profile, span);+ fn subpath(&self, out: &mut BezPath, flat: &Flat, segs: &[PathSeg], closed: bool, span: (f64, f64)) {+ let (pts, corner, dirs) = densify(flat, segs, closed, self.profile, span); let n = pts.len(); let seg_count = if closed { n } else { n - 1 }; let seg_dir: Vec<Vec2> = (0..seg_count).map(|i| unit(pts[(i + 1) % n] - pts[i])).collect();@@ -174,117 +347,397 @@ impl Ctx<'_> { // at a discontinuous point). let width_at = |d: f64| { let t = span.0 + (span.1 - span.0) * d / total;- let (b, a) = self.profile.around(if t > 1.0 { t - 1.0 } else { t });+ // A closed path joins its own start and end: a profile with different widths there+ // is a step, not a stretch across the seam.+ let (b, a) = if closed && span == (0.0, 1.0) && d <= 1e-12 {+ (self.profile.around(1.0).0, self.profile.around(0.0).1)+ } else {+ self.profile.around(if t > 1.0 { t - 1.0 } else { t })+ }; let side = |(l, r): (f64, f64)| (self.half * l.max(0.0), self.half * r.max(0.0)); (side(b), side(a)) };- let mut lpts = Vec::with_capacity(n);- let mut rpts = Vec::with_capacity(n);+ let mut lpts: Vec<(Point, bool)> = Vec::with_capacity(n);+ let mut rpts: Vec<(Point, bool)> = Vec::with_capacity(n);+ // Only a butt cap makes the side end at a corner; square and round caps stay tangent to it.+ let end_sharp = matches!(self.cap, LineCap::Butt); for (i, &p) in pts.iter().enumerate() {- let (before, after) = width_at(cum[i]);+ let ((wl_b, wr_b), (wl_a, wr_a)) = width_at(cum[i]); if !closed && (i == 0 || i == n - 1) {- let nm = left(seg_dir[i.min(seg_count - 1)]);- let (wl, wr) = if i == 0 { after } else { before };- lpts.push(p + nm * wl);- rpts.push(p - nm * wr);+ let nm = left(dirs[i]);+ let (wl, wr) = if i == 0 { (wl_a, wr_a) } else { (wl_b, wr_b) };+ lpts.push((p + nm * wl, end_sharp));+ rpts.push((p - nm * wr, end_sharp)); continue; } let ip = if i == 0 { seg_count - 1 } else { i - 1 };- let v = Vertex { p, a: seg_dir[ip], b: seg_dir[i], la: cum[ip + 1] - cum[ip], lb: cum[i + 1] - cum[i], corner: corner[i] };+ let v = Vertex { p, a: seg_dir[ip], b: seg_dir[i], n: dirs[i], la: cum[ip + 1] - cum[ip], lb: cum[i + 1] - cum[i], corner: corner[i] }; // A step: the side goes straight out (or in) from the width before to the one after.- for (k, (wl, wr)) in [before, after].into_iter().enumerate() {- if k == 0 || (wl, wr) != before {- self.join(&mut lpts, &v, wl, 1.0);- self.join(&mut rpts, &v, wr, -1.0);- }+ // Both ends of that straight piece are corners: the run before it must not round+ // into the step.+ let (step_l, step_r) = (wl_a != wl_b, wr_a != wr_b);+ self.join(&mut lpts, &v, wl_b, 1.0, step_l);+ self.join(&mut rpts, &v, wr_b, -1.0, step_r);+ if step_l {+ self.join(&mut lpts, &v, wl_a, 1.0, true);+ }+ if step_r {+ self.join(&mut rpts, &v, wr_a, -1.0, true); } } if closed {- polygon(out, lpts.into_iter());- polygon(out, rpts.into_iter().rev());+ polygon(out, lpts.into_iter(), self.tol);+ polygon(out, rpts.into_iter().rev(), self.tol); return; }- let (t0, t1) = (seg_dir[0], seg_dir[seg_count - 1]);+ let (t0, t1) = (dirs[0], dirs[n - 1]); let ((wl0, wr0), (wl1, wr1)) = (width_at(0.0).1, width_at(total).0); let mut ring = lpts; // End cap: from the left side around the end to the right side.- cap_points(&mut ring, pts[n - 1], left(t1), t1, wl1, wr1, self.cap);+ cap_points(&mut ring, pts[n - 1], left(t1), t1, wl1, wr1, self.cap, self.tol); ring.extend(rpts.into_iter().rev()); // Start cap: from the right side around the start back to the left side.- cap_points(&mut ring, pts[0], -left(t0), -t0, wr0, wl0, self.cap);- polygon(out, ring.into_iter());+ cap_points(&mut ring, pts[0], -left(t0), -t0, wr0, wl0, self.cap, self.tol);+ polygon(out, ring.into_iter(), self.tol); } - /// The offset points at `v` on one side (`side` 1: left, −1: right), `w` from the path: the- /// join on the outer side of a turn, the inner miter point (or a detour through the vertex- /// when that would overshoot a segment) on the inner side.- fn join(&self, pts: &mut Vec<Point>, v: &Vertex, w: f64, side: f64) {+ /// The offset points at `v` on one side (`side` 1: left, −1: right), `w` from the path. A+ /// smooth point follows the vertex normal, the offset of the curve itself; a corner takes the+ /// join on its outer side and the inner miter point (or a detour through the vertex when that+ /// would overshoot a segment) on its inner side.+ ///+ /// Each point says whether the outline is sharp there: a path corner, a miter tip, a width+ /// step or a butt cap end. Only those break the smooth fitting; a rapid width change makes+ /// the offset turn sharply, but it is not a corner and must not be fitted as one.+ fn join(&self, pts: &mut Vec<(Point, bool)>, v: &Vertex, w: f64, side: f64, step: bool) { let (na, nb) = (left(v.a) * side, left(v.b) * side); let mid = na + nb; // Cosine of half the turn; the miter point is `w / c` out along `mid`. let c = mid.hypot() / 2.0;- let miter = |pts: &mut Vec<Point>| pts.push(v.p + mid * (w / (2.0 * c * c))); if w <= 0.0 {- pts.push(v.p);- } else if v.b.dot(na) <= 0.0 {+ pts.push((v.p, true));+ return;+ }+ let miter = if c > 1e-9 { Some(v.p + mid * (w / (2.0 * c * c))) } else { None };+ // The offset of the smooth path itself is at `w` along the path normal. The polyline+ // miter (`w / c`) is the offset of the flattened segments, not of the curve: at a tight+ // curve it spiked every sample outward and left a scalloped edge. The source curve's+ // tangent is the smooth normal; a corner still uses its two chords for the join.+ let smooth = v.p + left(v.n) * (w * side);+ if v.b.dot(na) <= 0.0 { // Outer side: the path turns away from it.- let excess = if c > 1e-9 { w * (1.0 / c - 1.0) } else { f64::INFINITY };- match self.join {- _ if excess <= self.tol => miter(pts),- LineJoin::Miter if v.corner && 1.0 / c <= self.miter_limit => miter(pts),- LineJoin::Miter | LineJoin::Bevel if v.corner => pts.extend([v.p + na * w, v.p + nb * w]),- _ => self.arc(pts, v, na, nb, w),+ if !v.corner {+ // A smooth point has no join: its offset is along the path normal.+ pts.push((smooth, step));+ } else {+ let excess = if c > 1e-9 { w * (1.0 / c - 1.0) } else { f64::INFINITY };+ match self.join {+ _ if excess <= self.tol => pts.push((miter.unwrap_or(v.p), true)),+ LineJoin::Miter if c > 1e-9 && 1.0 / c <= self.miter_limit => pts.push((miter.unwrap_or(v.p), true)),+ LineJoin::Miter | LineJoin::Bevel => pts.extend([(v.p + na * w, true), (v.p + nb * w, true)]),+ _ => self.arc(pts, v, na, nb, w, step),+ }+ }+ } else if c <= 1e-9 {+ // A reversal has no inner miter; go through the vertex. That is a notch in the+ // outline, so it stays sharp: fitting a curve through it would loop.+ pts.extend([(v.p + na * w, true), (v.p, true), (v.p + nb * w, true)]);+ } else if !v.corner {+ // A smooth point's inner offset follows its normal too. With a constant profile, once+ // the half-width reaches the local radius of curvature the offset crosses the centre of+ // curvature and comes back as a reversed contour, which the non-zero fill rules into a+ // hole. The stroke covers that centre, so cut through it instead: the cut is inside the+ // painted region and does not show. (With varying widths the crossing usually marks a+ // real caustic; a cut there would show as a slit, so leave it to the offset.)+ let turn = 2.0 * c.clamp(-1.0, 1.0).acos();+ let radius = if turn > 1e-9 { 0.5 * (v.la + v.lb) / turn } else { f64::INFINITY };+ if self.uniform && w >= radius {+ pts.push((smooth, true));+ pts.push((v.p, true));+ pts.push((smooth, true));+ } else {+ pts.push((smooth, step)); }- } else if c > 1e-9 && w * (1.0 - c * c).sqrt() / c <= v.la.min(v.lb) {- miter(pts);+ } else if w * (1.0 - c * c).sqrt() / c <= v.la.min(v.lb) {+ // A corner's inner offset is its miter while that stays inside both segments.+ pts.push((miter.unwrap_or(v.p), true)); } else {- pts.extend([v.p + na * w, v.p, v.p + nb * w]);+ // The inner offset of a corner cuts through the vertex; keep that notch sharp.+ pts.extend([(v.p + na * w, true), (v.p, true), (v.p + nb * w, true)]); } } /// A round join from `na` to `nb` (unit normals) at radius `w` around `v`; a full reversal- /// rounds through the direction of travel.- fn arc(&self, pts: &mut Vec<Point>, v: &Vertex, na: Vec2, nb: Vec2, w: f64) {+ /// rounds through the direction of travel. `sharp` marks a step at the join's ends.+ fn arc(&self, pts: &mut Vec<(Point, bool)>, v: &Vertex, na: Vec2, nb: Vec2, w: f64, sharp: bool) { let phi = if (na + nb).hypot() < 1e-9 { if Vec2::new(-na.y, na.x).dot(v.a) > 0.0 { PI } else { -PI } } else { na.cross(nb).atan2(na.dot(nb)) }; let step = 2.0 * (1.0 - (self.tol / w).min(1.0)).acos(); let steps = ((phi.abs() / step.max(1e-3)).ceil() as usize).clamp(1, 256); for k in 0..=steps { let (s, c) = (phi * k as f64 / steps as f64).sin_cos();- pts.push(v.p + Vec2::new(na.x * c - na.y * s, na.x * s + na.y * c) * w);+ pts.push((v.p + Vec2::new(na.x * c - na.y * s, na.x * s + na.y * c) * w, sharp)); } } } /// Cap points between `c + u·r0` and `c − u·r1`, bulging towards `v`.-fn cap_points(ring: &mut Vec<Point>, c: Point, u: Vec2, v: Vec2, r0: f64, r1: f64, cap: LineCap) {+#[allow(clippy::too_many_arguments)]+fn cap_points(ring: &mut Vec<(Point, bool)>, c: Point, u: Vec2, v: Vec2, r0: f64, r1: f64, cap: LineCap, tol: f64) { match cap { LineCap::Butt => {} LineCap::Square => { let h = (r0 + r1) / 2.0;- ring.push(c + u * r0 + v * h);- ring.push(c - u * r1 + v * h);+ ring.push((c + u * r0 + v * h, true));+ ring.push((c - u * r1 + v * h, true)); } LineCap::Round => {- let steps = 16;+ // Enough steps that the cap's facets stay within `tol`, as a round join does.+ let r = r0.max(r1).max(1e-9);+ let step = 2.0 * (1.0 - (tol / r).min(1.0)).acos();+ let steps = ((PI / step.max(1e-6)).ceil() as usize).clamp(8, 256); for k in 1..steps {- let a = std::f64::consts::PI * k as f64 / steps as f64;+ let a = PI * k as f64 / steps as f64; let r = r0 + (r1 - r0) * (k as f64 / steps as f64);- ring.push(c + u * (a.cos() * r) + v * (a.sin() * r));+ ring.push((c + u * (a.cos() * r) + v * (a.sin() * r), false)); } } } } -fn polygon(out: &mut BezPath, mut pts: impl Iterator<Item = Point>) {- let Some(first) = pts.next() else { return };- out.move_to(first);- for p in pts {- out.line_to(p);+/// Append `pts` as a closed contour (a width outline's ring or loop), through a smooth run's+/// points as cubic curves. Sampled as line segments, a curved, wide stroke shows the facets of+/// its offset whenever it is magnified; the cubics keep it smooth. A run whose points are+/// collinear stays a line, and the points marked sharp — caps, miter joins, width steps and path+/// corners — stay sharp. A rapid width change turns the offset sharply without being a corner:+/// marking corners here rather than measuring turns keeps that turn smooth.+fn polygon(out: &mut BezPath, pts: impl Iterator<Item = (Point, bool)>, tol: f64) {+ let mut ring: Vec<(Point, bool)> = Vec::new();+ for (p, sharp) in pts {+ if !p.x.is_finite() || !p.y.is_finite() {+ return;+ }+ if let Some(last) = ring.last_mut()+ && last.0.distance(p) <= 1e-9+ {+ last.1 |= sharp;+ continue;+ }+ ring.push((p, sharp));+ }+ if ring.len() > 1+ && ring[0].0.distance(ring[ring.len() - 1].0) <= 1e-9+ && let Some(last) = ring.pop()+ {+ ring[0].1 |= last.1;+ }+ let n = ring.len();+ if n == 0 {+ return;+ }+ if n < 3 {+ out.move_to(ring[0].0);+ if n == 2 {+ out.line_to(ring[1].0);+ }+ out.close_path();+ return;+ }+ // Start at a sharp point when there is one, so no run has to wrap: `smooth_run` starts from+ // whichever point is current, and starting anywhere else would bridge over the skipped arc.+ match ring.iter().position(|&(_, sharp)| sharp) {+ None => {+ // A smooth closed loop: fit across the seam, so it doesn't start with a kink.+ let pts: Vec<Point> = ring.iter().map(|&(p, _)| p).collect();+ out.move_to(pts[0]);+ smooth_run(out, &pts, true, tol);+ }+ Some(first) => {+ out.move_to(ring[first].0);+ // From each sharp point to the next; the sharp points themselves stay sharp.+ let mut i = first;+ loop {+ let mut j = (i + 1) % n;+ while !ring[j].1 {+ j = (j + 1) % n;+ }+ // A contour with a single sharp point comes back to it: the run is the whole+ // loop, fitted non-cyclically so that point stays sharp.+ let steps = if j == i { n } else { (j + n - i) % n };+ if steps == 1 {+ out.line_to(ring[j].0);+ } else {+ let run: Vec<Point> = (0..=steps).map(|k| ring[(i + k) % n].0).collect();+ smooth_run(out, &run, false, tol);+ }+ if j == first {+ break;+ }+ i = j;+ }+ } } out.close_path(); } +/// The derivative of the run at each point, in points per point of chord length. Each coordinate+/// is a shape-preserving cubic Hermite (Fritsch–Carlson): between two points it stays within their+/// coordinate range, so a cubic through a fast width pinch cannot bulge past the pinch and cross+/// the other side, and it has a flat slope at a local extremum. A Catmull–Rom tangent (the secant+/// across the neighbours) does neither: it overshoots a V and, with the uneven sample spacing of a+/// flattened path, leaves a scalloped edge.+fn tangents(run: &[Point], cyclic: bool) -> Vec<Vec2> {+ let n = run.len();+ let segs = if cyclic { n } else { n.saturating_sub(1) };+ let mut h = vec![0.0; segs];+ for (i, hi) in h.iter_mut().enumerate() {+ *hi = run[i].distance(run[(i + 1) % n]);+ }+ let slope = |d0: f64, d1: f64, h0: f64, h1: f64| {+ if d0 * d1 <= 0.0 {+ return 0.0;+ }+ let (w0, w1) = (2.0 * h1 + h0, h1 + 2.0 * h0);+ let m = (w0 + w1) / (w0 / d0 + w1 / d1);+ if m.is_finite() { m } else { 0.0 }+ };+ // The one-sided slope of a run's end uses its two end secants, instead of only the last one.+ // A coarse sample then still leaves the end of a profile curve with the right slope.+ let end_slope = |d0: f64, d1: f64, h0: f64, h1: f64| {+ if d0 * d1 <= 0.0 || h0 + h1 <= 1e-12 {+ return 0.0;+ }+ let m = ((2.0 * h0 + h1) * d0 - h0 * d1) / (h0 + h1);+ if m.is_finite() && m * d0 > 0.0 {+ let cap = 3.0 * d0.abs();+ m.clamp(-cap, cap)+ } else {+ 0.0+ }+ };+ let delta = |i: usize| -> Vec2 {+ let hi = h[i % segs];+ if hi > 1e-12 { (run[(i + 1) % n] - run[i % n]) / hi } else { Vec2::ZERO }+ };+ let mut out = vec![Vec2::ZERO; n];+ for (i, m) in out.iter_mut().enumerate() {+ let (d0, d1) = (delta((i + n - 1) % n), delta(i % segs));+ let (h0, h1) = (h[(i + n - 1) % segs], h[i % segs]);+ if h0 <= 1e-12 || h1 <= 1e-12 {+ *m = if h1 > 1e-12 { d1 } else { d0 };+ } else if cyclic || (i > 0 && i + 1 < n) {+ *m = Vec2::new(slope(d0.x, d1.x, h0, h1), slope(d0.y, d1.y, h0, h1));+ } else if i == 0 {+ *m = if n >= 3 {+ let (a, b) = (delta(0), delta(1));+ Vec2::new(end_slope(a.x, b.x, h[0], h[1]), end_slope(a.y, b.y, h[0], h[1]))+ } else {+ d1+ };+ } else {+ *m = if n >= 3 {+ let (a, b) = (delta(n - 2), delta(n - 3));+ Vec2::new(end_slope(a.x, b.x, h[n - 2], h[n - 3]), end_slope(a.y, b.y, h[n - 2], h[n - 3]))+ } else {+ d0+ };+ }+ // A shape-preserving slope is flat in a coordinate at that coordinate's local extremum.+ // Where both are extrema at one sample (a loop or a pinch in the sampled edge) the flat+ // tangent would make a line and a kink; the secant across the sample keeps the curve C1+ // there, and the extremum itself is what trims the loop later.+ if m.hypot() <= 1e-12 {+ let prev = if cyclic || i > 0 { run[(i + n - 1) % n] } else { run[i] };+ let next = if cyclic || i + 1 < n { run[(i + 1) % n] } else { run[i] };+ let sec = next - prev;+ if sec.hypot() > 1e-12 {+ *m = sec.normalize();+ }+ }+ }+ out+}++/// Append a run of points as a fitted chain of cubics (or one line when they are collinear).+///+/// A cubic through every flattened point, as this used to emit, keeps the outline smooth but puts+/// three coordinates per point into the file; a small, thin stroke then exports several times the+/// path data of the same stroke without a profile. Fit a chain within the outline tolerance+/// instead: the result is still G1 continuous and stays within `tol` of the sampled edge, but a+/// smooth side is a few cubics rather than one per flatten step. Profile bends that need finer+/// detail produce more cubics; straight runs stay lines.+fn smooth_run(out: &mut BezPath, run: &[Point], cyclic: bool, tol: f64) {+ let n = run.len();+ if n < 2 {+ return;+ }+ if !cyclic && is_straight(run, tol) {+ out.line_to(run[n - 1]);+ return;+ }+ let tans = tangents(run, cyclic);+ let tol = tol.max(1e-6);+ // A short run is one or two profile features, not flattened path detail. Fitting it loosely+ // enough to save path data can let a handle cross the narrow side of a V; keep the+ // shape-preserving per-point cubics there.+ let segs = if cyclic { n } else { n - 1 };+ if n <= 3 {+ for i in 0..segs {+ let j = (i + 1) % n;+ let h = run[i].distance(run[j]);+ let (m0, m1) = (tans[i] * (h / 3.0), tans[j] * (h / 3.0));+ if m0.hypot() <= 1e-12 || m1.hypot() <= 1e-12 {+ out.line_to(run[j]);+ } else {+ out.curve_to(run[i] + m0, run[j] - m1, run[j]);+ }+ }+ return;+ }+ let unit_or = |v: Vec2, fallback: Vec2| {+ let len = v.hypot();+ if len > 1e-12 {+ v / len+ } else {+ let len = fallback.hypot();+ if len > 1e-12 { fallback / len } else { Vec2::new(1.0, 0.0) }+ }+ };+ let t0 = unit_or(tans[0], run[1] - run[0]);+ let (pts, t0, t1) = if cyclic {+ // Fit the seam too: the fit starts and arrives with the same tangent, so closing the+ // contour adds no kink.+ let mut pts = Vec::with_capacity(n + 1);+ pts.extend_from_slice(run);+ pts.push(run[0]);+ (pts, t0, t0)+ } else {+ (run.to_vec(), t0, unit_or(tans[n - 1], run[n - 1] - run[n - 2]))+ };+ // Fit tighter than the flattening tolerance: the fit's error is the whole outline's error,+ // and a least-squares fit may sit on one side of the sampled edge, which would otherwise+ // shift a profile's area visibly.+ let cubics = fit_cubics(&pts, t0, t1, tol * 0.1);+ if cubics.is_empty() {+ out.line_to(run[n - 1]);+ return;+ }+ for c in cubics {+ out.curve_to(c.p1, c.p2, c.p3);+ }+}++/// Are the run's points within the flattening tolerance of its chord?+fn is_straight(run: &[Point], tol: f64) -> bool {+ let (a, b) = (run[0], run[run.len() - 1]);+ let d = b - a;+ let l = d.hypot();+ if l <= 1e-12 {+ return false;+ }+ run.iter().all(|p| (d.cross(*p - a) / l).abs() <= tol.max(1e-6) * 0.25)+}+ #[cfg(test)] mod tests { use super::*;@@ -317,10 +770,12 @@ mod tests { assert!((area(&width_outline(&line(), 10.0, &p, &capped(LineCap::Square), 0.01)) - 1100.0).abs() < 1e-6); } + /// The lens eases up to full width and back down (a parabolic bump averaging two thirds of+ /// the width); a one-sided profile keeps its side at zero and stays on the other. #[test]- fn lens_profile_is_a_diamond_and_one_sided_profiles_stay_on_their_side() {+ fn lens_profile_is_a_smooth_bump_and_one_sided_profiles_stay_on_their_side() { let a = area(&width_outline(&line(), 10.0, &WidthProfile::lens(), &capped(LineCap::Butt), 0.01));- assert!((a - 500.0).abs() < 1e-6, "{a}");+ assert!((a - 2000.0 / 3.0).abs() < 0.1, "{a}"); let one = WidthProfile { points: vec![(0.0, 1.0, 0.0), (1.0, 1.0, 0.0)] }; let o = width_outline(&line(), 10.0, &one, &capped(LineCap::Butt), 0.01); assert!((area(&o) - 500.0).abs() < 1e-6);@@ -344,6 +799,105 @@ mod tests { assert!(a.is_finite() && (a - 3000.0).abs() < 150.0, "{a}"); } + #[test]+ fn a_closed_path_steps_where_its_profile_ends_differ() {+ let mut sq = BezPath::new();+ sq.move_to((0.0, 0.0));+ sq.line_to((100.0, 0.0));+ sq.line_to((100.0, 100.0));+ sq.line_to((0.0, 100.0));+ sq.close_path();+ // 5 pt at the seam's start, 10 pt at its end: the ring must step between them, not+ // stretch the last width point round the corner.+ let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 2.0, 2.0)] };+ let o = width_outline(&sq, 10.0, &p, &capped(LineCap::Butt), 0.01);+ let at = |p: Point, x: f64, y: f64| (p.x - x).abs() < 1e-9 && (p.y - y).abs() < 1e-9;+ let step = o.elements().windows(2).any(|w| match (w[0], w[1]) {+ (PathEl::MoveTo(a), PathEl::LineTo(b)) | (PathEl::LineTo(a), PathEl::LineTo(b)) => {+ at(a, -10.0, -10.0) && at(b, -5.0, -5.0) || at(a, -5.0, -5.0) && at(b, -10.0, -10.0)+ }+ _ => false,+ });+ assert!(step, "{o:?}");+ }++ #[test]+ fn added_samples_follow_the_curve_not_the_flattened_chord() {+ // A cubic with a tight S: its chords are far from its tangents. A sample inserted inside a+ // chord must take the curve's direction there; the chord's direction is what made a wide+ // profile scallop at every flatten vertex.+ let mut b = BezPath::new();+ b.move_to((0.0, 0.0));+ b.curve_to((0.0, 120.0), (120.0, -120.0), (120.0, 0.0));+ let segs = segments(b.elements());+ let flat = flatten(&segs, false, 2.0);+ assert!(flat.pts.len() >= 3);+ let mut marks = vec![];+ let mut acc = 0.0;+ for i in 0..flat.pts.len() - 1 {+ let len = flat.pts[i].distance(flat.pts[i + 1]);+ marks.push(acc + len / 2.0);+ acc += len;+ }+ let (all, _, dirs) = split_at(&flat, false, &marks, &segs);+ assert!(all.len() > flat.pts.len());+ let seg = segs[0];+ for (p, d) in all.iter().zip(&dirs) {+ let want = tangent(&seg, seg.nearest(*p, 1e-9).t);+ assert!(d.dot(want) > 0.999, "{d:?} vs {want:?} at {p:?}");+ }+ }++ #[test]+ fn a_wiggly_profile_on_a_curve_fits_without_kinks() {+ // A rapid width change turns the offset sharply; that is not a path corner, so the+ // outline must stay tangent-continuous through it (the old turn-angle test did not).+ let c = kurbo::Circle::new((0.0, 0.0), 50.0).to_path(1e-3);+ let p = WidthProfile {+ points: vec![(0.0, 1.0, 1.0), (0.15, 3.0, 0.4), (0.3, 0.2, 2.8), (0.5, 2.5, 0.3), (0.7, 0.4, 2.2), (0.85, 2.0, 0.5), (1.0, 1.0, 1.0)],+ };+ let o = width_outline(&c, 10.0, &p, &capped(LineCap::Butt), 0.01);+ let mut cursor = None;+ let mut prev: Option<Vec2> = None;+ let mut kinks = 0;+ let mut check = |a: Vec2, b: Vec2| {+ let (la, lb) = (a.hypot(), b.hypot());+ if la > 1e-9 && lb > 1e-9 && (a.dot(b) <= 0.0 || a.cross(b).abs() / (la * lb) > 1e-6) {+ kinks += 1;+ }+ };+ for el in o.elements() {+ match el {+ PathEl::MoveTo(p) => {+ cursor = Some(*p);+ prev = None;+ }+ PathEl::LineTo(p) => {+ if let Some(q) = cursor {+ let d = *p - q;+ if let Some(a) = prev {+ check(a, d);+ }+ prev = Some(d);+ }+ cursor = Some(*p);+ }+ PathEl::CurveTo(a, b, p) => {+ if let Some(q) = cursor {+ let d = if a.distance(q) > 1e-9 { *a - q } else { *b - q };+ if let Some(prev) = prev {+ check(prev, d);+ }+ prev = Some(if p.distance(*b) > 1e-9 { *p - *b } else { *p - *a });+ }+ cursor = Some(*p);+ }+ PathEl::QuadTo(_, _) | PathEl::ClosePath => {}+ }+ }+ assert_eq!(kinks, 0, "{o:?}");+ }+ #[test] fn closed_paths_make_a_ring() { let mut sq = BezPath::new();@@ -366,4 +920,108 @@ mod tests { let want = 2.0 * std::f64::consts::PI * 50.0 * 10.0; assert!((a - want).abs() / want < 0.01, "{a} vs {want}"); }++ #[test]+ fn a_uniform_circle_narrower_than_its_stroke_has_no_hole() {+ // Half-width 15 on a radius-5 circle: the inner offset crosses the centre. The constant+ // stroke still covers the centre, so the outline must not leave a hole there.+ let c = kurbo::Circle::new((0.0, 0.0), 5.0).to_path(1e-3);+ let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)] };+ let o = width_outline(&c, 30.0, &p, &capped(LineCap::Butt), 0.01);+ assert!(o.contains(Point::new(0.0, 0.0)), "{o:?}");+ }++ #[test]+ fn a_quick_width_change_does_not_overshoot_its_samples() {+ // Width falls to a point and comes back, unevenly on either side: the fitted edge must not+ // dip past the point (that crossed the other edge and left a scalloped neck).+ let mut run = vec![Point::new(0.0, 0.0), Point::new(10.0, -1.0), Point::new(20.0, -0.3)];+ let (mut a, mut b) = (BezPath::new(), BezPath::new());+ a.move_to(run[0]);+ b.move_to(run[0]);+ smooth_run(&mut a, &run, false, 0.0);+ // Reverse the same points: the fit must stay inside the V from either direction too.+ run.reverse();+ smooth_run(&mut b, &run, false, 0.0);+ for path in [a, b] {+ let mut start = Point::ZERO;+ for el in path.elements() {+ match el {+ PathEl::MoveTo(p) => start = *p,+ PathEl::CurveTo(c1, c2, p) => {+ for c in [c1, c2] {+ assert!(c.y >= -1.0 - 1e-9, "{c:?} in {path:?}");+ assert!(c.y <= start.y.max(p.y) + 1e-9, "{c:?} in {path:?}");+ }+ start = *p;+ }+ _ => {}+ }+ }+ }+ }++ #[test]+ fn added_samples_stay_on_their_flattened_branch() {+ // This cubic loops back near itself. At a coarse tolerance a chord midpoint can be closer+ // to the other branch; a full-segment nearest would then take that branch's tangent and+ // spike the offset. Each inserted sample must use the parameter range of its own piece.+ let mut b = BezPath::new();+ b.move_to((0.0, 0.0));+ b.curve_to((150.0, 100.0), (-50.0, 100.0), (100.0, 0.0));+ let segs = segments(b.elements());+ let seg = segs[0];+ let flat = flatten(&segs, false, 2.0);+ let mut acc = 0.0;+ let mut divergent = 0;+ for i in 0..flat.pts.len() - 1 {+ let len = flat.pts[i].distance(flat.pts[i + 1]);+ if len <= 1e-12 {+ continue;+ }+ let (t0, t1) = flat.param[i];+ let sub = seg.subsegment(t0..t1);+ for k in 1..16 {+ let (out, _, dirs) = split_at(&flat, false, &[acc + len * k as f64 / 16.0], &segs);+ assert!(out.len() >= i + 2, "no sample inserted in piece {i}");+ let p = out[i + 1];+ let want = tangent(&seg, t0 + (t1 - t0) * sub.nearest(p, 1e-9).t);+ assert!(dirs[i + 1].dot(want) > 0.999, "piece {i}, k {k}: {:?} vs {want:?}", dirs[i + 1]);+ let full = tangent(&seg, seg.nearest(p, 1e-9).t);+ if full.dot(want) < 0.9 {+ divergent += 1;+ }+ }+ acc += len;+ }+ assert!(divergent > 0, "the fixture did not cross the other branch");+ }++ #[test]+ fn a_coarse_wide_circle_keeps_its_offset() {+ // A wide stroke flattened coarsely: offsetting each flattened segment by its miter+ // (`w / cos(θ/2)`) scalloped the circle outward at every sample. Smooth points follow the+ // curve's normal instead, so the ring is the annulus between radii 10 and 30.+ let c = kurbo::Circle::new((0.0, 0.0), 20.0).to_path(0.5);+ let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)] };+ let a = area(&width_outline(&c, 20.0, &p, &capped(LineCap::Butt), 0.5));+ let want = std::f64::consts::PI * (30.0 * 30.0 - 10.0 * 10.0);+ assert!((a - want).abs() / want < 0.01, "{a} vs {want}");+ }++ #[test]+ fn profiled_outlines_stay_compact() {+ // A smooth profile is fitted with cubics, so it must not turn every profile sample into+ // exported path data. Compare it with the same curved path's uniform outline.+ let circle = kurbo::Circle::new((0.0, 0.0), 5.0).to_path(0.01);+ let count = |points| {+ let p = WidthProfile { points };+ width_outline(&circle, 5.0, &p, &capped(LineCap::Butt), 0.01).elements().len()+ };+ let uniform = count(vec![(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)]);+ let lens = count(WidthProfile::lens().points);+ let wave = count(vec![(0.0, 0.3, 0.3), (0.25, 1.0, 1.0), (0.5, 0.3, 0.3), (0.75, 1.0, 1.0), (1.0, 0.3, 0.3)]);+ assert!(lens <= uniform * 3 / 2, "lens {lens} vs uniform {uniform}");+ assert!(wave <= uniform * 3 / 2, "wave {wave} vs uniform {uniform}");+ } }@@ -72,11 +72,11 @@ fn arrowheads_are_part_of_the_outline() { } #[test]-fn a_lens_profile_outlines_to_half_the_rectangle() {+fn a_lens_profile_outlines_to_two_thirds_of_the_rectangle() { let mut s = session(); line(&mut s, json!({"weight": 10, "profile": "lens"})); let n = outline(&mut s);- assert!(near(area(&n), 0.5 * 10.0 * 100.0, 2.0), "{}", area(&n));+ assert!(near(area(&n), 2.0 / 3.0 * 10.0 * 100.0, 2.0), "{}", area(&n)); } #[test]@@ -2,6 +2,7 @@ //! Adjoining Width Points and the render of a step. use serde_json::json;+use vectorcraft_doc::WidthProfile; use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; use crate::*;@@ -216,16 +217,27 @@ fn new_width_point_without_adjoining_preserves_neighbours() { #[test] fn new_width_point_adjust_adjoining_uses_sampled_widths() {+ let base = [(0.0, 9.0, 9.0), (0.25, 1.0, 0.0), (0.75, 3.0, 0.0), (1.0, 7.0, 7.0)]; for indexed in [false, true] { let (mut s, id) = line_session();- s.execute("stroke.widthProfile.set", &json!({"ids": [id.0], "points": [[0, 9, 9], [0.25, 1, 0], [0.75, 3, 0], [1, 7, 7]]})).unwrap();- // At t=0.5 the old sides are 10pt and 0pt. Indexed editing of that sampled- // point is the existing convention: scale the nonzero side, add from zero.+ s.execute("stroke.widthProfile.set", &json!({"ids": [id.0], "points": base})).unwrap();+ // At t=0.5 the curve's sides are what a new point starts from (an indexed edit starts from+ // the point it made there: 10pt and 0pt, half the 10pt stroke's 5pt).+ let old = if indexed { (2.0, 0.0) } else { WidthProfile { points: base.to_vec() }.at(0.5) }; let index = if indexed { Some(set(&mut s, json!({"id": id.0, "t": 0.5, "left": 10, "right": 0}))) } else { None }; set(&mut s, json!({"id": id.0, "index": index, "t": 0.5, "left": 20, "right": 5, "adjustAdjoining": true}));+ // Scale the nonzero side, add from zero (as Adjust Adjoining Width Points does).+ let scale = |v: f64, o: f64, n: f64| if o > 1e-9 { v * n / o } else { v + n - o };+ let (nl, nr) = (4.0, 1.0); assert_eq!( points(&s, id),- vec![(0.0, 9.0, 9.0), (0.25, 2.0, 1.0), (0.5, 4.0, 1.0), (0.75, 6.0, 1.0), (1.0, 7.0, 7.0)],+ vec![+ (0.0, 9.0, 9.0),+ (0.25, scale(1.0, old.0, nl), scale(0.0, old.1, nr)),+ (0.5, nl, nr),+ (0.75, scale(3.0, old.0, nl), scale(0.0, old.1, nr)),+ (1.0, 7.0, 7.0),+ ], "only nearest neighbours change, using the sampled sides; indexed={indexed}" ); }@@ -27,7 +27,7 @@ pub(crate) fn end_tangent(c: &CubicBez) -> Vec2 { /// /// `t0` is the unit tangent leaving `pts[0]`; `t1` is the unit tangent arriving at the last point /// (forward direction). Consecutive output cubics are G1 continuous.-pub(crate) fn fit_cubics(pts: &[Point], t0: Vec2, t1: Vec2, tol: f64) -> Vec<CubicBez> {+pub fn fit_cubics(pts: &[Point], t0: Vec2, t1: Vec2, tol: f64) -> Vec<CubicBez> { let mut out = Vec::new(); let pts = dedup(pts); if pts.len() < 2 {@@ -23,6 +23,7 @@ pub use edit::{ AverageAxis, SIMPLIFY_LEVEL, SimplifiedPart, SimplifyOptions, add_anchor_points, auto_simplify_level, average, join, remove_anchor, remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth, split_into_grid, };+pub use fit::fit_cubics; pub use offset::{Cap, Join, offset_path, outline_stroke, stroke_region}; pub use pathfinder::{FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions}; pub use planar::{@@ -105,8 +105,12 @@ impl Renderer { } ctx.set_transform(f.view * xf); let closed = effects::stroke::is_closed(bp);- // Keep hairlines visible when zoomed far out (at least ~1 device pixel).- let width = effects::stroke::aligned_width(st, closed).max(f.px * 0.5 / xf.determinant().abs().sqrt().max(1e-9));+ // Keep hairlines visible when zoomed far out (at least ~1 device pixel). A width profile+ // sets its own widths: inflating the base for a hairline would scale every width point+ // with it, so a 1 pt stroke with a 100x point became a 100 px wide hairline when zoomed+ // out (and shrank back when its outline was expanded, which uses the true width).+ let base = effects::stroke::aligned_width(st, closed);+ let width = if st.profile.is_some() { base } else { base.max(f.px * 0.5 / xf.determinant().abs().sqrt().max(1e-9)) }; let inside = st.align == StrokeAlign::Inside && closed; if inside { ctx.set_fill_rule(fill_rule(rule));@@ -247,6 +247,8 @@ fn new_width_point_profile_and_compound_target() { assert!(d.fields.get("index").is_none_or(Value::is_null)); let actual_t = d.f64("t", -1.0); assert!((actual_t - 0.25).abs() < 1e-6, "compound={compound} pointer={quarter:?} actual_t={actual_t} want=0.25");+ // The two-point profile is linear: at a quarter its sides are 1.25 and 0.75 of+ // 1..2 and 0.5..1.5, on a 10pt stroke (5pt half). assert!((d.f64("side1", 0.0) - 6.25).abs() < 1e-6); assert!((d.f64("side2", 0.0) - 3.75).abs() < 1e-6); assert!(!d.bool("linked"));@@ -855,7 +855,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Gradients:** lossless, validated gradient params; gradients follow rotate, reflect, shear, non-uniform scale and distortions; the Gradient tool edits the fill or stroke of the active proxy, type included; an interactive on-canvas annotator (move, length/angle, rotate, add/move/delete/duplicate stops, midpoints, a stop popover, Delete and arrow keys). The Gradient panel has the Fill/Stroke proxy, a gradient-swatch dropdown with Save to Swatches, midpoint locations, Alt-drag to copy or swap stops, swatch drops on the ramp and a stop eyedropper; copied appearances and graphic styles place gradients on each target's own bounds; gradient handles snap and honour Constrain Angle. Gradient stops stay linked to global and spot swatches. Freeform gradients (points and lines) are edited on the canvas; radial gradients have an extent ellipse, an aspect handle and an off-centre focal point (SVG `fx`/`fy`, PDF two-point radials). A stroke's gradient runs within, along or across it. Object ▸ Expand turns gradients into N objects or a gradient mesh. With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. Points in different models mix in display RGB, and a CMYK document stores the result as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own.- - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty more arrowheads, and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance.+ - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty more arrowheads, and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with the one-sided three-point PCHIP slope at the profile's ends and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined where the width bends, and leaning on dense path flattening) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt at the default 0.01 pt) rather than one cubic per flatten step, so exports stay close to a uniform stroke's path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random or Pressure with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values or Pressure from the first at the lightest pressure to the second at the heaviest; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Still to come: the Art brush's Overlap, auto-generated Pattern brush corners, new tile art picked in Pattern Brush Options, Stylus Wheel, Tilt, Bearing and Rotation, and pen pressure on macOS. Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method (<https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html>) and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value.@@ -1186,6 +1186,7 @@ applies to fills). Tests: `color::gradient::tests` (perceptual midpoint, expansi | 2026-10-22 | minor | G2: Effect › Sketch › Conté Crayon (Foreground Level, Background Level, Texture, Scaling, Relief, Light Direction, Invert; a black crayon in the dark areas and a white one in the light areas on textured mid-grey paper; ranges and defaults unverified VectorCraft choices); measured Photoshop-style filters 57/57, the Effect Gallery remains (4–6 h); area score unchanged (49%, estimated). | | 2026-10-22 | minor | File formats: Affinity import gains master pages, tables, paragraph formats, text scale, shadows, glows, outlines (also on stroked shapes), overlays, underlines, strikethrough and editable embedded documents, strokes styled None left out, CMYK pixel layers through the document's CMYK profile, text placed as Affinity places it (AF.5, from storytold/designcraft#291); synthetic, corpus and local-thumbnail tests; score and hours unchanged (estimated). Hostile files stay bounded: one budget for the whole read (layers, pixels, characters, table cells, embedded documents included), a work budget for overlays, capped master page copies, objects past `MAX_COORD` left out; the import fuzzer and limit tests cover tables, paragraphs, effects, overlays, master pages, CMYK pixels and embedded documents. | | 2026-10-22 | minor | Recolor Artwork Edit chips scroll within the available screen height (#3416); small palettes retain their tab height; scores and estimates unchanged. |+| 2026-10-21 | minor | Width-profile outlines offset samples added inside a flattened chord along the source curve's exact tangent, so a zoomed outline no longer jogs at flatten vertices; a regression test covers added samples. Scores and estimates unchanged. | | 2026-10-22 | minor | Artboard Options honors Scale Artwork with Artboard for preset, orientation and typed-size changes; both Fits keep artwork stationary; scores and estimates unchanged. | | 2026-10-22 | minor | Colour and gradients: Illustrator 30.0's gradient Method, Classic or Perceptual (Gradient panel menu, canvas and raster exports, SVG/PDF as images at the raster effects resolution, native file); score and hours unchanged (estimated). | | 2026-10-22 | minor | G2: the Effect Gallery shipped (#2883): Effect › Effect Gallery… browses the Artistic, Brush Strokes, Distort, Sketch, Stylize and Texture filters, edits each filter's settings, builds an ordered stack (add, reorder, hide, remove) with a live canvas preview, and OK applies it as separate appearance effects in one undo step; remaining: filter thumbnails and a preview area inside the dialog; G2 estimate 4–6 → 1–2 h; Raster effects 82% → 85% (power-user view 49% → 52%), estimated, a modest move because the named missing dialog landed without thumbnails or an in-dialog preview. |@@ -1209,6 +1210,7 @@ applies to fills). Tests: `color::gradient::tests` (perceptual midpoint, expansi | 2026-10-21 | minor | Snap to Glyph (#3124) removed from View navigation missing lists and menu stubs; scores and hours unchanged at this rounding | | 2026-10-21 | minor | Type core: System Layout (Character panel menu, whole document, off by default) is done; scores and hours unchanged | | 2026-10-22 | minor | Ruby (ふりがな) for live text: `type.ruby` sets/removes a reading over a byte range, above or below (right of the column in vertical type), aligned, sized and overhanging or squeezed; saved natively, laid out with line growth, drawn on the canvas and in SVG/PDF (outlines where ruby is present); scores and hours unchanged |+| 2026-10-23 | minor | Width-profile outlines sample adaptively: two samples per profile segment, refined where the width bends, and only where the flattened path does not already sample the width. The sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt by default) instead of one cubic per flatten step. On the reviewer's 1,500-ellipse fixture (20–200 pt ellipses, 3–12 pt weights) the PDF falls to 3.59 MB and the SVG to 6.79 MB (reported main baselines 4.48 MB and 9.30 MB, about 0.80× and 0.73×), and `profiled_outlines_stay_compact` guards the path-element count. Scores and estimates unchanged. | | 2026-10-21 | minor | 3D: original Standard, Diffuse, Top Left and Right lighting presets; command access, effective-setting recognition and preview/history; scores and estimates unchanged | | 2026-10-21 | minor | Properties: one selected clip group has Edit Clipping Path and Edit Contents at the top of the panel (public doc cited) (G1). Scores and hours unchanged. | | 2026-10-21 | minor | Print: the Print dialog's Media list carries the Japanese papers — JIS B4 (257 × 364 mm), JIS B5 (182 × 257 mm) and JIS B6 next to the ISO B4/B5, which keep their ISO 216 sizes, plus はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判; the JSON id or the dialog label names a paper, any case and spacing. Print score and hours unchanged. |@@ -1222,6 +1224,7 @@ applies to fills). Tests: `color::gradient::tests` (perceptual midpoint, expansi | 2026-10-19 | minor | Plug-ins: parameters with labels, units, help, groups and conditions in their dialogs, `string` and `numberList` types, up to 256 per plug-in (G17); manifest and kittest dialog regressions. Scores and hours unchanged. | | 2026-10-19 | minor | Plug-ins: exporter plug-ins add write-only file formats to Export As and `document.export` (G17); engine, ABI and headless Export As regressions. Scores and hours unchanged. | | 2026-10-19 | minor | Libraries panel: the list fills the panel and scrolls (also while a drag nears its edges); items drag before or after others of their kind and into or out of groups, and groups drag by their headers (`library.moveItem` `before`/`after`, `library.moveGroup`). Scores and estimates unchanged. |+| 2026-10-19 | minor | Width profiles run as a smooth C1 curve between their points (a monotone cubic Hermite, Fritsch-Carlson) instead of straight lines, sampled along the path so the outline follows it on straight runs; steps between coincident points still step. Regression tests cover easing, monotonicity, locality and steps. Scores and estimates unchanged. | | 2026-10-19 | minor | Cache status-readout sample widths per UI, language, document unit and pixels per point; regressions check reuse across live frames and refresh after display-setting changes. Scores and estimates unchanged. | | 2026-10-19 | minor | Status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates. Contributor original-file acceptance confirmed; scores and estimates unchanged. | | 2026-10-19 | minor | Cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission. Regression coverage; scores and estimates unchanged. |