Merge pull request #10369 from dotCooCoo/fix/shape-builder-freeze

Shape Builder: stop building regions of paths that cross too often
This commit is contained in:
.CooCoo authored and GitHub committed 2026-12-01 01:16:11 -08:00
commit 0d450fa20a
7 files changed
+93 -12

No files matched your search

+1 -1
View File
@@ -59,7 +59,7 @@ pub fn interior_point(path: &PathData) -> Option<Point>;
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 skips the full map and returns only the regions of the filled areas, which are capped on their own: a filled shape apart from open paths that cross too often still has its region.
```rust
pub struct Adjacency { pub faces: Vec<MapFace>, pub edges: Vec<MapEdge>, pub slivers: Vec<PathData>, pub outlines: Vec<MapOutline> }
+3 -2
View File
@@ -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};
+10
View File
@@ -561,6 +561,16 @@ pub fn regions_with(shapes: &[Shape], precision: f64) -> Vec<Region> {
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<Vec<Region>> {
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<Vec<Region>> {
+2 -2
View File
@@ -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};
+15 -3
View File
@@ -42,6 +42,11 @@ pub(crate) fn map(shapes: &[Shape], cover: bool) -> Option<Map> {
/// [`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> {
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<Map> {
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<Point>, Vec<Edge>)> {
fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64, max_edges: usize) -> Option<(Vec<Point>, Vec<Edge>)> {
// 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::<Crossings>::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<Region>, Vec<Shape>, Vec<Shape>)> {
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<Fill> = shapes.iter().map(Fill::new).collect();
+19 -4
View File
@@ -9,6 +9,16 @@ 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 skips the full map and keeps only the regions of the filled areas,
/// which are capped on their own: when the open paths alone cross too often, a filled shape apart
/// from them still has its region.
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 +50,10 @@ 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. The same happens when the sweep cuts the paths into more than
/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces; the filled areas are then capped on their own. They
/// then have no regions when they alone are cut into more pieces than that, and a filled area
/// thinner than the precision is dropped as a sliver, as in [`regions`](crate::regions).
pub fn shape_builder(shapes: &[Shape], edges: bool) -> BuilderArrangement {
shape_builder_with_gap(shapes, edges, 0.0)
}
@@ -97,7 +110,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 +125,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<crate::Region> {
let fills = |s: &Shape| s.path.subpaths.iter().any(|sp| sp.closed || encloses_area(sp));
let keep: Vec<usize> = (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<Shape> = 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();
+43
View File
@@ -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<Shape> {
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<Shape> {
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.