diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index b4ce273dad..0085c2d9d6 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -803,35 +803,59 @@ fn offset_path(s: &mut Session, p: &Value) -> Result { let miter = number_given(p, "miterLimit", C)?.unwrap_or(4.0).clamp(1.0, 500.0); let roots = selected_roots(s)?; let ids = s.edit("Offset Path", |d, sel| { - let (mut out, mut above) = (vec![], vec![]); - let mut paths = false; + // Each selected root, whether it is a group, and the style of each of its leaf paths; the + // paths themselves go to `sources` in the same order. + let (mut roots_found, mut sources) = (vec![], vec![]); for id in &roots { - let Some(n) = d.node(*id).cloned() else { continue }; - let mut lv = vec![]; - leaves(&n, &mut lv); + let Some(n) = d.node(*id) else { continue }; + let mut styles = vec![]; + each_leaf(n, &mut |l| { + if !matches!(l.kind, NodeKind::Text(_)) + && let Some((path, rule)) = node_path(l) + { + styles.push(Style::of(l)); + sources.push((path, rule, matches!(l.kind, NodeKind::Compound { .. }))); + } + }); + roots_found.push((*id, matches!(n.kind, NodeKind::Group { .. }), styles)); + } + let paths = !sources.is_empty(); + let offset = |(path, rule, compound): &(PathData, FillRule, bool)| { + let normalized; + let base = if *compound && path.is_closed() { + normalized = po::normalize(path, *rule); + &normalized + } else { + path + }; + match po::try_offset_path(base, delta, join, miter) { + Ok(p) => Ok(Some(p)), + Err(po::PathOpsError::NonFinite) => Ok(None), + Err(e) => Err(e), + } + }; + // The offsets are worked out together; the nodes are made here, in selection order, so + // the ids, the stacking and the first error are those of one path after another. + let (offsets, _) = ordered_map(&sources, offset_threads(), offset, std::result::Result::is_err); + let mut offsets = offsets.into_iter(); + let (mut out, mut above) = (vec![], vec![]); + for (id, group, styles) in roots_found { let mut made = vec![]; - for l in lv.iter().filter(|l| !matches!(l.kind, NodeKind::Text(_))) { - let Some((path, rule)) = node_path(l) else { continue }; - paths = true; - let base = if matches!(l.kind, NodeKind::Compound { .. }) && path.is_closed() { po::normalize(&path, rule) } else { path }; - let off = match po::try_offset_path(&base, delta, join, miter) { - Ok(p) => p, - Err(po::PathOpsError::NonFinite) => continue, - Err(po::PathOpsError::TooComplex) => { + for style in &styles { + match offsets.next().flatten() { + Some(Ok(Some(off))) if !off.is_empty() => made.push(shape_node_styled(d, off, style)), + Some(Err(po::PathOpsError::TooComplex)) => { return Err(EngineError::Other("Offset Path: the path is too complex to offset".into())); } - Err(e) => return Err(EngineError::Other(format!("Offset Path: {e}"))), - }; - if off.is_empty() { - continue; + Some(Err(e)) => return Err(EngineError::Other(format!("Offset Path: {e}"))), + _ => {} } - made.push(shape_node(d, off, Some(l))); } if made.is_empty() { continue; } let new = if made.len() == 1 - && !matches!(n.kind, NodeKind::Group { .. }) + && !group && let Some(one) = made.pop() { one @@ -840,7 +864,7 @@ fn offset_path(s: &mut Session, p: &Value) -> Result { Node::group(gid, made.into_iter().map(Arc::new).collect()) }; out.push(new.id); - above.push((*id, vec![new])); + above.push((id, vec![new])); } if out.is_empty() && paths { return Err(EngineError::Other("Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes)".into())); @@ -855,6 +879,86 @@ fn offset_path(s: &mut Session, p: &Value) -> Result { Ok(ids_json(&ids)) } +/// The threads [`offset_path`] works on: the logical CPUs, or one on the web. +fn offset_threads() -> usize { + #[cfg(target_arch = "wasm32")] + { + 1 + } + #[cfg(not(target_arch = "wasm32"))] + { + std::thread::available_parallelism().map_or(1, std::num::NonZero::get) + } +} + +/// `f` of each of `items`, in their order. The items are split into runs whose sizes differ by +/// at most one, as many as `threads` or the items allow and at least one. This thread works +/// on the first run, and a thread of its own works on each other run (this thread does when that +/// one can't start). Once `stop` accepts a result, the items after it are left out (`None`); every +/// item before the first such result has its result. Returns the results and the number of +/// threads that worked on them. +pub(crate) fn ordered_map( + items: &[T], + threads: usize, + f: impl Fn(&T) -> R + Sync, + stop: impl Fn(&R) -> bool + Sync, +) -> (Vec>, usize) { + use std::sync::atomic::{AtomicUsize, Ordering}; + let mut out: Vec> = std::iter::repeat_with(|| None).take(items.len()).collect(); + let stopped = AtomicUsize::new(usize::MAX); + let run = |from: usize, its: &[T], out: &mut [Option]| { + for (i, (item, slot)) in its.iter().zip(out).enumerate() { + let at = from + i; + if at > stopped.load(Ordering::Relaxed) { + return; + } + let r = f(item); + if stop(&r) { + stopped.fetch_min(at, Ordering::Relaxed); + } + *slot = Some(r); + } + }; + let runs = threads.clamp(1, items.len().max(1)); + if runs == 1 { + run(0, items, &mut out); + return (out, 1); + } + // Run `k` holds the items from `start(k)` up to `start(k + 1)`. + let start = |k: usize| k * items.len() / runs; + let mut unstarted = vec![]; + let used = std::thread::scope(|s| { + let mut rest = out.as_mut_slice(); + let mut first = None; + let mut used = 1; + for k in 0..runs { + let (from, to) = (start(k), start(k + 1)); + let Some((o, tail)) = std::mem::take(&mut rest).split_at_mut_checked(to - from) else { break }; + rest = tail; + let its = items.get(from..to).unwrap_or_default(); + if k == 0 { + first = Some((o, its)); + continue; + } + let run = &run; + match std::thread::Builder::new().spawn_scoped(s, move || run(from, its, o)) { + Ok(_) => used += 1, + Err(_) => unstarted.push(k), + } + } + if let Some((o, its)) = first { + run(0, its, o); + } + used + }); + for (from, to) in unstarted.into_iter().map(|k| (start(k), start(k + 1))) { + if let (Some(o), Some(its)) = (out.get_mut(from..to), items.get(from..to)) { + run(from, its, o); + } + } + (out, used) +} + // ---------- Outline Stroke ---------- /// Can Outline Stroke turn `st` into filled art? diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 1397357061..b587740744 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -441,6 +441,98 @@ fn offset_open_path_whose_ends_meet_grows_the_shape() { assert_eq!(path_of(&s, r[0]).0.subpaths.len(), 1); } +/// The ids of the objects in the first layer, back to front. +fn first_layer(s: &Session) -> Vec { + s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +/// Offset Path of several objects at once: each result goes directly above its object and takes +/// the next ids in the objects' order, a group gives a group of its paths' offsets with their +/// styles, a compound path gives a compound path, an inset that leaves nothing and type give +/// nothing, and one undo gives the objects back. +#[test] +fn offset_path_of_several_objects_keeps_their_order() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 40.0, 0.0, 10.0, 10.0); + let c = rect(&mut s, 60.0, 0.0, 10.0, 10.0); + set_fill(&mut s, b, Color::rgb(1.0, 0.0, 0.0)); + set_fill(&mut s, c, Color::rgb(0.0, 0.0, 1.0)); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let tiny = rect(&mut s, 100.0, 0.0, 4.0, 4.0); + let outer = rect(&mut s, 200.0, 0.0, 40.0, 40.0); + let inner = rect(&mut s, 210.0, 10.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [outer.0, inner.0]})).unwrap(); + let cp = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let t = NodeId(s.execute("text.create", &json!({"x": 300, "y": 10, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + let before = first_layer(&s); + assert_eq!(before, [a, g, tiny, cp, t]); + let first = s.doc().unwrap().doc.peek_next_id(); + s.execute("select.set", &json!({"ids": [a.0, g.0, tiny.0, cp.0, t.0]})).unwrap(); + let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": -3, "joins": "miter"})).unwrap()); + // a's offset, then b's and c's and their group, then the compound path and its two subpaths. + assert_eq!(r, [NodeId(first), NodeId(first + 3), NodeId(first + 4)]); + assert_eq!(first_layer(&s), [a, r[0], g, r[1], tiny, cp, r[2], t]); + assert_eq!(s.doc().unwrap().selection.objects, r); + assert!(close(bounds(&s, r[0]), Rect::new(3.0, 3.0, 17.0, 17.0), 1e-2), "{:?}", bounds(&s, r[0])); + let group = node(&s, r[1]); + assert!(matches!(group.kind, NodeKind::Group { .. }), "{:?}", group.kind); + let kids = group.children().unwrap(); + assert_eq!(kids.iter().map(|k| k.id).collect::>(), [NodeId(first + 1), NodeId(first + 2)]); + assert_eq!(kids[0].appearance.fill_paint(), Paint::solid(Color::rgb(1.0, 0.0, 0.0))); + assert_eq!(kids[1].appearance.fill_paint(), Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + let rings = node(&s, r[2]); + assert!(matches!(rings.kind, NodeKind::Compound { .. }), "{:?}", rings.kind); + assert!(close(bounds(&s, r[2]), Rect::new(203.0, 3.0, 237.0, 37.0), 1e-2), "{:?}", bounds(&s, r[2])); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(first_layer(&s), before); +} + +/// Offset Path works out the offsets of several paths on more than one thread, and gives the +/// results in the paths' order. +#[test] +fn offset_path_works_on_several_threads_in_order() { + let seen = std::sync::Mutex::new(vec![]); + let items: Vec = (0..8).collect(); + let work = |i: &usize| { + if let Ok(mut seen) = seen.lock() { + seen.push(std::thread::current().id()); + } + i * 2 + }; + let (out, used) = crate::cmd::pathops::ordered_map(&items, 4, work, |_| false); + assert_eq!(out, (0..8).map(|i| Some(i * 2)).collect::>()); + assert_eq!(used, 4); + let threads: std::collections::HashSet<_> = seen.into_inner().unwrap().into_iter().collect(); + assert_eq!(threads.len(), 4); + // A count just past the threads still uses every thread. + let (out, used) = crate::cmd::pathops::ordered_map(&items[..5], 4, |i| i * 2, |_| false); + assert_eq!(out, (0..5).map(|i| Some(i * 2)).collect::>()); + assert_eq!(used, 4); + // One item, or one thread, is worked on here. + let (out, used) = crate::cmd::pathops::ordered_map(&items[..1], 4, |i| i * 2, |_| false); + assert_eq!((out, used), (vec![Some(0)], 1)); + let (out, used) = crate::cmd::pathops::ordered_map(&items, 1, |i| i * 2, |_| false); + assert_eq!(used, 1); + assert_eq!(out.len(), 8); +} + +/// Once a result stops the work (an offset that fails), the paths after it are left out, and every +/// path before it has its result, so the first failure in the paths' order is the one reported. +#[test] +fn offset_path_stops_after_the_first_failure() { + let items: Vec = (0..8).collect(); + let (out, _) = crate::cmd::pathops::ordered_map(&items, 1, |i| *i, |r| *r == 2 || *r == 5); + assert_eq!(out, [Some(0), Some(1), Some(2), None, None, None, None, None]); + for threads in [2, 4, 8] { + let (out, _) = crate::cmd::pathops::ordered_map(&items, threads, |i| *i, |r| *r == 2 || *r == 5); + assert_eq!(out[..3], [Some(0), Some(1), Some(2)], "{threads} threads"); + let first = out.iter().position(|r| r.is_some_and(|r| r == 2 || r == 5)); + assert_eq!(first, Some(2), "{threads} threads"); + } +} + #[test] fn outline_stroke_of_line() { let mut s = session(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9a9b0d06ed..f00550dff4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1749,6 +1749,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Pathfinder › Merge and the `pathfinder.merge` group effect find the faces of every fill in a few contour passes over the arrangement, as Trim and Crop do, instead of one pass for each distinct fill. The output paths and their order are the same. With 8,000 squares that do not touch, each with its own fill, Merge takes 72 to 107 ms instead of 17 to 32 s (release build). The Pathfinder panel, Offset Path, Clean Up, Divide Objects Below, Make and Release Blend, Envelope Distort's Make and Release, Repeat (Radial, Grid, Mirror and Release), Vector Halftone, New and Redefine Symbol, Delete Symbol, erasing with the Symbol Sprayer, Rasterize, Convert to Artboards, Flatten Transparency, Clear Guides, Shape Builder, Live Paint, Release Image Trace, Make and Release Opacity Mask, Delete with direct-selected anchor points, Remove Anchor Points, Cut Path, and the Shaper, Knife, Eraser, Path Eraser, Line Cut, Rectangle Cut, Mirror & Cut and Blob Brush tools add and remove objects in one pass over each layer or group they change, and Outline Stroke and Expand write each new object in the place of the object it replaces (#1429). Offset Path looks up the segments near each candidate hole or island in a tree of the source path's segment bounds when it decides whether to drop that contour, instead of testing the bounds of every segment. The output paths are the same. On compound and open paths of 25,000 to 40,000 anchors with 6,400 to 11,976 candidate contours, that check takes 11 to 13 ms instead of 140 to 649 ms (medians of five interleaved runs). The limit on overlapping segment pairs is the same, so a path that stops with "Offset Path: the path is too complex to offset" still stops there. + Offset Path on several selected paths, or on a group of them, works out their offsets on as many threads as the computer has logical CPUs (one thread on the web and for a single path), and then makes the new objects one after another in the selection's order. The new objects, their ids, their stacking, the selection and the undo step are the same as when the paths were offset one at a time, and when more than one path fails, the error is the one for the first of them in that order (`tests::pathops::offset_path_of_several_objects_keeps_their_order`, `tests::pathops::offset_path_works_on_several_threads_in_order`, `tests::pathops::offset_path_stops_after_the_first_failure`). Finding the distinct regions of an arrangement lists the shapes that cover each region instead of keeping a flag for every shape, so that step's time follows how many shapes cover each region rather than how many shapes there are. Divide, Hard Mix, Soft Mix, Shape Builder, Flatten Transparency, trapping, Intertwine and the Pathfinder effects are among the commands that use that step. The regions, their order and the output are the same. Divide on 3,000 overlapping rectangles takes 0.84 to 1.13 billion CPU cycles on its thread instead of 1.25 to 1.46 billion (dev build, six runs of each, alternating, while other builds were running). The contour passes of the two-path boolean operations, Offset Path, compound shapes and Intertwine test the list of shapes that cover each face instead of a flag for every shape, so each test's time follows how many shapes cover the face rather than how many shapes there are. The contours, their order and the output are the same. The many-shape boolean that compound shapes use takes 0.75 to 0.83 billion CPU cycles on its thread instead of 1.28 to 1.33 billion to unite 10,000 squares that do not touch, and 2.27 to 2.30 billion instead of 2.43 to 2.47 billion for 1,500 members of two squares each over 3,000 overlapping squares (dev build, six runs of each, alternating, while other builds were running). Pathfinder › Unite and the other commands that unite filled paths sweep a single input once instead of twice when its own sweep neither splits nor drops any of its segments and no two of its segments lie within twice the sweep tolerance. The output is the same. Unite on one compound path of 4,000 rings takes 485 to 542 ms instead of 872 to 1,008 ms, and on one zigzag polygon of 20,000 teeth 70 to 76 ms instead of 118 to 130 ms (release build, medians of three alternating rounds of five runs, while other builds were running).