diff --git a/crates/doc/src/appearance/profile.rs b/crates/doc/src/appearance/profile.rs index e6f69e6670..4b0b59ce54 100644 --- a/crates/doc/src/appearance/profile.rs +++ b/crates/doc/src/appearance/profile.rs @@ -32,10 +32,9 @@ impl WidthProfile { /// 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 of a run use the one-sided PCHIP slope - /// from its first two secants, or the secant when it has only two points, so a two-point - /// profile stays a straight taper and the lens is a parabola. Two points at one `t` are still - /// a step: each run either side ends independently at it. + /// neighbours (their slopes depend on it). The ends of a run take the span's own slope, so a + /// two-point profile stays a straight taper. Two points at one `t` are still a step: each run + /// either side ends independently at it. pub fn at_points(p: &[(f64, f64, f64)], t: f64) -> (f64, f64) { if p.is_empty() { return (1.0, 1.0); @@ -263,27 +262,12 @@ impl AngleProfile { /// How close two width points' positions are to make a step ([`WidthProfile::around`]). const STEP: f64 = 1e-7; -/// The one-sided three-point PCHIP slope at the start of a run, from the first two secants. -/// A sign change caps the slope, and a slope that turns back on the first secant is flattened. -/// Runs of only two points use their secant instead (see [`tangent`]). -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 one side (`v` reads it from a point) of width profile `p` at its point `j`, in /// width per unit of position: Fritsch–Carlson's choice for a monotone cubic curve. It is 0 where /// the point is wider or narrower than both neighbours, and the weighted harmonic mean of the /// slopes of the spans on either side elsewhere (never more than three times either, so no span -/// overshoots its points). The ends of a run take the one-sided three-point PCHIP slope, or their -/// secant when the run has only two points; a step ends the run on each side, so the points either -/// side of it do not see across it. +/// overshoots its points). The ends of a run take their secant; a step ends the run on each +/// side, so the points either side of it do not see across it. fn tangent(p: &[(f64, f64, f64)], j: usize, v: fn(&(f64, f64, f64)) -> f64) -> f64 { let Some(q) = p.get(j) else { return 0.0 }; let before = j.checked_sub(1).and_then(|k| p.get(k)).filter(|a| q.0 - a.0 > STEP); @@ -298,18 +282,8 @@ fn tangent(p: &[(f64, f64, f64)], j: usize, v: fn(&(f64, f64, f64)) -> f64) -> f let (h0, h1) = (q.0 - a.0, b.0 - q.0); 3.0 * (h0 + h1) / ((2.0 * h1 + h0) / d0 + (h1 + 2.0 * h0) / d1) } - // The end of a run: its previous two points set a one-sided three-point slope, or its - // secant when the run has only two points (the point before `a` is on the other side of a - // step, or does not exist). - (Some(a), None) => { - let Some(prev) = j.checked_sub(2).and_then(|k| p.get(k)).filter(|z| a.0 - z.0 > STEP) else { return slope(a, q) }; - end_slope(q.0 - a.0, a.0 - prev.0, slope(a, q), slope(prev, a)) - } - // The start of a run, symmetrically. - (None, Some(b)) => { - let Some(next) = p.get(j + 2).filter(|z| z.0 - b.0 > STEP) else { return slope(q, b) }; - end_slope(b.0 - q.0, next.0 - b.0, slope(q, b), slope(b, next)) - } + (Some(a), None) => slope(a, q), + (None, Some(b)) => slope(q, b), (None, None) => 0.0, } } @@ -464,12 +438,12 @@ mod tests { #[test] fn widths_run_smoothly_through_width_points() { // A swell in the middle: flat at its widest, and a quarter of the way along above the - // straight ramp from 1 to 3 (2) because the end eases out of the first point. + // straight ramp from 1 to 3 (2). let swell = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 3.0, 2.0), (1.0, 1.0, 1.0)] }; let (before, after) = slopes(&swell, 0.5); assert!(before.abs() < 1e-4 && after.abs() < 1e-4, "{before} {after}"); let (l, r) = swell.at(0.25); - assert!((l - 2.5).abs() < 1e-12 && (r - 1.75).abs() < 1e-12, "{l} {r}"); + assert!((l - 2.25).abs() < 1e-12 && (r - 1.625).abs() < 1e-12, "{l} {r}"); // Rising on both sides of a point: the slope is the same either side of it. let rise = WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.3, 1.0, 1.0), (1.0, 4.0, 4.0)] }; let (before, after) = slopes(&rise, 0.3); diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs index ab0ba559f0..c91348d57f 100644 --- a/crates/doc/src/appearance/tests.rs +++ b/crates/doc/src/appearance/tests.rs @@ -221,9 +221,9 @@ fn strokes_without_pressure_round_trip_unchanged() { fn profile_interp() { let p = WidthProfile::lens(); assert_eq!(p.at(0.5), (1.0, 1.0)); - // The lens is a parabola between its ends, so a quarter of the way along is 0.75: above the - // 0.5 a straight taper would give. - assert_eq!(p.at(0.25), (0.75, 0.75)); + // Half way up the lens the width curves above the straight ramp (0.5), flattening into its + // widest point. + assert_eq!(p.at(0.25), (0.625, 0.625)); assert_eq!(p.at(2.0), (0.0, 0.0)); } @@ -259,13 +259,13 @@ fn profile_two_point_runs_are_linear() { } } -/// 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. +/// The lens swells above a straight line between its points: a quarter of the way along it is +/// 0.625, easing flat into its widest point rather than rising at a constant rate. #[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); + assert!((p.at(0.25).0 - 0.625).abs() < 1e-12); + assert!((p.at(0.75).0 - 0.625).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); diff --git a/crates/effects/src/stroke/tests.rs b/crates/effects/src/stroke/tests.rs index 1c79fd4805..aa4ea8dc9f 100644 --- a/crates/effects/src/stroke/tests.rs +++ b/crates/effects/src/stroke/tests.rs @@ -232,14 +232,16 @@ 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); - // The lens is a parabola between its ends: 2/3 of the full-width band. - 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 lens swells on a cubic, flat at the middle: 7/12 of the full-width band (#5714). + assert!(near(lens.area().abs(), 1000.0 * 7.0 / 12.0, 0.05)); + // Each dash takes its widths from where it sits along the lens (0 → 1 → 0). Half of the lens + // rises as w(u) = u + u² − u³ (u from 0 to 1 across that half): the dash over 0..25 covers + // its first half, ∫₀^½ w = 29/192, the one over 50..75 the wider other half, 83/192. 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(), 1000.0 / 3.0, 0.1)); + assert!(near(line_outline(&l, &st, 10.0, 1e-3).area().abs(), 500.0 * (29.0 + 83.0) / 192.0, 0.05)); assert!(line_outline(&BezPath::new(), &st, 10.0, 1e-3).elements().is_empty()); } diff --git a/crates/effects/src/stroke/tests_fit.rs b/crates/effects/src/stroke/tests_fit.rs index cc69606aee..f7fecb9abc 100644 --- a/crates/effects/src/stroke/tests_fit.rs +++ b/crates/effects/src/stroke/tests_fit.rs @@ -169,10 +169,9 @@ 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, - // where the smooth profile is thinner than a straight ramp (a parabola's first tenth). + // The dash over 40..50 is near the lens's widest point; the one over 0..10 near its tip. 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, 0.8)) && !o.contains(Point::new(5.0, 1.2)), "first dash is thin"); + 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(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| { @@ -181,7 +180,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.4)) && !o.contains(Point::new(10.0, 2.0))); + 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))); } /// An L whose corner turns 90° at (100, 0), or a sharp V turning back at (100, 0). diff --git a/crates/effects/src/stroke/tests_gradient.rs b/crates/effects/src/stroke/tests_gradient.rs index 784c84d1db..55aeda8d7f 100644 --- a/crates/effects/src/stroke/tests_gradient.rs +++ b/crates/effects/src/stroke/tests_gradient.rs @@ -138,8 +138,9 @@ 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 three quarters as wide: its top edge is 3.75 up. - assert!(param(&sl, Point::new(25.0, -3.6)).unwrap() < 0.05); + // A quarter of the way along, the lens is 0.625 as wide (its curve, #5714): its top edge is + // 3.125 up. + assert!(param(&sl, Point::new(25.0, -3.0)).unwrap() < 0.05); assert!((param(&sl, Point::new(50.0, -2.5)).unwrap() - 0.25).abs() < 0.02); } diff --git a/crates/effects/src/stroke/width.rs b/crates/effects/src/stroke/width.rs index 0b307cc6b5..f52b82ba9f 100644 --- a/crates/effects/src/stroke/width.rs +++ b/crates/effects/src/stroke/width.rs @@ -53,7 +53,7 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil kept.push(!(a.x.max(b.x) < near.x0 || a.x.min(b.x) > near.x1 || a.y.max(b.y) < near.y0 || a.y.min(b.y) > near.y1)); } if kept.iter().all(|v| *v) { - ctx.subpath(&mut out, &flat, &segs, closed, (0.0, 1.0), count as f64); + ctx.subpath(&mut out, &flat, &segs, closed, (0.0, 1.0)); continue; } cut = true; @@ -78,14 +78,14 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil } else if let Some(part) = run.take() && part.pts.len() > 1 { - ctx.subpath(&mut out, &part, &segs, false, (from, walked / total), count as f64); + ctx.subpath(&mut out, &part, &segs, false, (from, walked / total)); } walked += lengths[i]; } if let Some(part) = run && part.pts.len() > 1 { - ctx.subpath(&mut out, &part, &segs, false, (from, walked / total), count as f64); + ctx.subpath(&mut out, &part, &segs, false, (from, walked / total)); } } cut.then_some(out) @@ -102,8 +102,7 @@ pub(super) fn outline_spans(bp: &BezPath, spans: &[(f64, f64)], width: f64, prof let flat = flatten(&segs, closed, ctx.tol); if flat.pts.len() > 1 { let span = spans.get(i).copied().unwrap_or((0.0, 1.0)); - let pieces = if closed { flat.pts.len() } else { flat.pts.len() - 1 }.max(1); - ctx.subpath(&mut out, &flat, &segs, closed, span, pieces as f64 / (span.1 - span.0)); + ctx.subpath(&mut out, &flat, &segs, closed, span); } } out @@ -215,25 +214,17 @@ pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> Flat { /// 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), - density: f64, -) -> (Vec, Vec, Vec) { - // 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. +/// share one sample). `span` maps the subpath onto the profile (see [`outline_spans`]); `bend` is +/// the gap (in width factor) the straight line between samples may leave the curve, the outline +/// tolerance turned into the profile's units (see [`adaptive_samples`]). +fn densify(flat: &Flat, segs: &[PathSeg], closed: bool, profile: &WidthProfile, span: (f64, f64), bend: f64) -> (Vec, Vec, Vec) { + // Start at a midpoint per profile segment: the fit through those keeps a gentle taper smooth + // with little path data. A stronger bend measures itself finer (see `adaptive_samples`): the + // straight line between samples must stay within the outline tolerance, as a plain stroke's + // own flattening does, so the profile's shape does not drift from the one a uniform profile + // draws. const SAMPLES: usize = 2; - const MAX_SAMPLES: usize = 8; - // The gap (in width factor) the straight line between two samples may leave: small enough - // that a sharp peak like the lens' needs one more piece, large enough that a long taper's - // gentle bend does not. - const BEND: f64 = 0.05; + const MAX_SAMPLES: usize = 64; let total = length(&flat.pts, closed); let range = span.1 - span.0; if total <= 1e-12 || range <= 1e-12 { @@ -250,6 +241,15 @@ fn densify( // 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 mut marks = Vec::with_capacity(ts.len() * SAMPLES); + // Where each flattened point falls on the profile, so a segment can see the points inside it. + let mut at = Vec::with_capacity(flat.pts.len()); + let mut walked = 0.0; + for (i, p) in flat.pts.iter().enumerate() { + at.push(span.0 + walked / total * range); + if let Some(next) = flat.pts.get(i + 1) { + walked += p.distance(*next); + } + } for w in ts.windows(2) { let (a, b) = (w[0], w[1]); let samples = if constant { @@ -259,12 +259,11 @@ fn densify( // 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); - // How many of the flattened path's points already fall in this profile segment. - // `density` is measured on the whole subpath, not on this piece, so outlining only - // the piece near the view picks the same samples as outlining the whole subpath. - let existing = (b - a) * density; - if existing >= want as f64 { 1 } else { want } + let want = adaptive_samples(profile, start, end, SAMPLES, MAX_SAMPLES, bend).min(cap); + // Judge the flattened points inside this profile segment, not the subpath's overall + // density: a long straight run beside a densely flattened curve has few points of its + // own, and only they can tell whether the run already follows the width curve. + if sampled_enough(profile, &at, a, b, bend) { 1 } else { want } }; for k in 0..samples { marks.push(a + (b - a) * k as f64 / samples as f64); @@ -277,22 +276,17 @@ fn densify( 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. +/// How many pieces one profile segment needs so the outline follows the width curve to within +/// `bend` (a gap in width factor; the caller turns the outline tolerance into it). A straight +/// taper is already straight; a visible bend gets progressively more samples, up to `max`. fn adaptive_samples(profile: &WidthProfile, t0: f64, t1: f64, base: usize, max: usize, bend: f64) -> usize { let mut samples = base.max(1); while samples < max { // One probe in the middle of each piece: how far the curve leaves the straight line // between the piece's ends. The more pieces, the closer the line follows the curve, so // the loop only stops when the pieces it has are fine enough (or at `max`). - let mut dev = 0.0_f64; - for k in 0..samples { - let (a, b) = (k as f64 / samples as f64, (k + 1) as f64 / samples as f64); - let (la, ra) = profile.at(t0 + (t1 - t0) * a); - let (lb, rb) = profile.at(t0 + (t1 - t0) * b); - let (lm, rm) = profile.at(t0 + (t1 - t0) * (a + b) / 2.0); - dev = dev.max((lm - (la + lb) / 2.0).abs()).max((rm - (ra + rb) / 2.0).abs()); - } + let step = (t1 - t0) / samples as f64; + let dev = (0..samples).fold(0.0_f64, |dev, k| dev.max(deviation(profile, t0 + step * k as f64, t0 + step * (k + 1) as f64))); if dev <= bend { break; } @@ -301,6 +295,46 @@ fn adaptive_samples(profile: &WidthProfile, t0: f64, t1: f64, base: usize, max: samples } +/// How far the width curve leaves the straight line between two profile positions: the widest of +/// its two sides at the span's middle. +fn deviation(profile: &WidthProfile, t0: f64, t1: f64) -> f64 { + let (la, ra) = profile.at(t0); + let (lb, rb) = profile.at(t1); + let (lm, rm) = profile.at((t0 + t1) / 2.0); + (lm - (la + lb) / 2.0).abs().max((rm - (ra + rb) / 2.0).abs()) +} + +/// Whether the flattened points inside profile segment `[a, b]` already follow the width curve to +/// within `bend`, so the segment needs no samples of its own. `at` holds each flattened point's +/// profile position. The subpath's overall point density cannot answer this: a long straight run +/// beside a densely flattened curve has few points of its own, and its width must still follow the +/// curve rather than run straight between its ends. +fn sampled_enough(profile: &WidthProfile, at: &[f64], a: f64, b: f64, bend: f64) -> bool { + let first = at.partition_point(|p| *p < a); + let last = at.partition_point(|p| *p <= b); + // A segment whose flattened points only sit on its boundaries is a straight run: one probe in + // the middle cannot see a bend that matches the chord there but leaves it nearer the ends. Let + // `adaptive_samples` measure it. + if !at[first..last].iter().any(|&p| p > a + 1e-9 && p < b - 1e-9) { + return false; + } + // A dash crossing a closed seam has a window past 1 (`[1.0, 1.5]`), where the widths wrap; + // probe the positions `densify` measured its samples at. `at` stays unwrapped for selection. + let shift = a - a.rem_euclid(1.0); + let mut from = a - shift; + for &p in &at[first..last] { + let p = p - shift; + if p <= from { + continue; + } + if deviation(profile, from, p) > bend { + return false; + } + from = p; + } + deviation(profile, from, b - shift) <= bend +} + /// Length of a flattened subpath (see [`flatten`]). pub(super) fn length(pts: &[Point], closed: bool) -> f64 { let n = pts.len(); @@ -419,8 +453,11 @@ impl<'a> Ctx<'a> { } } - fn subpath(&self, out: &mut BezPath, flat: &Flat, segs: &[PathSeg], closed: bool, span: (f64, f64), density: f64) { - let (pts, corner, dirs) = densify(flat, segs, closed, self.profile, span, density); + fn subpath(&self, out: &mut BezPath, flat: &Flat, segs: &[PathSeg], closed: bool, span: (f64, f64)) { + // The flattened edge and its cubic fit are already within `tol`, so a width bend that + // strays further would show as a dent or a bulge that the plain stroke does not have. + let bend = self.tol.max(1e-9) / self.half.max(1e-12); + let (pts, corner, dirs) = densify(flat, segs, closed, self.profile, span, bend); let n = pts.len(); let seg_count = if closed { n } else { n - 1 }; let seg_dir: Vec = (0..seg_count).map(|i| unit(pts[(i + 1) % n] - pts[i])).collect(); @@ -803,11 +840,11 @@ fn smooth_run(out: &mut BezPath, run: &[Point], cyclic: bool, tol: f64) { } 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. The points lie on the outline's own curve, so the fit follows - // their curve between them rather than the chords through them. - let cubics = fit_cubics_through(&pts, t0, t1, tol * 0.1); + // Fit to the flattening tolerance: the samples lie on the outline's own curve, so the fit + // follows that curve between them rather than the chords through them, and the outline is as + // close to the ideal offset as a plain stroke's flattened edge is. A tighter fit added many + // cubics along a strong width wave without a visible gain. + let cubics = fit_cubics_through(&pts, t0, t1, tol); if cubics.is_empty() { out.line_to(run[n - 1]); return; @@ -860,12 +897,15 @@ 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. + /// The lens eases up to full width and back down (a smooth bump covering seven twelfths of the + /// full width); a one-sided profile keeps its side at zero and stays on the other. #[test] 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 - 2000.0 / 3.0).abs() < 0.1, "{a}"); + // Within a couple of square points over the bump's 200 pt of edge: the sampled chords and + // the cubic fit each stay within the outline tolerance (0.01) of the curve, so about + // 200 × 0.01 of area either side is expected and invisible. + assert!((a - 1000.0 * 7.0 / 12.0).abs() < 2.0, "{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); @@ -1099,10 +1139,74 @@ mod tests { assert!((a - want).abs() / want < 0.01, "{a} vs {want}"); } + /// A long straight run beside a densely flattened curve still follows the profile across the + /// run: the subpath's overall point count must not stand in for the points the run itself has. + #[test] + fn a_long_run_beside_a_dense_curve_keeps_the_profiles_shape() { + // One 200 pt line whose second half is 128 collinear pieces: the same geometry as the + // two-segment line, with most of the flattened points on the second half. The lens peaks + // at the join, so a straight chord across either half would sit at 2.5 pt half way along + // it rather than the 3.125 the profile has there. + let mut dense = BezPath::new(); + dense.move_to((0.0, 0.0)); + for i in 1..=128 { + dense.line_to((100.0 + 100.0 * i as f64 / 128.0, 0.0)); + } + let mut sparse = BezPath::new(); + sparse.move_to((0.0, 0.0)); + sparse.line_to((200.0, 0.0)); + let p = WidthProfile::lens(); + let dense = width_outline(&dense, 10.0, &p, &capped(LineCap::Butt), 0.01); + let sparse = width_outline(&sparse, 10.0, &p, &capped(LineCap::Butt), 0.01); + // The extra collinear points may not change the outline. + let (a, b) = (area(&dense), area(&sparse)); + assert!((a - b).abs() < 2.0, "{a} vs {b}"); + assert!((b - 10.0 * 200.0 * 7.0 / 12.0).abs() < 2.0, "{b}"); + // ... and the edge at a quarter of the way along each half sits at the lens's width. + for x in [50.0, 150.0] { + assert!(dense.contains(Point::new(x, -3.0)), "{x}: {dense:?}"); + assert!(!dense.contains(Point::new(x, -3.4)), "{x}: no extra samples: {dense:?}"); + } + } + + /// A profile segment whose flattened points only sit on its boundaries is a straight run: the + /// sampler measures it, rather than accepting it on a midpoint that happens to match the chord. + #[test] + fn a_bend_that_matches_the_chords_midpoint_still_gets_samples() { + // Flat at 1, then a smooth rise to 2, with collinear vertices exactly on the rise's + // boundaries: through the rising segment the curve matches its chord at the middle and + // sits below it at a quarter of the way, so one midpoint probe would leave the edge + // 0.47 pt out at the quarter. + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.line_to((25.0, 0.0)); + b.line_to((75.0, 0.0)); + b.line_to((100.0, 0.0)); + let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.25, 1.0, 1.0), (0.75, 2.0, 2.0), (1.0, 2.0, 2.0)] }; + let o = width_outline(&b, 10.0, &p, &capped(LineCap::Butt), 0.01); + // At a quarter of the way through the rise the width is 1.15625, so that edge is 5.78 pt + // from the path; a chord from 1 to 2 would put it at 6.25. + assert!(!o.contains(Point::new(37.5, -6.0)), "{o:?}"); + assert!(o.contains(Point::new(37.5, -5.5)), "{o:?}"); + } + + /// A window past the seam of a closed path probes the widths it actually wraps to: the + /// flattened points of a dash tail sit before the seam. + #[test] + fn a_window_past_the_seam_measures_the_wrapped_widths() { + let profile = WidthProfile::lens(); + // A dash from 0.9 to 1.1 of the subpath, its flattened points ending at 1.1: `[1.0, 1.5]` + // is the wrapped half of the profile's first segment. + let at = [0.9, 0.95, 1.0, 1.05, 1.1]; + assert!(!sampled_enough(&profile, &at, 1.0, 1.5, 0.002), "the wrapped width bends"); + } + #[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. + // exported path data. The wave genuinely bends four times around this small circle, so it + // takes more cubics than the plain annulus; a fit to every sample would take several times + // as many again. let circle = kurbo::Circle::new((0.0, 0.0), 5.0).to_path(0.01); let count = |points| { let p = WidthProfile { points }; @@ -1112,6 +1216,6 @@ mod tests { 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}"); + assert!(wave <= uniform * 3, "wave {wave} vs uniform {uniform}"); } } diff --git a/crates/engine/src/tests/outlinestroke.rs b/crates/engine/src/tests/outlinestroke.rs index 16b57a628c..494ac8dc52 100644 --- a/crates/engine/src/tests/outlinestroke.rs +++ b/crates/engine/src/tests/outlinestroke.rs @@ -73,13 +73,14 @@ fn arrowheads_are_part_of_the_outline() { assert_eq!(path_of(&n).subpaths.len(), 1, "line and head are one shape"); } -/// Outline Stroke of a Lens-profile line covers 2/3 of the full-width rectangle. +/// Outline Stroke of a Lens-profile line covers 7/12 of the full-width rectangle. #[test] -fn a_lens_profile_outlines_to_two_thirds_of_the_rectangle() { +fn a_lens_profile_outlines_to_seven_twelfths_of_the_rectangle() { let mut s = session(); line(&mut s, json!({"weight": 10, "profile": "lens"})); let n = outline(&mut s); - assert!(near(area(&n), 2.0 / 3.0 * 10.0 * 100.0, 2.0), "{}", area(&n)); + // Each half of the lens swells on a cubic, flat at the middle (#5714). + assert!(near(area(&n), 7.0 / 12.0 * 10.0 * 100.0, 2.0), "{}", area(&n)); } #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9cb03f12b3..e7037dc267 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2090,7 +2090,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur 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. In the Gradient tool's freeform Lines mode, moving the pointer out of the object and back ends the line being drawn, and the next click on the object starts a new line from the point it adds. The help page describes this way of starting another line segment in the same object ([Create freeform gradient in lines mode](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=262)). As VectorCraft's own rules, the line ends as soon as the pointer, with no button held, moves off the object's own art, its fill, stroke or glyphs (other art lying over the object still counts as inside), and Escape and a click off the art still end it as before (`xform::freeform::tests::leaving_the_object_ends_the_line`). - **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. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand 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-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), 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. + - **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-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), 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 each end's own span slope and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined until the line between samples stays within the outline tolerance, and reusing a segment's own flattened points only where they already follow the curve) 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 the flattening tolerance (0.01 pt) rather than one cubic per flatten step, so a profiled outline draws the same shape as a uniform one and exports stay close to its 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, Pressure, Tilt, Bearing or Rotation 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, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; 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, Overlap) 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. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on Windows and the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch to Fit Stroke Length and Stretch Between Guides art is, on top of the scale the path length gives it, so a 3 pt stroke draws the art three times as wide as a 1 pt stroke. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says Scale Proportionately keeps the art's proportions and does not say how the stroke weight applies; that rule is VectorCraft's own. Evidence: `tests::art_brush_proportional_grows_with_weight` (vectorcraft-brush). @@ -3438,7 +3438,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-10-23 | minor | Artboard Options: Show Center Mark and Show Cross Hairs (`artboard.setProps`/`artboard.new` `showCenterMark`, `showCrossHairs`) draw a center cross and lines from the middle of each side through the center on the canvas only, in one undo step; video safe areas, video rulers and the pixel aspect ratio remain missing; scores and estimates unchanged. | | 2026-10-23 | minor | Path operations: Simplify of part of a path: with anchors or segments of a path direct-selected, Object › Path › Simplify (slider, Auto-Simplify and dialog) refits only each run of selected segments between its end anchors; no longer listed as missing; evidence added; score and hours unchanged (estimated). | | 2026-10-23 | minor | Path operations: Simplify: Object › Path › Simplify opens its slider at the Auto-Simplify level for the selection, previewing that result, instead of at 1 pt; partial-path simplify remains missing; score and hours unchanged (estimated). | -| 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-23 | minor | Width-profile outlines sample adaptively: two samples per profile segment, refined until the line between samples stays within the outline tolerance, and only where the flattened path does not already sample the width. The sampled edges are fitted with G1 cubics within the flattening tolerance (0.01 pt by default) instead of one cubic per flatten step, and a profiled outline now covers the same area as before the smoothing (on a star with the Wave profile, 15597.7 pt² against 15595.4 pt², and the same on a Wave-profile line). 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-22 | minor | Drawing tools: a Pen, Anchor Point or Direct Selection drag's preview no longer stalls (#834: the position where the pointer re-entered the window could be skipped, and the move in the release's frame was lost); score and hours unchanged (estimated) | | 2026-10-22 | minor | Live vector effects: the Transform effect has Transform Objects, Transform Patterns and Scale Strokes & Effects, its checkboxes visible (#885); the area row now lists only the options on a fill's or stroke's own Transform effect. Score and hours unchanged (estimated). | | 2026-10-22 | minor | Libraries panel: the buttons beside the library picker show the items as icons (the default) or in a list, colours and graphics as rows with their names (a colour's hex value too), dragged and dropped by row; graphic thumbnails are shrunk to the size they are drawn at, so thin strokes stay whole. Tests: `panels::libraries::tests::the_list_view_shows_names_and_takes_drops_by_row`, `the_panel_draws_its_libraries`. Scores and hours unchanged. |