From 7a46d5ec564fec016045cf956ef86817c8275559 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 21:19:58 -0800 Subject: [PATCH] Shape Builder: stop building regions of paths that cross too often Paths that cross each other many times are cut by the sweep into far more pieces than they have segments, and building the regions and edges of those pieces took minutes and gigabytes of memory. 400 circles stacked nearly on top of each other (1,600 segments) were cut into about 320,000 pieces, and their map took 60 s and 4.2 GB, enough to make the whole computer unresponsive. The Shape Builder now stops after the sweep when it cuts the paths into more than SHAPE_BUILDER_MAX_MAP_EDGES pieces (twice SHAPE_BUILDER_MAX_SEGMENTS, what open paths that cross nothing make at that cap) and finds no regions. The filled-area regions it falls back to are capped the same way. --- crates/pathops/README.md | 2 +- crates/pathops/src/lib.rs | 5 ++- crates/pathops/src/pathfinder.rs | 10 +++++ crates/pathops/src/planar.rs | 4 +- crates/pathops/src/planar/map.rs | 18 +++++++-- crates/pathops/src/planar/shape_builder.rs | 19 ++++++++-- crates/pathops/src/planar/tests.rs | 43 ++++++++++++++++++++++ 7 files changed, 89 insertions(+), 12 deletions(-) diff --git a/crates/pathops/README.md b/crates/pathops/README.md index 2397045a84..54b39b1dc5 100644 --- a/crates/pathops/README.md +++ b/crates/pathops/README.md @@ -59,7 +59,7 @@ pub fn interior_point(path: &PathData) -> Option; Unlike `regions`, which splits the filled areas of closed shapes, `live_paint` treats every path as an edge, open paths included. Three crossing lines enclose a triangle, a line across a rectangle splits it in two, and an area enclosed by paths becomes a face even when nothing fills it. Each face lists the inputs whose fill covers it; the list is empty for an area that is only enclosed by paths. Each edge is a piece of a path, split wherever another path meets it, and keeps the key of the front-most input it lies on. -`shape_builder` gives the Shape Builder's regions. With closed paths only, they are the `regions`. Once an open path is among them, they are the `live_paint` faces, so a stroke-only line across a shape splits it and lines can enclose a region of their own. The second list holds the pieces of each path that has no closed subpath, keyed by its index, so the Shape Builder can delete them one by one. The caller closes any open path whose fill should count. Inputs with more than `SHAPE_BUILDER_MAX_SEGMENTS` segments fall back to the filled areas. +`shape_builder` gives the Shape Builder's regions. With closed paths only, they are the `regions`. Once an open path is among them, they are the `live_paint` faces, so a stroke-only line across a shape splits it and lines can enclose a region of their own. The second list holds the pieces of each path that has no closed subpath, keyed by its index, so the Shape Builder can delete them one by one. The caller closes any open path whose fill should count. Inputs with more than `SHAPE_BUILDER_MAX_SEGMENTS` segments fall back to the filled areas. When the paths cross each other so often that the sweep cuts them into more than `SHAPE_BUILDER_MAX_MAP_EDGES` pieces, it returns no regions. ```rust pub struct Adjacency { pub faces: Vec, pub edges: Vec, pub slivers: Vec, pub outlines: Vec } diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index d02e5a8a93..61d03ecbc1 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -33,8 +33,9 @@ pub use pathfinder::{ FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_with, regions_within, }; pub use planar::{ - Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, adjacency, cut_out, - encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap, + Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS, + adjacency, cut_out, encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, + shape_builder_with_gap, }; pub use thickness::{MAX_DOCUMENT_THICKNESS_WORK, MAX_THICKNESS_PIECES, ThicknessBudget, thinner_than, thinner_than_within}; pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band}; diff --git a/crates/pathops/src/pathfinder.rs b/crates/pathops/src/pathfinder.rs index 102d7e7138..3caddb4bc0 100644 --- a/crates/pathops/src/pathfinder.rs +++ b/crates/pathops/src/pathfinder.rs @@ -561,6 +561,16 @@ pub fn regions_with(shapes: &[Shape], precision: f64) -> Vec { arrangement(shapes, precision).map(|a| regions_of(&a)).unwrap_or_default() } +/// [`regions_with`], or `None` when the sweep cuts the shapes into more than `max_edges` pieces +/// (the faces are then not built). +pub(crate) fn regions_capped(shapes: &[Shape], precision: f64, max_edges: usize) -> Option> { + let Some(a) = arrangement(shapes, precision) else { return Some(Vec::new()) }; + if a.top.segment_indices().nth(max_edges).is_some() { + return None; + } + Some(regions_of(&a)) +} + /// [`regions`] when there are at most `limit` of them; `None` when there are more, found as soon /// as the face past `limit` is built (the faces after it are not built). pub fn regions_within(shapes: &[Shape], limit: usize) -> Option> { diff --git a/crates/pathops/src/planar.rs b/crates/pathops/src/planar.rs index f702f993ed..ca473dd839 100644 --- a/crates/pathops/src/planar.rs +++ b/crates/pathops/src/planar.rs @@ -41,8 +41,8 @@ pub use live_paint::{find_gaps, live_paint, live_paint_with_gaps}; pub use map::interior_point; pub(crate) use map::{Map, Rest, map}; pub use shape_builder::{ - BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, has_open_path, run_around, shape_builder, - shape_builder_with_gap, + BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, has_open_path, + run_around, shape_builder, shape_builder_with_gap, }; pub(crate) use shape_builder::{builder, gap_inputs}; diff --git a/crates/pathops/src/planar/map.rs b/crates/pathops/src/planar/map.rs index f2c4b200d3..051a341e1a 100644 --- a/crates/pathops/src/planar/map.rs +++ b/crates/pathops/src/planar/map.rs @@ -42,6 +42,11 @@ pub(crate) fn map(shapes: &[Shape], cover: bool) -> Option { /// [`map`] whose faces and pieces are refit to `precision`, and whose slivers thinner than it are dropped. pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option { + map_within(shapes, cover, precision, usize::MAX) +} + +/// [`map_with`], or `None` when the sweep cuts the paths into more than `max_edges` pieces. +pub(super) fn map_within(shapes: &[Shape], cover: bool, precision: f64, max_edges: usize) -> Option { let mut inputs: Vec<(BezPath, usize)> = Vec::new(); for (i, s) in shapes.iter().enumerate() { let mut bp = BezPath::new(); @@ -69,7 +74,7 @@ pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option< return None; } let tidy = Tidy::keeping(precision, inputs.iter().map(|p| &p.0)); - let (points, edges) = sweep_graph(&inputs, eps, precision)?; + let (points, edges) = sweep_graph(&inputs, eps, precision, max_edges)?; let nv = points.len(); // Half-edges leaving each vertex, sorted by direction; walking a face, the next half-edge is @@ -188,11 +193,17 @@ pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option< Some(Map { edges, around, slot_of, faces, face_index, slivers, holes, face_holes, tidy, anchors, snap }) } -fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64) -> Option<(Vec, Vec)> { +fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64, max_edges: usize) -> Option<(Vec, Vec)> { // The sweep can panic on rare near-degenerate input; that must never take the app down. let sweep = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Topology::::from_paths(inputs.iter().map(|(p, i)| (p, *i)), eps))); let top = sweep.ok()?.ok()?; + // What is built from here on takes time and memory in proportion to the pieces the sweep cut + // the paths into, and paths that cross many times are cut into far more pieces than they have + // segments. + if top.segment_indices().nth(max_edges).is_some() { + return None; + } // The planar graph: vertices are the sweep's points, edges its segments. Points closer than // the sweep's tolerance are one vertex (it can put a corner that lies on another path's edge // a rounding error away from where it cuts that edge). @@ -426,8 +437,9 @@ impl Map { /// Faces and edges of `shapes`, and the pieces of the open paths (those with no closed subpath) /// that lie under another path in front of them, whose edges are that path's: under a closed /// path's outline, or along an open path in front. +/// `None` when the sweep cuts the paths into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces. pub(super) fn build(shapes: &[Shape], precision: f64) -> Option<(Vec, Vec, Vec)> { - let m = map_with(shapes, false, precision)?; + let m = map_within(shapes, false, precision, SHAPE_BUILDER_MAX_MAP_EDGES)?; let Map { edges, around, faces, holes, face_holes, tidy, anchors, snap, .. } = &m; let snap = *snap; let fills: Vec = shapes.iter().map(Fill::new).collect(); diff --git a/crates/pathops/src/planar/shape_builder.rs b/crates/pathops/src/planar/shape_builder.rs index fcfb6cea95..b1f8520c23 100644 --- a/crates/pathops/src/planar/shape_builder.rs +++ b/crates/pathops/src/planar/shape_builder.rs @@ -9,6 +9,14 @@ use super::*; /// can take on art far past what a drawing holds. pub const SHAPE_BUILDER_MAX_SEGMENTS: usize = 65_536; +/// Most pieces the sweep may cut the Shape Builder's paths into, where they cross each other and +/// where an open path is traced there and back: twice [`SHAPE_BUILDER_MAX_SEGMENTS`], what open +/// paths that cross nothing make at that cap. Paths that cross many times make far more pieces +/// than they have segments (400 circles stacked nearly on top of each other, 1,600 segments, make +/// about 320,000), and the regions and edges built from them took minutes and gigabytes of memory. +/// Past this the Shape Builder finds no regions. +pub const SHAPE_BUILDER_MAX_MAP_EDGES: usize = 2 * SHAPE_BUILDER_MAX_SEGMENTS; + /// The Shape Builder's arrangement: see [`shape_builder`]. #[derive(Clone, Debug, Default, PartialEq)] pub struct BuilderArrangement { @@ -40,7 +48,8 @@ pub fn has_open_path(shapes: &[Shape]) -> bool { /// nothing fills, and each path with no closed subpath comes back cut wherever another path meets /// it, as pieces keyed by its index in `shapes`. Outlines are cut the same way. With more than /// [`SHAPE_BUILDER_MAX_SEGMENTS`] segments or a map that can't be built, only the filled areas -/// count and there are no pieces. +/// count and there are no pieces. When the sweep cuts the paths into more than +/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces, there are no regions either. pub fn shape_builder(shapes: &[Shape], edges: bool) -> BuilderArrangement { shape_builder_with_gap(shapes, edges, 0.0) } @@ -97,7 +106,7 @@ pub(crate) fn builder(shapes: &[Shape], edges: bool, gap: f64, precision: f64) - faces } else { // The filled areas from their arrangement, whose faces merge exactly, then the gaps. - let mut regions = crate::pathfinder::regions_with(shapes, precision); + let mut regions = crate::pathfinder::regions_capped(shapes, precision, SHAPE_BUILDER_MAX_MAP_EDGES).unwrap_or_default(); regions.extend(faces.into_iter().filter(|f| f.sources.is_empty())); regions }; @@ -112,14 +121,16 @@ pub(crate) fn builder(shapes: &[Shape], edges: bool, gap: f64, precision: f64) - /// The regions of the shapes' filled areas. A shape that fills nothing (open paths that enclose no /// area, such as cutting lines) is left out, so a flood of them cannot push the arrangement past its /// size budget and take the filled shapes down with it; the regions keep the original indices. +/// There are none when the sweep cuts the filled shapes into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces. fn filled_regions(shapes: &[Shape], precision: f64) -> Vec { let fills = |s: &Shape| s.path.subpaths.iter().any(|sp| sp.closed || encloses_area(sp)); let keep: Vec = (0..shapes.len()).filter(|&i| shapes.get(i).is_some_and(fills)).collect(); if keep.len() == shapes.len() { - return crate::pathfinder::regions_with(shapes, precision); + return crate::pathfinder::regions_capped(shapes, precision, SHAPE_BUILDER_MAX_MAP_EDGES).unwrap_or_default(); } let kept: Vec = keep.iter().filter_map(|&i| shapes.get(i).cloned()).collect(); - crate::pathfinder::regions_with(&kept, precision) + crate::pathfinder::regions_capped(&kept, precision, SHAPE_BUILDER_MAX_MAP_EDGES) + .unwrap_or_default() .into_iter() .map(|mut r| { r.sources = r.sources.iter().filter_map(|&s| keep.get(s).copied()).collect(); diff --git a/crates/pathops/src/planar/tests.rs b/crates/pathops/src/planar/tests.rs index ad888448a7..130d381bfa 100644 --- a/crates/pathops/src/planar/tests.rs +++ b/crates/pathops/src/planar/tests.rs @@ -603,6 +603,49 @@ fn shape_builder_offers_the_gaps_closed_shapes_enclose() { assert!(shape_builder(&s, false).regions.iter().all(|r| !r.sources.is_empty())); } +/// `n` horizontal and `n` vertical lines across one square, every one crossing every other. +fn line_grid(n: usize) -> Vec { + let at = |k: usize| 10.0 + k as f64 * 980.0 / n as f64; + let across = (0..n).map(|k| line((0.0, at(k)), (1000.0, at(k)), k as u64)); + let down = (0..n).map(|k| line((at(k), 0.0), (at(k), 1000.0), (n + k) as u64)); + across.chain(down).collect() +} + +/// `n` horizontal and `n` vertical bars across one square, every one crossing every other. +fn bar_grid(n: usize) -> Vec { + let at = |k: usize| 10.0 + k as f64 * 980.0 / n as f64; + let across = (0..n).map(|k| rect(0.0, at(k), 1000.0, at(k) + 1.0, k as u64)); + let down = (0..n).map(|k| rect(at(k), 0.0, at(k) + 1.0, 1000.0, (n + k) as u64)); + across.chain(down).collect() +} + +#[test] +fn a_map_past_its_edge_cap_is_not_built() { + // 20 lines each way: each line is cut into 21 pieces, 840 in all. + let s = line_grid(20); + assert!(map::map_within(&s, false, DEFAULT_PRECISION, 1000).is_some()); + assert!(map::map_within(&s, false, DEFAULT_PRECISION, 500).is_none()); + let bars = bar_grid(20); + assert!(crate::pathfinder::regions_capped(&bars, DEFAULT_PRECISION, 100_000).is_some_and(|r| r.len() > 400)); + assert!(crate::pathfinder::regions_capped(&bars, DEFAULT_PRECISION, 1000).is_none()); +} + +#[test] +fn shape_builder_builds_no_regions_past_its_edge_cap() { + // 300 lines each way cross 90,000 times with 600 segments: the sweep cuts them into about + // 180,000 pieces, past the cap, and nothing is built from them. + let s = line_grid(300); + let started = work_done(); + let BuilderArrangement { regions, lines, edges, lines_under } = shape_builder(&s, true); + assert!(regions.is_empty() && lines.is_empty() && edges.is_empty() && lines_under.is_empty(), "{} regions", regions.len()); + assert_eq!(work_done() - started, 0, "no face or edge was looked up"); + // Bars, closed paths only, each edge crossing 300 others: their filled areas are not built + // either. + assert!(shape_builder(&bar_grid(150), true).regions.is_empty()); + // Under the cap, the same grid is built. + assert_eq!(shape_builder(&line_grid(20), false).regions.len(), 19 * 19); +} + #[test] fn shape_builder_stays_quick_up_to_its_cap() { // A wavy ring of nearly the most segments the map takes, crossed by a few lines.