diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs index cd5cacac97..eaf22f0809 100644 --- a/crates/render/src/stroke.rs +++ b/crates/render/src/stroke.rs @@ -19,7 +19,7 @@ pub(crate) fn outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) -> } // Closed endpoint rounding must not consume a substantial part of a subpixel band. let fine = (tol / 8.0).min(width / 32.0).max(1e-4); - if let Some(band) = thin_line(line, st, width).and_then(|lines| thin_band(&lines, st, width, fine)) { + if let Some(band) = thin_line(line, st, width).and_then(|lines| thin_band(&lines, &corners(line), st, width, fine)) { return band; } let outline = effects::stroke::line_outline(line, st, width, fine); @@ -49,14 +49,53 @@ fn thin_line(line: &BezPath, st: &StrokeLayer, width: f64) -> Option { lines.elements().iter().all(|el| !matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))).then_some(lines) } +/// The points where `line` has a corner: where two of its segments meet with tangents that are not +/// in line ([`SMOOTH`]), or where a segment has no direction there. Sorted by [`point_order`]. +/// [`draw_sub`] leaves these points where they are, so the lines a curve is drawn with have each +/// corner at the same point. +fn corners(line: &BezPath) -> Vec { + let tangents = |seg: PathSeg| { + let c = match seg { + PathSeg::Line(l) => CubicBez::new(l.p0, l.p0, l.p1, l.p1), + other => cubic(other)?, + }; + Some((start_tangent(&c)?, end_tangent(&c)?)) + }; + let mut out = Vec::new(); + // A span of `f64::INFINITY` gives every segment no steps: only the segments are wanted. + for sub in subpaths(line.elements(), f64::INFINITY, 1.0).unwrap_or_default() { + let n = sub.segs.len(); + let first = if sub.closed { 0 } else { 1 }; + for i in first..n { + let before = if i == 0 { n - 1 } else { i - 1 }; + let (Some((a, _)), Some((b, _))) = (sub.segs.get(before), sub.segs.get(i)) else { continue }; + let smooth = match (tangents(*a).map(|t| t.1), tangents(*b).map(|t| t.0)) { + (Some(u), Some(v)) => u.dot(v) > 0.0 && u.cross(v).abs() <= SMOOTH * u.hypot() * v.hypot(), + _ => false, + }; + if !smooth { + out.push(b.start()); + } + } + } + out.sort_by(point_order); + out +} + +/// Points in order of `x`, then `y` ([`corners`]). +fn point_order(a: &Point, b: &Point) -> std::cmp::Ordering { + a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)) +} + /// The outline of stroke `st` at `width` along `lines`, a path of lines only ([`thin_line`]), to fill /// with the non-zero rule. Each side of each line is offset by half the width. Where two lines meet -/// at a small angle ([`THIN_SMOOTH`]) both sides go to where the offsets cross; elsewhere the -/// stroke's join is drawn, and an open subpath ends in the stroke's caps, with round parts drawn as +/// at a small angle ([`THIN_SMOOTH`]) both sides go to where the offsets cross. Elsewhere the +/// stroke's join is drawn at the path's `corners` ([`corners`]) and a round join where the lines a +/// curve is drawn with meet. An open subpath ends in the stroke's caps, with round parts drawn as /// lines within `fine` of their arcs. `None` when a subpath has fewer than two distinct points or a /// point that isn't finite, or is closed and no wider or taller than the stroke: those take /// [`effects::stroke::line_outline`]. -fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option { +fn thin_band(lines: &BezPath, corners: &[Point], st: &StrokeLayer, width: f64, fine: f64) -> Option { let h = width / 2.0; // The angle between two points of an arc of radius `h` drawn as lines within `fine` of it. let step = 2.0 * (1.0 - (fine / h).min(1.0)).acos().max(1e-3); @@ -80,7 +119,7 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option return None; } } - band_sub(out, pts, closed, st, h, step); + band_sub(out, pts, corners, closed, st, h, step); pts.clear(); Some(()) }; @@ -108,8 +147,9 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option /// repeating the first when `closed`) to `out`: for an open subpath one contour, its left side, /// the end cap, its right side backward and the start cap; for a closed one its left side and its /// right side backward, as two contours. `h` is half the width and `step` the angle between the -/// points of a round join or cap. -fn band_sub(out: &mut BezPath, pts: &[Point], closed: bool, st: &StrokeLayer, h: f64, step: f64) { +/// points of a round join or cap. A sharp turn takes the stroke's join at one of the path's +/// `corners` (sorted by [`point_order`]) and a round join elsewhere. +fn band_sub(out: &mut BezPath, pts: &[Point], corners: &[Point], closed: bool, st: &StrokeLayer, h: f64, step: f64) { use vectorcraft_doc::{LineCap, LineJoin}; let n = pts.len(); let chords = if closed { n } else { n - 1 }; @@ -143,7 +183,10 @@ fn band_sub(out: &mut BezPath, pts: &[Point], closed: bool, st: &StrokeLayer, h: inner.push(p); inner.push(p - nb * sign); outer.push(p + na * sign); - match st.join { + // Only the path's corners take the stroke's join; where the lines of a curve turn sharply + // the stroke along the curve is round. + let kind = if corners.binary_search_by(|c| point_order(c, &p)).is_ok() { st.join } else { LineJoin::Round }; + match kind { LineJoin::Miter if 2.0 < (1.0 + dot) * st.miter_limit.powi(2) => outer.push(p + miter * sign), LineJoin::Round => arc(outer, p, na * sign, cross.atan2(dot)), LineJoin::Miter | LineJoin::Bevel => {} diff --git a/crates/render/src/tests/thincoverage.rs b/crates/render/src/tests/thincoverage.rs index 4017448fd9..62197d4ec0 100644 --- a/crates/render/src/tests/thincoverage.rs +++ b/crates/render/src/tests/thincoverage.rs @@ -133,6 +133,127 @@ fn thin_strokes_drawn_as_lines_keep_both_turns_of_a_curve() { assert!(bounds.x1 <= turn + past && bounds.x0 >= -turn - past, "the outline spans {bounds:?}"); } +/// A path with a bend at (10, 0) and then six smooth anchors `gap` apart, each with handles +/// `handle` and 1.7 times `handle` long, scaled by `zoom`, and its points flattened within 0.001. +fn close_smooth_anchors(gap: f64, handle: f64, zoom: f64) -> (BezPath, Vec) { + let path = close_smooth_path(gap, handle, zoom); + let mut line = Vec::new(); + vectorcraft_geom::flatten(path.iter(), 1e-3, |el| { + if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = el { + line.push(p); + } + }); + (path, line) +} + +/// How far `q` is from the nearest point of `path`. +fn from_curve(path: &BezPath, q: kurbo::Point) -> f64 { + use kurbo::ParamCurveNearest; + path.segments().map(|s| s.nearest(q, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min) +} + +/// The path of [`close_smooth_anchors`]. +fn close_smooth_path(gap: f64, handle: f64, zoom: f64) -> BezPath { + use vectorcraft_geom::path::{Anchor, AnchorKind, PathData, SubPath}; + let dir = kurbo::Vec2::new(0.8, 0.6); + let mut anchors = vec![ + Anchor::corner(kurbo::Point::new(0.0, 0.0)), + Anchor::with_handles(kurbo::Point::new(10.0, 0.0), kurbo::Point::new(10.0, 0.0), kurbo::Point::new(10.0, 5.0)), + ]; + let mut x = 10.0; + for i in 0..6 { + x += gap; + let p = kurbo::Point::new(x, 1.0 + if i % 2 == 0 { 0.3 } else { -0.2 } * gap); + anchors.push(Anchor { p, h_in: p - dir * handle, h_out: p + dir * handle * 1.7, kind: AnchorKind::Smooth }); + } + anchors.push(Anchor::smooth(kurbo::Point::new(x + 20.0, 0.0), kurbo::Point::new(x + 25.0, -4.0))); + kurbo::Affine::scale(zoom) * PathData::single(SubPath::new(anchors, false)).to_bezpath() +} + +/// A thin stroke along smooth anchors that sit close together after a bend follows the curve: its +/// outline has no point farther than a stroke's width from the curve, and covers the curve. The +/// lines such a curve is drawn with are short beside the stroke and turn sharply, so offsetting +/// them drew the stroke's miter joins as spikes. +#[test] +fn thin_strokes_follow_smooth_anchors_close_together() { + for gap in [0.1, 1.0] { + let (path, line) = close_smooth_anchors(gap, 1.0, 1.0); + for w in [0.6, 0.9] { + let st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + let o = raster_stroke_outline(&path, &st, w, 0.25); + for el in o.elements() { + if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = *el { + let d = from_curve(&path, p); + assert!(d <= w, "gap {gap}, width {w}: outline point {p:?} is {d} from the curve"); + } + } + for p in line.iter().step_by(7) { + assert!(o.winding(*p) != 0, "gap {gap}, width {w}: the curve at {p:?} is not covered"); + } + } + } +} + +/// A thin stroke's outline stays within the stroke's width of its curve where the lines the curve is +/// drawn with turn sharply, as near a cusp: they meet with a round join, not the stroke's miter. +/// 200 cubic curves, each about 100 device pixels across. +#[test] +fn thin_strokes_meet_round_where_a_curves_lines_turn_sharply() { + let mut seed: u64 = 7; + let mut r = |lo: f64, hi: f64| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + lo + (hi - lo) * ((seed >> 11) as f64 / (1u64 << 53) as f64) + }; + let w = 0.5; + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + st.join = LineJoin::Miter; + st.miter_limit = 10.0; + for _ in 0..200 { + let (x, y) = (r(20.0, 980.0), r(20.0, 980.0)); + let mut q = [kurbo::Point::ZERO; 3]; + for p in &mut q { + *p = kurbo::Point::new((x + r(-30.0, 30.0)) * 1.71, (y + r(-30.0, 30.0)) * 1.71); + } + let mut path = BezPath::new(); + path.move_to((x * 1.71, y * 1.71)); + path.curve_to(q[0], q[1], q[2]); + let o = raster_stroke_outline(&path, &st, w, 0.25); + for el in o.elements() { + if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = *el { + let d = from_curve(&path, p); + assert!(d <= w, "outline point {p:?} is {d} from the curve {path:?}"); + } + } + } +} + +/// A thin stroke along smooth anchors close together, with handles long beside the gaps between +/// them, covers what the curve's own outline covers: at every point of a grid more than 0.25 pixels +/// nearer or farther than half the stroke's width from the curve, both outlines agree. The miter +/// joins drawn where the curve's lines turned sharply covered points well outside the stroke. +#[test] +fn thin_strokes_along_long_handles_cover_the_curve_outline() { + let tol = 0.25; + for (gap, w) in [(1.0, 0.6), (1.0, 0.9), (0.1, 0.6)] { + let path = close_smooth_path(gap, 10.0, 4.0); + let st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + let o = raster_stroke_outline(&path, &st, w, tol); + let fine = (tol / 8.0).min(w / 32.0); + let mut want = BezPath::new(); + vectorcraft_geom::flatten(crate::effects::stroke::line_outline(&path, &st, w, fine).iter(), fine, |el| want.push(el)); + let bb = want.bounding_box().inflate(w, w); + for i in 0..90 { + for j in 0..90 { + let q = kurbo::Point::new(bb.x0 + bb.width() * f64::from(i) / 90.0, bb.y0 + bb.height() * f64::from(j) / 90.0); + let d = from_curve(&path, q); + if (d - w / 2.0).abs() > 0.25 { + assert_eq!(o.winding(q) != 0, want.winding(q) != 0, "gap {gap}, width {w}: at {q:?}, {d} from the curve"); + } + } + } + } +} + /// Independently integrate coverage in radial/angle bins of an original notched ring. Checking /// only the outline geometry misses raster flattening that cancels its two nearby contours. #[test]