diff --git a/crates/tools/src/builder/map.rs b/crates/tools/src/builder/map.rs index 6b524e9af9..437ecde69a 100644 --- a/crates/tools/src/builder/map.rs +++ b/crates/tools/src/builder/map.rs @@ -519,6 +519,58 @@ pub fn sample_polyline(pts: &[Point], step: f64) -> Vec { out } +#[cfg(test)] +thread_local! { + /// The edges [`hatch`] has tested against a scanline on this thread. + pub(super) static HATCH_EDGE_TESTS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// A region's edges in [`hatch`]'s rotated space, met in order of rising scanline. Each line tests +/// only the edges that span it, and the edges with a NaN or infinite end height. +pub(super) struct EdgeSweep { + /// The edges with finite, unequal end heights, by lower end. + edges: Vec<(Point, Point)>, + /// How many of `edges` have reached the active list. + next: usize, + /// The edges whose lower end is at or below the last line and whose upper end is above it. + active: Vec<(Point, Point)>, + /// The edges with a NaN or infinite end height. + loose: Vec<(Point, Point)>, +} + +impl EdgeSweep { + pub(super) fn new(mut edges: Vec<(Point, Point)>) -> Self { + let mut loose = vec![]; + edges.retain(|&(a, c)| { + let finite = a.y.is_finite() && c.y.is_finite(); + if !finite { + loose.push((a, c)); + } + // An edge with equal end heights never crosses a scanline. + finite && a.y != c.y + }); + edges.sort_unstable_by(|(a, c), (b, d)| a.y.min(c.y).total_cmp(&b.y.min(d.y))); + EdgeSweep { edges, next: 0, active: vec![], loose } + } + + /// Pushes the x of each edge crossing the scanline at `y` onto `xs`, in no particular order. + /// `y` is not NaN and never decreases from one call to the next. + pub(super) fn crossings(&mut self, y: f64, xs: &mut Vec) { + while let Some(&(a, c)) = self.edges.get(self.next).filter(|(a, c)| a.y.min(c.y) <= y) { + self.active.push((a, c)); + self.next += 1; + } + self.active.retain(|(a, c)| a.y.max(c.y) > y); + #[cfg(test)] + HATCH_EDGE_TESTS.with(|n| n.set(n.get() + self.active.len() + self.loose.len())); + for (a, c) in self.active.iter().chain(&self.loose) { + if (a.y <= y) != (c.y <= y) { + xs.push(a.x + (y - a.y) / (c.y - a.y) * (c.x - a.x)); + } + } + } +} + /// Diagonal hatch lines filling `path` (the Shape Builder's grey mesh highlight), `gap` apart. pub fn hatch(path: &BezPath, gap: f64) -> BezPath { let mut out = BezPath::new(); @@ -563,6 +615,7 @@ pub fn hatch(path: &BezPath, gap: f64) -> BezPath { } let gap = gap.max((y1 - y0) / 400.0).max(1e-6); let start = (y0 / gap).floor() * gap + gap * 0.5; + let mut sweep = EdgeSweep::new(edges); let mut xs: Vec = vec![]; // Counted, not summed: far from the origin `y + gap` can round back to `y`. The gap is at least // a 400th of the height, so 402 lines cover it. @@ -572,11 +625,7 @@ pub fn hatch(path: &BezPath, gap: f64) -> BezPath { break; } xs.clear(); - for (a, c) in &edges { - if (a.y <= y) != (c.y <= y) { - xs.push(a.x + (y - a.y) / (c.y - a.y) * (c.x - a.x)); - } - } + sweep.crossings(y, &mut xs); xs.sort_by(f64::total_cmp); for pair in xs.as_chunks::<2>().0 { out.move_to(unrot(Point::new(pair[0], y))); diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 78d1c0b838..2de1260d3e 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -1032,6 +1032,275 @@ fn hatch_far_from_the_origin_ends() { assert!(hatch(&bp, 4.0).elements().len() <= 2 * 402); } +/// [`hatch`] as it tested every edge on every scanline, the reference the sweep must match. +fn hatch_every_edge(path: &BezPath, gap: f64) -> BezPath { + let mut out = BezPath::new(); + let b = path.bounding_box(); + if b.width() <= 0.0 || b.height() <= 0.0 { + return out; + } + let s = std::f64::consts::FRAC_1_SQRT_2; + let rot = |p: Point| Point::new((p.x + p.y) * s, (p.y - p.x) * s); + let unrot = |p: Point| Point::new((p.x - p.y) * s, (p.x + p.y) * s); + let mut edges: Vec<(Point, Point)> = vec![]; + let mut first = Point::ZERO; + let mut last = Point::ZERO; + kurbo::flatten(path.iter(), gap.max(1e-3) * 0.1, |el| match el { + kurbo::PathEl::MoveTo(p) => { + if last != first { + edges.push((rot(last), rot(first))); + } + first = p; + last = p; + } + kurbo::PathEl::LineTo(p) => { + edges.push((rot(last), rot(p))); + last = p; + } + kurbo::PathEl::ClosePath => { + if last != first { + edges.push((rot(last), rot(first))); + } + last = first; + } + _ => {} + }); + if last != first { + edges.push((rot(last), rot(first))); + } + let (mut y0, mut y1) = (f64::INFINITY, f64::NEG_INFINITY); + for (a, c) in &edges { + y0 = y0.min(a.y.min(c.y)); + y1 = y1.max(a.y.max(c.y)); + } + let gap = gap.max((y1 - y0) / 400.0).max(1e-6); + let start = (y0 / gap).floor() * gap + gap * 0.5; + let mut xs: Vec = vec![]; + for i in 0..402u32 { + let y = start + f64::from(i) * gap; + if y.partial_cmp(&y1) != Some(std::cmp::Ordering::Less) { + break; + } + xs.clear(); + for (a, c) in &edges { + if (a.y <= y) != (c.y <= y) { + xs.push(a.x + (y - a.y) / (c.y - a.y) * (c.x - a.x)); + } + } + xs.sort_by(f64::total_cmp); + for pair in xs.as_chunks::<2>().0 { + out.move_to(unrot(Point::new(pair[0], y))); + out.line_to(unrot(Point::new(pair[1], y))); + } + } + out +} + +/// A path's elements with every coordinate as its bits, so NaN and -0.0 compare exactly. +fn path_bits(p: &BezPath) -> Vec<(u8, Vec)> { + let bits = |pts: &[Point]| pts.iter().flat_map(|p| [p.x.to_bits(), p.y.to_bits()]).collect(); + p.elements() + .iter() + .map(|el| match *el { + kurbo::PathEl::MoveTo(a) => (0, bits(&[a])), + kurbo::PathEl::LineTo(a) => (1, bits(&[a])), + kurbo::PathEl::QuadTo(a, b) => (2, bits(&[a, b])), + kurbo::PathEl::CurveTo(a, b, c) => (3, bits(&[a, b, c])), + kurbo::PathEl::ClosePath => (4, vec![]), + }) + .collect() +} + +/// A closed polygon through `pts`. +fn polygon(pts: impl IntoIterator) -> BezPath { + let mut bp = BezPath::new(); + for (i, p) in pts.into_iter().enumerate() { + if i == 0 { + bp.move_to(p); + } else { + bp.line_to(p); + } + } + bp.close_path(); + bp +} + +/// A polygon of `n` sides inscribed in the circle of radius `r` about the origin. +fn circle_polygon(n: u32, r: f64) -> BezPath { + polygon((0..n).map(|i| { + let t = std::f64::consts::TAU * f64::from(i) / f64::from(n); + Point::new(r * t.cos(), r * t.sin()) + })) +} + +/// The paths the hatch is checked on: many edges, a random star, holes, several subpaths, a +/// sliver, curves, edges along the hatch, repeated outlines, an open path, far coordinates, an +/// empty path and NaN and infinite coordinates. +fn hatch_cases() -> Vec<(&'static str, BezPath)> { + let mut seed = 0x2545_f491_4f6c_dd1d_u64; + let mut rand = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f64 / (1u64 << 53) as f64 + }; + let star = polygon((0..300).map(|i| { + let t = std::f64::consts::TAU * f64::from(i) / 300.0; + let r = 100.0 + 300.0 * rand(); + Point::new(r * t.cos(), r * t.sin()) + })); + let mut holes = shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 200.0)).to_bezpath(); + holes.extend(polygon([(50.0, 50.0), (50.0, 150.0), (120.0, 150.0), (120.0, 50.0)].map(Point::from))); + holes.extend(polygon([(180.0, 40.0), (260.0, 100.0), (180.0, 160.0)].map(Point::from))); + holes.extend(circle_polygon(40, 30.0).iter().map(|el| match el { + kurbo::PathEl::MoveTo(p) => kurbo::PathEl::MoveTo(p + kurbo::Vec2::new(400.0, 100.0)), + kurbo::PathEl::LineTo(p) => kurbo::PathEl::LineTo(p + kurbo::Vec2::new(400.0, 100.0)), + other => other, + })); + let mut repeated = BezPath::new(); + for _ in 0..7 { + repeated.extend(shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)).to_bezpath()); + } + let mut open = BezPath::new(); + open.move_to((0.0, 0.0)); + open.line_to((120.0, 10.0)); + open.line_to((60.0, 90.0)); + vec![ + ("2,000-sided circle", circle_polygon(2000, 500.0)), + ("300-point star", star), + ("holes and subpaths", holes), + ("sliver", polygon([(0.0, 0.0), (900.0, 1.0), (900.0, 1.002)].map(Point::from))), + ("curves", kurbo::Circle::new((10.0, -20.0), 300.0).to_path(0.01)), + ("edges along the hatch", polygon([(0.0, 0.0), (10.0, 10.0), (0.0, 20.0), (-10.0, 10.0)].map(Point::from))), + ("repeated outlines", repeated), + ("open path", open), + ("far from the origin", shapes::rectangle(Rect::new(0.0, 1e17, 64.0, 1e17 + 64.0)).to_bezpath()), + ("empty", BezPath::new()), + ("NaN", polygon([(0.0, 0.0), (100.0, f64::NAN), (100.0, 100.0), (0.0, 80.0)].map(Point::from))), + ("infinite", polygon([(0.0, 0.0), (f64::INFINITY, 50.0), (100.0, 100.0)].map(Point::from))), + ] +} + +#[test] +fn hatch_matches_testing_every_edge() { + for (name, bp) in hatch_cases() { + for gap in [0.5, 4.0, 40.0] { + assert_eq!(path_bits(&hatch(&bp, gap)), path_bits(&hatch_every_edge(&bp, gap)), "{name} at gap {gap}"); + } + } +} + +#[test] +fn hatch_tests_only_the_edges_spanning_each_line() { + let bp = circle_polygon(2000, 500.0); + let before = map::HATCH_EDGE_TESTS.with(std::cell::Cell::get); + let h = hatch(&bp, 4.0); + let tests = map::HATCH_EDGE_TESTS.with(std::cell::Cell::get) - before; + // Each line crosses the circle once, so it has one segment. + let lines = h.elements().len() / 2; + assert!(lines > 200, "{lines}"); + assert!(tests * 20 < lines * 2000, "{tests} edge tests on {lines} lines of 2,000 edges"); +} + +#[test] +fn hatch_sweep_finds_the_crossings_of_every_edge() { + let p = Point::new; + let edges = vec![ + (p(0.0, 0.0), p(1.0, 1.0)), + (p(1.0, 1.0), p(0.0, 2.0)), + (p(3.0, 2.0), p(3.0, -1.0)), + (p(5.0, 1.0), p(9.0, 1.0)), + (p(2.0, -0.0), p(2.0, 0.0)), + (p(4.0, -0.0), p(4.0, 3.0)), + (p(6.0, 0.5), p(6.0, 0.5)), + (p(7.0, f64::NAN), p(7.0, 2.0)), + (p(8.0, 0.0), p(8.0, f64::INFINITY)), + (p(f64::NAN, 0.0), p(1.0, 2.0)), + (p(3.0, 2.0), p(3.0, -1.0)), + (p(3.0, 2.0), p(3.0, -1.0)), + ]; + let mut sweep = map::EdgeSweep::new(edges.clone()); + let mut xs = vec![]; + for y in [-2.0, -1.0, -0.0, 0.0, 0.5, 1.0, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0] { + let mut old: Vec = + edges.iter().filter(|(a, c)| (a.y <= y) != (c.y <= y)).map(|(a, c)| a.x + (y - a.y) / (c.y - a.y) * (c.x - a.x)).collect(); + xs.clear(); + sweep.crossings(y, &mut xs); + old.sort_by(f64::total_cmp); + xs.sort_by(f64::total_cmp); + let bits = |v: &[f64]| v.iter().map(|x| x.to_bits()).collect::>(); + assert_eq!(bits(&xs), bits(&old), "at y = {y}"); + } +} + +fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos) +} + +/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock. +fn cpu_time(f: impl FnOnce()) -> std::time::Duration { + match thread_cpu() { + Some(before) => { + f(); + thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before)) + } + None => { + let start = std::time::Instant::now(); + f(); + start.elapsed() + } + } +} + +/// Timings of 1,000 hatches by the sweep and by testing every edge, on a 2,000-sided circle of +/// radius 500 and on a 40-sided one, run in turn, 7 runs each. Ignored by default; it prints the +/// median, fastest and slowest run and sets no bound on them: +/// `cargo test --release -p vectorcraft-tools --lib hatch_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn hatch_perf() { + const RUNS: usize = 7; + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + eprintln!("hatch_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + for (sides, r) in [(2000, 500.0), (2000, 100.0), (40, 100.0)] { + let bp = circle_polygon(sides, r); + assert_eq!(path_bits(&hatch(&bp, 4.0)), path_bits(&hatch_every_edge(&bp, 4.0))); + let (mut old, mut new) = (vec![], vec![]); + let every = || { + for _ in 0..1000 { + std::hint::black_box(hatch_every_edge(std::hint::black_box(&bp), 4.0)); + } + }; + let sweep = || { + for _ in 0..1000 { + std::hint::black_box(hatch(std::hint::black_box(&bp), 4.0)); + } + }; + for run in 0..RUNS { + // The two take turns going first. + if run % 2 == 0 { + old.push(cpu_time(every)); + new.push(cpu_time(sweep)); + } else { + new.push(cpu_time(sweep)); + old.push(cpu_time(every)); + } + } + old.sort(); + new.sort(); + eprintln!( + "hatch_perf: {sides:>5} sides r {r:>5}: every edge {:>9.3} ms ({:.3}-{:.3}), sweep {:>9.3} ms ({:.3}-{:.3})", + ms(old[RUNS / 2]), + ms(old[0]), + ms(old[RUNS - 1]), + ms(new[RUNS / 2]), + ms(new[0]), + ms(new[RUNS - 1]), + ); + } +} + /// An empty hidden sources group for a Live Paint group made in a test. fn empty_sources(d: &mut Document) -> Arc { let mut g = Node::group(d.alloc_id(), vec![]); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..948d558050 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1356,6 +1356,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Pick Color From Artwork, a merged shape takes the appearance, opacity and blending mode of the object where the drag starts, else of the object where it ends, else of the front-most selected object, as the [Shape Builder combine page](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes. A click in an area that no selected object covers, such as a hole other shapes enclose, takes the front-most selected object's look (`shapeBuilder.merge` `points`: the first point is where the drag starts, and the last point is where it ends). A Shift-drag with the Shape Builder tool draws a rectangular marquee for merging many paths at once, as [Combine shapes with the Shape Builder tool](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes: the regions it reaches are shaded while it is drawn and merge into one shape on release, or with Alt they are deleted. The marquee reaches each region whose outline crosses it or has an anchor inside it, and the region that holds the whole marquee; this rule is VectorCraft's own. For Pick Color From Artwork, the marquee's starting corner is where the drag starts and the opposite corner is where it ends (`shapeBuilder.merge` `rect`). Shape Builder pieces on dense hatches (lines at exact 0.25 or 0.5 pt steps across another line) come back one per stretch between crossings, with no speck where the sweep cut a line's two passes a rounding error apart: the planar map contracts the stub between such cuts into one vertex, bounded by each cluster's extent so a run of tiny level segments keeps its length (`crates/pathops/src/planar.rs` tests `a_dense_hatch_at_exact_binary_steps_cuts_each_line_once_per_crossing`, `a_run_of_tiny_level_segments_is_not_contracted_as_stubs`, `a_line_crossed_where_its_two_passes_part_is_cut_once`). + The Shape Builder's gray hatch over the region under the pointer and the regions a drag has touched is drawn by a sweep that tests each hatch line only against the region's edges that span it, instead of every edge on every line. The hatch lines are the same, coordinate for coordinate; on a 2,000-sided region 1,000 hatches take about 83 ms of CPU time instead of 356 ms (release build, median of 7 alternating runs), and on a region of 40 sides the time is about the same, so the gain is on large, complex regions such as traced art (`crates/tools/src/builder/tests.rs` tests `hatch_matches_testing_every_edge`, `hatch_tests_only_the_edges_spanning_each_line` and `hatch_sweep_finds_the_crossings_of_every_edge`; timing: `hatch_perf`). The planar map's edge-source grid stays linear in memory on any input: a segment is filed once per cell it crosses, and the grid holds at most a budget of cell references (a few dozen per item plus a few rows' worth), past which the remaining items go to a short scanned list and are still found, so thousands of coincident segments cannot make the index quadratic (`crates/pathops/src/planar.rs` test `rect_index_holds_a_bounded_number_of_references`). The Blob Brush Tool Options have Keep selected and Merge only with selection, both off by default: while Keep selected is off, the blob a stroke draws or merges into is not selected afterwards, and while Merge only with selection is on, a stroke merges only with selected blobs of its color that it touches (`path.blob` `keepSelected` and `mergeOnlySelection`). The Blob Brush Tool Options also have Angle and Roundness, as the reference app's [Blob Brush options](https://web.archive.org/web/20261012042029/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/blob-brush-options-and-best-practices.html) list them: Angle from −180° to 180° (0° by default) and Roundness from 0% to 100% (100%, a round tip, by default). The elliptical tip keeps its angle on the page along a stroke, a 0% tip is drawn 0.1% as wide as it is long, and the dialog shows the tip and three dabs of it. The values are kept with the tool's options (`path.blob` `angle` and `roundness`). Not done: the Random and pen-driven variations of Angle and Roundness.