diff --git a/ASSETS.md b/ASSETS.md
index dbdd8b84d8..2c7a07478b 100644
--- a/ASSETS.md
+++ b/ASSETS.md
@@ -129,6 +129,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-cap-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-center-hide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-center-show.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
+| `assets/icons/dc-circle-points.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a circle with three dots on its edge) | MIT OR Apache-2.0 | |
| `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | |
diff --git a/ROADMAP.md b/ROADMAP.md
index b2ebdb0545..05862568d6 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -141,6 +141,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
+- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
diff --git a/assets/icons/dc-circle-points.svg b/assets/icons/dc-circle-points.svg
new file mode 100644
index 0000000000..46da3a3401
--- /dev/null
+++ b/assets/icons/dc-circle-points.svg
@@ -0,0 +1 @@
+
diff --git a/crates/brush/src/calli.rs b/crates/brush/src/calli.rs
index 888294356c..69a8463c92 100644
--- a/crates/brush/src/calli.rs
+++ b/crates/brush/src/calli.rs
@@ -9,7 +9,6 @@
//! the stroke with what the pen recorded on it (`StrokeLayer::pressure`, `tilt`, `bearing` and
//! `rotation`): the sweep is sampled densely and each sample takes the nib for the pen there.
-use vectorcraft_color::Paint;
use vectorcraft_doc::{Node, StrokeLayer};
use vectorcraft_geom::{BezPath, PathData, Point, SubPath, Vec2};
@@ -198,7 +197,70 @@ fn offset_track(t: &Track, d: f64, trim0: f64, trim1: f64) -> Option {
Some(bp)
}
-pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, name: &str) -> Vec {
+/// A strand that follows the recorded pen pose. Pressure and tilt change its spread; bearing and
+/// barrel rotation turn that spread in the path's local frame. Original path corners are included
+/// in the samples so a turn is not rounded away by the pose sampling interval.
+fn posed_bristle_track(
+ t: &Track,
+ d: f64,
+ trim0: f64,
+ trim1: f64,
+ size: f64,
+ stroke: &StrokeLayer,
+ varies: bool,
+) -> Option<(BezPath, Vec<(f64, f64)>)> {
+ let l = t.len();
+ let (s0, s1) = (trim0.clamp(0.0, l), (l - trim1).clamp(0.0, l));
+ if s1 - s0 < 1e-6 {
+ return None;
+ }
+ let steps = if varies { ((s1 - s0) / (size * 0.2).max(0.25)).ceil().clamp(1.0, MAX_STEPS) as usize } else { 1 };
+ let mut positions: Vec = (0..=steps).map(|i| s0 + (s1 - s0) * i as f64 / steps as f64).collect();
+ positions.extend(t.cum.iter().copied().filter(|&s| s > s0 && s < s1));
+ positions.sort_by(f64::total_cmp);
+ positions.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
+ let mut path = BezPath::new();
+ // Distance along the posed strand -> fraction along the original, untrimmed path.
+ let mut source = Vec::with_capacity(positions.len());
+ let mut previous: Option = None;
+ let mut distance = 0.0;
+ for (i, s) in positions.into_iter().enumerate() {
+ let pen = PenAt::of(stroke, s / l);
+ let pressure = pen.control(Variation::Pressure).unwrap_or(0.5);
+ let tilt = pen.control(Variation::Tilt).unwrap_or(0.5);
+ let bearing = pen.control(Variation::Bearing).unwrap_or(0.5);
+ let rotation = pen.control(Variation::Rotation).unwrap_or(0.5);
+ let spread = d * (0.5 + pressure) * (1.25 - 0.5 * tilt);
+ let angle = std::f64::consts::TAU * (bearing + rotation - 1.0);
+ let p = t.map(s + spread * angle.sin(), spread * angle.cos());
+ if i == 0 {
+ path.move_to(p)
+ } else {
+ path.line_to(p)
+ }
+ if let Some(previous) = previous {
+ distance += previous.distance(p);
+ }
+ source.push((distance, s / l));
+ previous = Some(p);
+ }
+ Some((path, source))
+}
+
+fn source_fraction(source: &[(f64, f64)], distance: f64) -> f64 {
+ let next = source.partition_point(|(d, _)| *d < distance);
+ if next == 0 {
+ return source.first().map_or(0.0, |(_, f)| *f);
+ }
+ if next >= source.len() {
+ return source.last().map_or(1.0, |(_, f)| *f);
+ }
+ let (d0, f0) = source[next - 1];
+ let (d1, f1) = source[next];
+ if d1 - d0 < 1e-9 { f1 } else { f0 + (f1 - f0) * ((distance - d0) / (d1 - d0)) }
+}
+
+pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec {
let mut rng = Rng::new(seed_of(bp, name));
let size = b.size.max(0.1) * weight;
let strands = (3.0 + b.density.clamp(1.0, 100.0) / 100.0 * 13.0).round() as usize;
@@ -210,6 +272,13 @@ pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, nam
let wobble = (100.0 - b.stiffness.clamp(1.0, 100.0)) / 100.0;
let ragged = b.length.clamp(25.0, 300.0) / 100.0;
let opacity = (b.opacity.clamp(1.0, 100.0) / 100.0) as f32;
+ let posed = stroke.pressure.is_some() || stroke.tilt.is_some() || stroke.bearing.is_some() || stroke.rotation.is_some();
+ let varies = |points: &[(f64, f64)]| points.first().is_some_and(|(_, first)| points.iter().any(|(_, value)| (value - first).abs() > 1e-6));
+ let pressure_varies = stroke.pressure.as_ref().is_some_and(|p| varies(&p.points));
+ let pose_varies = pressure_varies
+ || stroke.tilt.as_ref().is_some_and(|p| varies(&p.points))
+ || stroke.bearing.as_ref().is_some_and(|p| varies(&p.points))
+ || stroke.rotation.as_ref().is_some_and(|p| varies(&p.points));
let mut out = vec![];
for t in tracks(bp, tolerance(size)) {
let l = t.len();
@@ -220,14 +289,37 @@ pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, nam
let edge = 1.0 - lane.abs();
let trim = |r: &mut Rng| r.unit() * ragged * size * (1.2 - edge) * 0.8;
let (t0, t1) = (trim(&mut rng), trim(&mut rng));
- let Some(sp) = offset_track(&t, off, t0.min(l * 0.3), t1.min(l * 0.3)) else { continue };
+ let (t0, t1) = (t0.min(l * 0.3), t1.min(l * 0.3));
+ let sp = if posed {
+ posed_bristle_track(&t, off, t0, t1, size, stroke, pose_varies)
+ } else {
+ offset_track(&t, off, t0, t1).map(|path| (path, Vec::new()))
+ };
+ let Some((sp, source)) = sp else { continue };
let w = thick * (0.6 + 0.4 * edge) * rng.range(0.8, 1.2);
- let nib = Nib::new(0.0, 1.0, w);
- let subs: Vec = tracks(&sp, tolerance(w)).iter().flat_map(|tt| sweep(tt, &|_| nib, None)).collect();
+ let subs: Vec = tracks(&sp, tolerance(w))
+ .iter()
+ .flat_map(|tt| {
+ if posed {
+ sweep(
+ tt,
+ &|f| {
+ let original_fraction = source_fraction(&source, f * tt.len());
+ let pressure = PenAt::of(stroke, original_fraction).control(Variation::Pressure).unwrap_or(0.5);
+ Nib::new(0.0, 1.0, w * (0.5 + pressure))
+ },
+ pressure_varies.then_some((tt.len() / MAX_STEPS).max(0.25)),
+ )
+ } else {
+ let nib = Nib::new(0.0, 1.0, w);
+ sweep(tt, &|_| nib, None)
+ }
+ })
+ .collect();
if subs.is_empty() {
continue;
}
- let mut n = filled(PathData::new(subs), paint);
+ let mut n = filled(PathData::new(subs), &stroke.paint);
n.opacity = (opacity * rng.range(0.7, 1.0) as f32).clamp(0.0, 1.0);
out.push(n);
}
diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs
index 7129279b31..43336f93dd 100644
--- a/crates/brush/src/lib.rs
+++ b/crates/brush/src/lib.rs
@@ -1084,7 +1084,7 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok
let w = if stroke.width > 0.0 { stroke.width } else { 1.0 };
let mut out = match &brush.kind {
BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name),
- BrushKind::Bristle(b) => calli::bristle(b, bp, w, &stroke.paint, &brush.name),
+ BrushKind::Bristle(b) => calli::bristle(b, bp, w, stroke, &brush.name),
BrushKind::Art(a) => warp::art(a, bp, w, stroke),
BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name),
BrushKind::Pattern(p) => warp::pattern(p, bp, w),
@@ -1245,6 +1245,14 @@ pub fn has_brush(n: &Node) -> bool {
n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && s.visible))
}
+/// Does `stroke` draw with a brush of `lib` (the document's [`library`])? [`stroke_pieces`] sizes
+/// brush art from the brush and the stroke weight and does not read the stroke's width profile, so
+/// the profile does not change what such a stroke draws. A stroke without a brush, or one that
+/// names a brush `lib` lacks, draws a plain stroke, which follows the profile.
+pub fn keeps_brush_size(lib: &[Brush], stroke: &StrokeLayer) -> bool {
+ stroke.brush.as_deref().is_some_and(|name| lib.iter().any(|b| b.name == name))
+}
+
/// How far brush art can paint past the visual box of `n`: `16 × w + 8`, where `w` is the widest
/// stroke of `n` (at least 1), when `n` has a visible brushed stroke with a paint; 0 when it has
/// none, as a brushed stroke without a paint draws no brush art. This is the room the renderer and
diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs
index 437ec4028f..fdec056730 100644
--- a/crates/brush/src/tests.rs
+++ b/crates/brush/src/tests.rs
@@ -827,6 +827,86 @@ fn bristle_makes_translucent_strands() {
assert!(bb.height() <= 6.0 * 1.3 && bb.height() >= 3.0, "{bb:?}");
}
+#[test]
+fn bristle_pen_pressure_changes_its_footprint() {
+ let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) };
+ let render = |pressure| {
+ let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, pressure), (1.0, pressure)] }), ..stroke(1.0) };
+ stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s)
+ };
+ let light = render(0.0);
+ let heavy = render(1.0);
+ assert_eq!(light.len(), heavy.len());
+ assert!(bounds(&heavy).height() > bounds(&light).height() * 1.8);
+}
+
+#[test]
+fn bristle_pen_pressure_is_sampled_along_the_stroke() {
+ let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) };
+ let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) };
+ let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s);
+ let mut points = Vec::new();
+ for n in &out {
+ all_points(n, &mut points);
+ }
+ let early = points.iter().filter(|p| p.x > 20.0 && p.x < 60.0).map(|p| p.y.abs()).fold(0.0_f64, f64::max);
+ let late = points.iter().filter(|p| p.x > 140.0 && p.x < 180.0).map(|p| p.y.abs()).fold(0.0_f64, f64::max);
+ assert!(late > early * 1.4, "spread along stroke: {early} -> {late}");
+}
+
+#[test]
+fn trimmed_bristle_strands_read_pressure_where_they_begin() {
+ let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle { size: 20.0, length: 300.0, ..Default::default() }) };
+ let render = |points| {
+ let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points }), ..stroke(1.0) };
+ stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 80.0, 0.0), &s)
+ };
+ let ramp = render(vec![(0.0, 0.0), (1.0, 1.0)]);
+ let neutral = render(vec![(0.0, 0.5), (1.0, 0.5)]);
+ assert_eq!(ramp.len(), neutral.len());
+ let start = |n: &Node| {
+ let anchors = &n.path_data().unwrap().subpaths[0].anchors;
+ let first = anchors[0].p;
+ let opposite = anchors[anchors.len() - 16].p;
+ (first.x, (first.y - opposite.y).abs())
+ };
+ let mut checked = false;
+ for (ramp, neutral) in ramp.iter().zip(&neutral) {
+ let (x, width) = start(ramp);
+ if x < 12.0 {
+ continue;
+ }
+ let (_, neutral_width) = start(neutral);
+ let expected = 0.5 + x / 80.0;
+ assert!(width / neutral_width > expected - 0.08, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}");
+ checked = true;
+ }
+ assert!(checked, "at least one strand begins past the pressure ramp's first eighth");
+}
+
+#[test]
+fn bristle_pen_orientation_changes_its_footprint() {
+ let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) };
+ let render = |tilt, bearing, rotation| {
+ let flat = |x| vec![(0.0, x), (1.0, x)];
+ let s = StrokeLayer {
+ tilt: Some(vectorcraft_doc::PressureProfile { points: flat(tilt) }),
+ bearing: Some(vectorcraft_doc::AngleProfile { points: flat(bearing) }),
+ rotation: Some(vectorcraft_doc::AngleProfile { points: flat(rotation) }),
+ ..stroke(1.0)
+ };
+ stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s)
+ };
+ let neutral = bounds(&render(0.5, 0.0, 0.0)).height();
+ let flat = bounds(&render(1.0, 0.0, 0.0)).height();
+ let upright = bounds(&render(0.0, 0.0, 0.0)).height();
+ let bearing = bounds(&render(0.5, 90.0, 0.0)).height();
+ let rotation = bounds(&render(0.5, 0.0, 90.0)).height();
+ assert!(flat > neutral && neutral > upright, "tilt: {flat} > {neutral} > {upright}");
+ assert!(bearing < neutral * 0.7, "bearing: {bearing} vs {neutral}");
+ assert!(rotation < neutral * 0.7, "rotation: {rotation} vs {neutral}");
+}
+
#[test]
fn tints_colorization_uses_stroke_colour() {
let b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs
index eafb4616f1..8aefe61a0d 100644
--- a/crates/cad/src/lib.rs
+++ b/crates/cad/src/lib.rs
@@ -7,6 +7,8 @@
//! hatches, type text entities or glyph outlines, and placed images image entities linked to PNG
//! or JPEG files the caller writes next to the drawing. Coordinates are y-up, in drawing units: `scale` units per
//! `unit` of the art, with the origin at the bottom-left corner of [`DxfOptions::region`].
+//! [`export_drawings`] writes one such drawing for each of several regions, applying the live
+//! effects once for all of them.
//!
//! What DXF can't hold (blending modes, opacity masks, raster effects, gradients, patterns,
//! clipping) is approximated or left out, and each such loss comes back as a warning.
@@ -436,18 +438,43 @@ pub const SCALE_RANGE: std::ops::RangeInclusive = 1e-6..=1e6;
/// Write `doc` as a DXF drawing with `opts`. Live geometry effects are applied first; template
/// layers, guides and hidden objects are left out.
pub fn export(doc: &Document, opts: &DxfOptions) -> Result {
+ Ok(export_drawings(doc, opts, &[(opts.region, opts.crop)])?.pop().unwrap_or_default())
+}
+
+/// Write `doc` as one DXF drawing for each `(region, crop)` of `drawings`, in order, each as
+/// [`export`] writes it with `opts` and that region and crop. Live geometry effects are applied
+/// once for all the drawings.
+pub fn export_drawings(doc: &Document, opts: &DxfOptions, drawings: &[(Rect, bool)]) -> Result, String> {
+ export_drawings_with(doc, opts, drawings, bake_for_drawings)
+}
+
+/// `doc` with its live geometry effects applied and its symbols' art placed, or `None` when
+/// nothing changes.
+fn bake_for_drawings(doc: &Document) -> Option {
+ // Symbols' art is placed without clipping, as the scene places it.
+ let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false };
+ vectorcraft_effects::bake_document_placing_symbols(doc, false, layers)
+}
+
+/// [`export_drawings`] with `bake` applying the live effects.
+fn export_drawings_with(
+ doc: &Document,
+ opts: &DxfOptions,
+ drawings: &[(Rect, bool)],
+ bake: impl Fn(&Document) -> Option,
+) -> Result, String> {
if !(opts.scale.is_finite() && SCALE_RANGE.contains(&opts.scale)) {
return Err(format!("scale must be a number from {} to {}, not {}", SCALE_RANGE.start(), SCALE_RANGE.end(), opts.scale));
}
- let r = opts.region;
- if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
+ if drawings.iter().any(|(r, _)| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())) {
return Err("the export region is not finite".into());
}
- // Symbols' art is placed without clipping, as the scene places it.
- let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false };
- let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers);
+ if drawings.is_empty() {
+ return Ok(vec![]);
+ }
+ let baked = bake(doc);
let doc = baked.as_ref().unwrap_or(doc);
- Ok(scene::Scene::new(doc, opts).run())
+ Ok(drawings.iter().map(|&(region, crop)| scene::Scene::new(doc, &DxfOptions { region, crop, ..opts.clone() }).run()).collect())
}
#[cfg(test)]
diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs
index dda09a0696..797223b688 100644
--- a/crates/cad/src/tests.rs
+++ b/crates/cad/src/tests.rs
@@ -1493,3 +1493,201 @@ fn export_bytes_match_shared_writer_goldens() {
assert_eq!(got, expected, "DXF bytes changed versus {}", path.display());
}
}
+
+/// One drawing written by applying the live effects for it alone and walking the result, as each
+/// drawing of a multi-drawing export was written before [`export_drawings`].
+fn export_baking_alone(doc: &Document, opts: &DxfOptions) -> DxfOutput {
+ let baked = crate::bake_for_drawings(doc);
+ crate::scene::Scene::new(baked.as_ref().unwrap_or(doc), opts).run()
+}
+
+/// A written drawing's bytes, linked images (name and bytes), warnings and setting notes.
+type Written = (Vec, Vec<(String, Vec)>, Vec, Vec);
+
+/// Every field of a written drawing, for comparing two.
+fn written(out: &DxfOutput) -> Written {
+ let images = out.images.iter().map(|i| (i.name.clone(), i.bytes.clone())).collect();
+ (out.bytes.clone(), images, out.warnings.clone(), out.setting_notes.clone())
+}
+
+/// A Transform effect that moves its object `x` pt right.
+fn moved_by(mut n: Node, x: f64) -> Node {
+ n.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": x}), visible: true });
+ n
+}
+
+/// A line moved by a Transform effect, an instance of a symbol whose art carries the same effect
+/// stained by its fill, a semi-transparent line in a blending mode, and a placed PNG image.
+fn drawings_doc() -> Document {
+ let png = craft_image_codecs::encode(
+ &craft_image_codecs::Image::from_raw(
+ 2,
+ 2,
+ craft_image_codecs::ChannelLayout::Rgba,
+ craft_image_codecs::SampleType::U8,
+ [0u8, 128, 255, 255].repeat(4),
+ )
+ .unwrap(),
+ craft_image_codecs::Format::Png,
+ &craft_image_codecs::EncodeOptions::default(),
+ )
+ .unwrap();
+ let mut d = doc_with(|d| {
+ let line = path(d, shapes::line((10.0, 10.0).into(), (20.0, 10.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0);
+ let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY });
+ instance.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0).into();
+ let mut faint = path(d, shapes::line((10.0, 90.0).into(), (190.0, 90.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0);
+ faint.opacity = 0.5;
+ faint.blend = vectorcraft_color::BlendMode::Multiply;
+ let im = ImageObject {
+ key: "raster-1".into(),
+ width: 2,
+ height: 2,
+ xf: Affine::translate((150.0, 20.0)) * Affine::scale(10.0),
+ link: None,
+ placement: Default::default(),
+ pixels: None,
+ };
+ vec![moved_by(line, 100.0), instance, faint, Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))]
+ });
+ let art = path(&mut d, shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
+ d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved_by(art, 20.0)) });
+ d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
+ d
+}
+
+#[test]
+fn drawings_apply_the_live_effects_once_and_match_drawings_written_alone() {
+ let d = drawings_doc();
+ assert!(crate::bake_for_drawings(&d).is_some(), "the document has live effects to apply");
+ // The left and right halves cropped, the whole page uncropped, and a region off the page.
+ let drawings = [
+ (Rect::new(0.0, 0.0, 100.0, 100.0), true),
+ (Rect::new(100.0, 0.0, 200.0, 100.0), true),
+ (Rect::new(0.0, 0.0, 200.0, 100.0), false),
+ (Rect::new(300.0, 0.0, 400.0, 100.0), true),
+ ];
+ // With every option, and with images and hatches left out (which adds setting notes).
+ let all_in = opts(&d);
+ for o in [all_in.clone(), DxfOptions { include_images: false, include_hatches: false, ..all_in }] {
+ let bakes = std::cell::Cell::new(0);
+ let outs = crate::export_drawings_with(&d, &o, &drawings, |doc| {
+ bakes.set(bakes.get() + 1);
+ crate::bake_for_drawings(doc)
+ })
+ .unwrap();
+ assert_eq!(bakes.get(), 1, "the live effects are applied once for every drawing");
+ assert_eq!(outs.len(), drawings.len());
+ for ((region, crop), out) in drawings.iter().zip(&outs) {
+ let alone = export_baking_alone(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() });
+ assert_eq!(written(out), written(&alone), "the drawing over {region:?}, crop {crop}");
+ let one = export(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() }).unwrap();
+ assert_eq!(written(&one), written(&alone), "export over {region:?}, crop {crop}");
+ }
+ let public: Vec<_> = export_drawings(&d, &o, &drawings).unwrap().iter().map(written).collect();
+ assert_eq!(public, outs.iter().map(written).collect::>());
+ // The halves hold different art, the left half a line with losses, and the region off the
+ // page nothing.
+ assert!(!entities(&outs[0]).is_empty() && !entities(&outs[1]).is_empty() && !outs[0].warnings.is_empty());
+ assert_ne!(outs[0].bytes, outs[1].bytes);
+ assert!(entities(&outs[3]).is_empty() && outs[3].images.is_empty());
+ if o.include_images {
+ assert_eq!(outs[2].images.len(), 1);
+ } else {
+ assert!(!outs[2].setting_notes.is_empty() && outs[2].images.is_empty());
+ }
+ }
+}
+
+#[test]
+fn drawings_are_checked_before_the_live_effects_are_applied() {
+ let d = drawings_doc();
+ let o = opts(&d);
+ let bakes = std::cell::Cell::new(0);
+ let count = |doc: &Document| {
+ bakes.set(bakes.get() + 1);
+ crate::bake_for_drawings(doc)
+ };
+ let page = (d.artboards[0].rect, false);
+ let off = (Rect::new(0.0, 0.0, f64::NAN, 100.0), false);
+ assert_eq!(crate::export_drawings_with(&d, &o, &[page, off], count).unwrap_err(), "the export region is not finite");
+ let e = crate::export_drawings_with(&d, &DxfOptions { scale: 0.0, ..o.clone() }, &[page], count).unwrap_err();
+ assert!(e.starts_with("scale must be a number"), "{e}");
+ assert!(crate::export_drawings_with(&d, &o, &[], count).unwrap().is_empty());
+ assert_eq!(bakes.get(), 0, "nothing is applied for drawings that are refused or for none");
+}
+
+/// The thread's time on the CPU in nanoseconds where Linux reports it, otherwise `None`.
+fn thread_cpu_ns() -> Option {
+ std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
+}
+
+/// Time a Use Artboards export of eight artboards whose art has live effects, written drawing by
+/// drawing with the effects applied for each (as before [`export_drawings`]) and with
+/// [`export_drawings`], alternating, seven times each, and check that both write the same
+/// drawings. Prints the median of each in milliseconds of the thread's CPU time (on Linux) and of
+/// wall-clock time.
+/// Run with `cargo test --release -p vectorcraft-cad --lib dxf_artboards_bake_perf -- --ignored --nocapture`.
+#[test]
+#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
+fn dxf_artboards_bake_perf() {
+ const BOARDS: usize = 8;
+ let mut d = Document::new(200.0 * BOARDS as f64, 200.0);
+ let layer = d.layers[0].id;
+ let effect = |id: &str, params: serde_json::Value| vectorcraft_doc::Effect { id: id.into(), params, visible: true };
+ let mut art = vec![];
+ for i in 0..50 {
+ let (x, y) = (f64::from(i % 10) * 5.0, f64::from(i / 10) * 5.0);
+ art.push(Arc::new(path(&mut d, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), Paint::None, Paint::solid(Color::BLACK), 0.5)));
+ }
+ let mut cell = Node::group(d.alloc_id(), art);
+ cell.appearance.effects.push(effect("distort.zigZag", serde_json::json!({"size": 1.0, "relative": false, "ridges": 4, "points": "smooth"})));
+ d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Cell".into(), art: Arc::new(cell) });
+ for b in 0..BOARDS {
+ let x0 = 200.0 * b as f64;
+ for i in 0..250 {
+ let (x, y) = (x0 + f64::from(i % 25) * 8.0, f64::from(i / 25) * 8.0);
+ let mut n = path(&mut d, shapes::ellipse(Rect::new(x, y, x + 6.0, y + 6.0)), Paint::None, Paint::solid(Color::BLACK), 0.5);
+ let params = serde_json::json!({"size": 1.0, "relative": false, "detail": 10.0, "points": "smooth", "seed": i});
+ n.appearance.effects.push(effect("distort.roughen", params));
+ d.insert(Some(layer), usize::MAX, n).unwrap();
+ }
+ for i in 0..20 {
+ let xf = Affine::translate((x0 + f64::from(i % 5) * 40.0, 100.0 + f64::from(i / 5) * 25.0));
+ let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Cell".into(), xf });
+ d.insert(Some(layer), usize::MAX, instance).unwrap();
+ }
+ }
+ let o = DxfOptions { unit: Unit::Points, ..DxfOptions::default() };
+ let drawings: Vec<(Rect, bool)> = (0..BOARDS).map(|b| (Rect::new(200.0 * b as f64, 0.0, 200.0 * (b + 1) as f64, 200.0), true)).collect();
+ let before = || drawings.iter().map(|&(region, crop)| export_baking_alone(&d, &DxfOptions { region, crop, ..o.clone() })).collect::>();
+ let after = || export_drawings(&d, &o, &drawings).unwrap();
+ let time = |f: &dyn Fn() -> Vec| {
+ let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now());
+ let outs = f();
+ let wall = wall.elapsed().as_secs_f64() * 1000.0;
+ let cpu = cpu.zip(thread_cpu_ns()).map(|(a, b)| (b - a) as f64 / 1e6);
+ (outs, cpu, wall)
+ };
+ let (mut runs_before, mut runs_after) = (vec![], vec![]);
+ for _ in 0..7 {
+ let (a, cpu_a, wall_a) = time(&before);
+ let (b, cpu_b, wall_b) = time(&after);
+ assert_eq!(a.len(), BOARDS);
+ assert_eq!(a.iter().map(written).collect::>(), b.iter().map(written).collect::>(), "both write the same drawings");
+ runs_before.push((cpu_a, wall_a));
+ runs_after.push((cpu_b, wall_b));
+ }
+ let median = |runs: &[(Option, f64)], cpu: bool| {
+ let mut v: Vec = runs.iter().filter_map(|r| if cpu { r.0 } else { Some(r.1) }).collect();
+ v.sort_by(f64::total_cmp);
+ v.get(v.len() / 2).copied()
+ };
+ for (name, runs) in [("drawing by drawing", &runs_before), ("export_drawings", &runs_after)] {
+ println!(
+ "{name}: {BOARDS} artboards, median CPU {:?} ms, median wall {:?} ms; runs (CPU ms, wall ms) {runs:?}",
+ median(runs, true),
+ median(runs, false)
+ );
+ }
+}
diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs
index 2fec3067d0..1bc134afb0 100644
--- a/crates/color/src/cms.rs
+++ b/crates/color/src/cms.rs
@@ -347,7 +347,9 @@ pub fn profiles_generation() -> u64 {
/// Profile `name` as an ICC file to embed in an export: any RGB or CMYK profile of [`profiles`]
/// (by its current or legacy name), or [`GRAY`]. Built-in profiles are written in code from the
/// CMS: the RGB spaces from their primaries, the CMYK spaces as lookup tables sampled from their
-/// model (both directions, perceptual and relative colorimetric, Lab PCS); a profile the user
+/// model (both directions, perceptual and relative colorimetric, Lab PCS, with the model's paper
+/// as the media white point; the colorimetric Lab → CMYK table without black-point
+/// compensation, the perceptual and saturation ones with it); a profile the user
/// loaded is the file it came from. Cached.
pub fn icc_bytes(name: &str) -> Result, CmsError> {
static CACHE: Mutex)>> = Mutex::new(Vec::new());
@@ -361,8 +363,17 @@ pub fn icc_bytes(name: &str) -> Result, CmsError> {
let bytes: Arc<[u8]> = if name == GRAY {
icc::encode(&icc::gray_profile(name))?
} else if BUILTIN_CMYK.contains(&name) {
- let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() })?;
- icc::encode(&icc::cmyk_profile(name, |c| cms.cmyk_to_lab(c), |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
+ // The perceptual and saturation tables map the shadows with black-point compensation; the
+ // colorimetric table is the inverse of the CMYK → Lab table, without it.
+ let mapped = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..ColorSettings::default() })?;
+ let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..ColorSettings::default() })?;
+ let paper = match &cms.cmyk {
+ CmykSpace::Generic(g) => g.paper_xyz(),
+ CmykSpace::Device | CmykSpace::Icc(_) => lab::D50,
+ };
+ let to_lab = |c| cms.cmyk_to_lab(c);
+ let shadows = |l| mapped.lab_to_cmyk(l, Intent::RelativeColorimetric);
+ icc::encode(&icc::cmyk_profile(name, paper, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
} else {
icc::builtin_rgb_bytes(name)?
}
diff --git a/crates/color/src/cms/generic.rs b/crates/color/src/cms/generic.rs
index 3d532ac02a..16f251054b 100644
--- a/crates/color/src/cms/generic.rs
+++ b/crates/color/src/cms/generic.rs
@@ -133,6 +133,11 @@ pub struct GenericCmyk {
}
impl GenericCmyk {
+ /// Absolute XYZ (D50) of the paper.
+ pub fn paper_xyz(&self) -> [f32; 3] {
+ self.paper_xyz
+ }
+
pub fn new(params: GenericCmykParams) -> Self {
let paper_xyz = lab_to_xyz(params.paper);
let mut prim = [D50; 16];
diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs
index ffddd6c955..8fc287ae23 100644
--- a/crates/color/src/cms/icc.rs
+++ b/crates/color/src/cms/icc.rs
@@ -446,11 +446,20 @@ const B2A_GRID: usize = 17;
const GAMUT_GRID: usize = 9;
/// A CMYK output profile sampled from a conversion: `to_lab` (CMYK → media-relative Lab) in a
-/// 9⁴ table, `from_lab` (Lab → CMYK, gamut-mapped) in a 17³ table, Lab PCS (ICC v4 encoding).
+/// 9⁴ table, and Lab → CMYK in 17³ tables, Lab PCS (ICC v4 encoding): `mapped` (gamut-mapped,
+/// with black-point compensation) for the perceptual and saturation intents, `colorimetric` (the
+/// colorimetric inverse of `to_lab`) for the colorimetric intents and the gamut tag.
/// It carries every tag ICC.1 requires of an output profile: the tables for all three intents
/// and the gamut tag (Windows rejects a CMYK profile without them, so Photos couldn't show a CMYK
-/// TIFF that embedded one, #2707).
-pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, from_lab: impl Fn(lab::Lab) -> [f32; 4]) -> ColorProfile {
+/// TIFF that embedded one, #2707). The media white point is `paper` (absolute XYZ, D50), which
+/// the ICC-absolute colorimetric intent reproduces.
+pub(super) fn cmyk_profile(
+ name: &str,
+ paper: [f32; 3],
+ to_lab: impl Fn([f32; 4]) -> lab::Lab,
+ mapped: impl Fn(lab::Lab) -> [f32; 4],
+ colorimetric: impl Fn(lab::Lab) -> [f32; 4],
+) -> ColorProfile {
let unit = |i: usize, n: usize| i as f32 / (n - 1) as f32;
let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0).round() as u16;
let mut a2b = Vec::with_capacity(A2B_GRID.pow(4) * 3);
@@ -459,17 +468,21 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr
let l = to_lab(cmyk);
a2b.extend([l.l / 100.0, (l.a + 128.0) / 255.0, (l.b + 128.0) / 255.0].map(q));
}
- let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4);
- for i in 0..B2A_GRID.pow(3) {
- let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID));
- b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q));
- }
+ let b2a_of = |from_lab: &dyn Fn(lab::Lab) -> [f32; 4]| {
+ let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4);
+ for i in 0..B2A_GRID.pow(3) {
+ let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID));
+ b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q));
+ }
+ b2a
+ };
+ let (b2a_mapped, b2a) = (b2a_of(&mapped), b2a_of(&colorimetric));
// Gamut: 0 where a colour separates and comes back within a ΔE of 3, else out of gamut.
let mut gamut = Vec::with_capacity(GAMUT_GRID.pow(3));
for i in 0..GAMUT_GRID.pow(3) {
let [l, a, b] = [2, 1, 0].map(|d| unit(i / GAMUT_GRID.pow(d) % GAMUT_GRID, GAMUT_GRID));
let want = lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0);
- gamut.push(if lab::delta_e2000(want, to_lab(from_lab(want))) <= 3.0 { 0 } else { u16::MAX });
+ gamut.push(if lab::delta_e2000(want, to_lab(colorimetric(want))) <= 3.0 { 0 } else { u16::MAX });
}
let identity = |n: usize| vec![ToneReprCurve::Parametric(vec![1.0]); n];
let table = |inputs: usize, outputs: usize, grid: usize, clut: Vec| {
@@ -490,6 +503,7 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr
})
};
let a2b = table(4, 3, A2B_GRID, a2b);
+ let b2a_mapped = table(3, 4, B2A_GRID, b2a_mapped);
let b2a = table(3, 4, B2A_GRID, b2a);
let gamut = table(3, 1, GAMUT_GRID, gamut);
let mut p = ColorProfile::default();
@@ -498,12 +512,12 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr
p.pcs = DataColorSpace::Lab;
p.rendering_intent = RenderingIntent::RelativeColorimetric;
p.white_point = moxcms::WHITE_POINT_D50.to_xyzd();
- p.media_white_point = Some(p.white_point);
+ p.media_white_point = Some(moxcms::Xyzd::new(f64::from(paper[0]), f64::from(paper[1]), f64::from(paper[2])));
p.lut_a_to_b_perceptual = Some(a2b.clone());
p.lut_a_to_b_saturation = Some(a2b.clone());
p.lut_a_to_b_colorimetric = Some(a2b);
- p.lut_b_to_a_perceptual = Some(b2a.clone());
- p.lut_b_to_a_saturation = Some(b2a.clone());
+ p.lut_b_to_a_perceptual = Some(b2a_mapped.clone());
+ p.lut_b_to_a_saturation = Some(b2a_mapped);
p.lut_b_to_a_colorimetric = Some(b2a);
p.gamut = Some(gamut);
labelled(p, name)
diff --git a/crates/color/src/cms/tests_icc.rs b/crates/color/src/cms/tests_icc.rs
index bee0f0f9fa..2c1d96638b 100644
--- a/crates/color/src/cms/tests_icc.rs
+++ b/crates/color/src/cms/tests_icc.rs
@@ -30,11 +30,62 @@ fn cmyk_profiles_convert_like_the_cms() {
let de = delta_e2000(lab::srgb_to_lab(want), lab::srgb_to_lab(got));
assert!(de < 2.5, "{name} {cmyk:?}: {want:?} vs {got:?} (ΔE {de})");
}
- // And back: an in-gamut colour separates to about the same inks.
- let srgb = cms.cmyk_to_srgb([0.1, 0.6, 0.8, 0.0], false);
- let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap();
- let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false);
- assert!(delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again)) < 3.0, "{back:?}");
+ // And back: in-gamut colours separate to inks that print them. The Lab → CMYK table is
+ // the colorimetric inverse of the CMYK → Lab table, with no black-point compensation.
+ for inks in [
+ [0.1, 0.6, 0.8, 0.0],
+ [0.5, 0.1, 0.3, 0.1],
+ [0.3, 0.3, 0.3, 0.2],
+ [0.05, 0.05, 0.4, 0.0],
+ [0.4, 0.3, 0.3, 0.6],
+ [0.6, 0.5, 0.5, 0.4],
+ [0.2, 0.2, 0.2, 0.8],
+ [0.0, 0.0, 0.0, 0.5],
+ ] {
+ let srgb = cms.cmyk_to_srgb(inks, false);
+ let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap();
+ let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false);
+ let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again));
+ assert!(de < 1.5, "{name} {inks:?}: {srgb:?} -> {back:?} -> {again:?} (ΔE {de})");
+ }
+ // The perceptual table keeps black-point compensation: source black separates to inks
+ // that print the press's black point, as the CMS separates it with compensation.
+ let compensated = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..Default::default() }).unwrap();
+ let want = compensated.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric);
+ let got = p.from_srgb([0.0; 3], Intent::Perceptual).unwrap();
+ let printed = |inks: &[f32]| cms.cmyk_to_lab([inks[0], inks[1], inks[2], inks[3]]);
+ let de = delta_e2000(printed(&want), printed(&got));
+ assert!(de < 1.5, "{name}: perceptual black {got:?} prints {:?}, want {want:?} ({:?})", printed(&got), printed(&want));
+ }
+}
+
+#[test]
+fn cmyk_profiles_separate_saturated_inks_back_without_clipping_to_srgb() {
+ // CMYK → PCS → CMYK through the profile's own colorimetric tables, by way of linear ProPhoto
+ // RGB, which holds every color these profiles print, so no display gamut clips the inks.
+ // Inks that print outside sRGB come back to inks that print the same color.
+ for name in BUILTIN_CMYK {
+ let p = IccProfile::from_bytes(None, &icc_bytes(name).unwrap()).unwrap();
+ let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..Default::default() }).unwrap();
+ for inks in
+ [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [1.0, 1.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [1.0, 0.0, 1.0, 0.0]]
+ {
+ let back = p.to_same_model_of(&p, &inks, Intent::RelativeColorimetric, false).unwrap();
+ let de = delta_e2000(cms.cmyk_to_lab(inks), cms.cmyk_to_lab([back[0], back[1], back[2], back[3]]));
+ // Within the ΔE of 3 that the gamut tag counts as reproduced.
+ assert!(de <= 3.0, "{name} {inks:?} -> {back:?} (ΔE {de})");
+ }
+ }
+}
+
+#[test]
+fn cmyk_profiles_carry_their_paper_as_the_media_white() {
+ let generic = generic::swop_like();
+ let p = parse(&icc_bytes(GENERIC_CMYK).unwrap());
+ let white = p.media_white_point.unwrap();
+ let paper = lab::lab_to_xyz(generic.paper);
+ for (got, want) in [white.x, white.y, white.z].iter().zip(paper) {
+ assert!((*got - f64::from(want)).abs() < 2e-3, "{white:?} vs {paper:?}");
}
}
@@ -116,9 +167,10 @@ fn black_point_compensation_maps_the_darkest_ink_to_rgb_black() {
let rich = [0.75, 0.68, 0.67, 0.9];
let (on, off) = (icc_cmyk(true).cmyk_to_rgb(rich, Intent::RelativeColorimetric), icc_cmyk(false).cmyk_to_rgb(rich, Intent::RelativeColorimetric));
// Without compensation the profile's black is a dark grey; with it, rich black goes most of
- // the way to RGB black (not all: it isn't quite the darkest ink the profile prints).
+ // the way to RGB black (not all: it isn't quite the darkest ink the profile prints, and the
+ // profile's Lab → CMYK table carries no compensation of its own).
assert!(off.iter().all(|v| *v > 0.1), "without: {off:?}");
- assert!(on.iter().zip(off).all(|(a, b)| *a < 0.08 && *a < b * 0.5), "with: {on:?}, without: {off:?}");
+ assert!(on.iter().zip(off).all(|(a, b)| *a < 0.09 && *a < b * 0.55), "with: {on:?}, without: {off:?}");
// The screen shows what an sRGB conversion writes, compensated alike.
let srgb = |bpc| {
let c = icc_cmyk(bpc);
diff --git a/crates/doc/src/appearance.rs b/crates/doc/src/appearance.rs
index 3bfba32f6a..737e10eb58 100644
--- a/crates/doc/src/appearance.rs
+++ b/crates/doc/src/appearance.rs
@@ -143,6 +143,11 @@ impl Appearance {
pub fn fill_paint(&self) -> Paint {
self.fill().map(|f| f.paint.clone()).unwrap_or(Paint::None)
}
+ /// Whether any visible fill has non-None paint. Unlike [`Self::fill`], this
+ /// includes lower fills in the stack; zero opacity still counts for selecting its geometry.
+ pub fn has_visible_fill(&self) -> bool {
+ self.items.iter().any(|item| matches!(item, AppearanceItem::Fill(fill) if fill.visible && !fill.paint.is_none()))
+ }
pub fn stroke_paint(&self) -> Paint {
self.stroke().map(|s| s.paint.clone()).unwrap_or(Paint::None)
}
diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs
index 3b415ef1ed..6a32a21bbc 100644
--- a/crates/doc/src/hit.rs
+++ b/crates/doc/src/hit.rs
@@ -82,8 +82,9 @@ impl Default for HitOptions {
}
}
-/// The shapes that an image's own fills and strokes paint, each with its fill rule and the fill or
-/// stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated
+/// The shapes that an image's own fills and strokes paint, or the fills and strokes of the art of a
+/// symbol instance whose own fill or stroke has a geometry effect, each with its fill rule and the
+/// fill or stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated
/// above this crate, so the engine registers one with [`set_image_paint`]. It looks up swatches and
/// patterns in the document it is given.
pub type ImagePaint = fn(Option<&Document>, &Node) -> Vec<(BezPath, FillRule, AppearanceItem)>;
@@ -97,10 +98,58 @@ pub fn set_image_paint(f: ImagePaint) {
let _ = IMAGE_PAINT.set(f);
}
-/// The shapes that the image `n`'s own fills and strokes paint ([`set_image_paint`]), none while
-/// nothing is registered.
-pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
- IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(doc, n))
+/// The shapes that [`ImagePaint`] gives for one object.
+type Painted = Vec<(BezPath, FillRule, AppearanceItem)>;
+
+/// The shapes that the image or symbol instance `n` paints with its geometry effects
+/// ([`set_image_paint`]), none while nothing is registered. The shapes of a symbol instance of
+/// `doc` with an effect on a fill or stroke are kept on this thread ([`PAINT_KEPT`]) and measured
+/// again when `n`, a symbol of `doc` or its 9-slice guides or natural size, a pattern of `doc`,
+/// its swatches or color groups, or the
+/// [`LiveInputs`] have changed since, and on every call while `n` or the document's symbols or
+/// patterns hold a placed document or the symbols hold an image ([`symbols_hold_images`]).
+pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Rc {
+ let Some(f) = IMAGE_PAINT.get() else { return Rc::default() };
+ let row_effects = || n.appearance.items.iter().any(|i| !i.effects().is_empty());
+ let Some(d) = doc.filter(|_| matches!(n.kind, NodeKind::SymbolInstance { .. }) && row_effects()) else {
+ return Rc::new(f(doc, n));
+ };
+ let inputs = live_inputs();
+ if let Some(painted) = kept(&PAINTED, d, n, inputs) {
+ return painted;
+ }
+ #[cfg(test)]
+ PAINT_EVALUATED.with(|c| c.set(c.get() + 1));
+ let painted = Rc::new(f(doc, n));
+ if !symbols_hold_images(d) {
+ let size = painted.iter().fold(0usize, |s, (bp, _, _)| s.saturating_add(1 + bp.elements().len()));
+ keep(&PAINTED, d, n, inputs, &painted, size, PAINT_KEPT);
+ }
+ painted
+}
+
+/// Does the art of a symbol of `doc` hold an image? The shapes its fills and strokes paint can
+/// follow its pixels, which change when its file is read again, so [`image_paint`] does not keep
+/// the shapes of an instance then.
+fn symbols_hold_images(doc: &Document) -> bool {
+ let mut image = false;
+ doc.symbols.iter().for_each(|s| s.art.walk(&mut |c| image |= matches!(c.kind, NodeKind::Image(_))));
+ image
+}
+
+/// How many symbol instances' shapes [`image_paint`] keeps on each thread: every click and every
+/// hover measures each instance whose fill or stroke has a geometry effect.
+const PAINT_KEPT: usize = 64;
+
+thread_local! {
+ /// The shapes [`image_paint`] keeps, the latest first.
+ static PAINTED: RefCell>> = const { RefCell::new(Vec::new()) };
+}
+
+#[cfg(test)]
+thread_local! {
+ /// How many symbol instances [`image_paint`] measured on this thread.
+ static PAINT_EVALUATED: std::cell::Cell = const { std::cell::Cell::new(0) };
}
/// One level of evaluation of a live object in a document, as the canvas draws it: type in an
@@ -127,21 +176,72 @@ fn live_inputs() -> u64 {
LIVE_ART.get().map_or(0, |(_, inputs)| inputs())
}
-/// A live object evaluated by [`live_art`] on this thread: the object, its document's symbols (by
-/// name and art), patterns, swatches and color groups and the [`LiveInputs`] as they were, the art
-/// and its [`art_size`].
-struct EvaluatedLive {
+/// An object evaluated by [`live_art`] or [`image_paint`] on this thread: the object, its
+/// document's symbols (by name and art), patterns, swatches and color groups, the document data
+/// that symbols' 9-slice guides and natural sizes are kept in, and the [`LiveInputs`] as they
+/// were, the result and its size.
+struct Evaluated {
node: Node,
symbols: Vec<(String, Arc)>,
patterns: Vec,
swatches: crate::Shared>,
swatch_groups: crate::Shared>,
+ unknown: crate::Shared>,
inputs: u64,
- art: Rc>,
+ art: Rc,
size: usize,
}
-impl EvaluatedLive {
+/// The evaluations kept on this thread in one store, the latest first.
+type Store = std::thread::LocalKey>>>;
+
+/// The evaluation of `n` in `doc` with inputs `inputs` that `store` keeps, moved to the front.
+fn kept(store: &'static Store, doc: &Document, n: &Node, inputs: u64) -> Option> {
+ store.with_borrow_mut(|kept| {
+ let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?;
+ let e = kept.remove(i);
+ let art = e.art.clone();
+ kept.insert(0, e);
+ Some(art)
+ })
+}
+
+/// Keep `art`, of size `size`, the evaluation of `n` in `doc` with inputs `inputs`, at the front
+/// of `store`, which keeps `most` evaluations whose sizes add up to [`LIVE_KEPT_SIZE`] at most.
+/// Nothing is kept when `art` alone is larger, or when `n` or the document's symbols or patterns
+/// hold a placed document ([`holds_placed`]).
+fn keep(store: &'static Store, doc: &Document, n: &Node, inputs: u64, art: &Rc, size: usize, most: usize) {
+ if size > LIVE_KEPT_SIZE || holds_placed(doc, n) {
+ return;
+ }
+ let e = Evaluated::new(doc, n, inputs, art, size);
+ store.with_borrow_mut(|kept| {
+ kept.insert(0, e);
+ kept.truncate(most);
+ let mut total = 0usize;
+ kept.retain(|e| {
+ total = total.saturating_add(e.size);
+ total <= LIVE_KEPT_SIZE
+ });
+ });
+}
+
+impl Evaluated {
+ /// `art`, of size `size`, the evaluation of `n` in `doc` with inputs `inputs`, as they are now.
+ fn new(doc: &Document, n: &Node, inputs: u64, art: &Rc, size: usize) -> Self {
+ Self {
+ node: n.clone(),
+ symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(),
+ patterns: doc.patterns.clone(),
+ swatches: doc.swatches.clone(),
+ swatch_groups: doc.swatch_groups.clone(),
+ unknown: doc.unknown.clone(),
+ inputs,
+ art: art.clone(),
+ size,
+ }
+ }
+
/// Is this the evaluation of `n` in `doc`, with inputs `inputs`, as they are now?
fn is_of(&self, doc: &Document, n: &Node, inputs: u64) -> bool {
self.inputs == inputs
@@ -151,6 +251,7 @@ impl EvaluatedLive {
&& self.patterns == doc.patterns
&& self.swatches == doc.swatches
&& self.swatch_groups == doc.swatch_groups
+ && self.unknown == doc.unknown
}
}
@@ -158,8 +259,9 @@ impl EvaluatedLive {
/// envelope's stroke band hits it again and again, and an envelope can hold a blend.
const LIVE_KEPT: usize = 4;
-/// Most [`art_size`] the evaluations [`live_art`] keeps on one thread add up to. Art larger than
-/// this is not kept.
+/// Most size the evaluations [`live_art`] keeps on one thread add up to ([`art_size`]), and the
+/// shapes [`image_paint`] keeps (each shape and its path elements). Art larger than this is not
+/// kept.
const LIVE_KEPT_SIZE: usize = 250_000;
/// The size of `art` for [`LIVE_KEPT_SIZE`]: its objects and the anchors of their paths.
@@ -184,52 +286,23 @@ fn holds_placed(doc: &Document, n: &Node) -> bool {
thread_local! {
/// The evaluations [`live_art`] keeps, the latest first.
- static EVALUATED: RefCell> = const { RefCell::new(Vec::new()) };
+ static EVALUATED: RefCell>>> = const { RefCell::new(Vec::new()) };
}
/// The art live object `n` of `doc` draws ([`set_live_art`]); [`crate::live::expand_live`] while
-/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc`, a pattern of
-/// `doc`, its swatches or color groups, or the [`LiveInputs`] have changed since, and on every
+/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc` or its 9-slice
+/// guides or natural size, a pattern of `doc`, its swatches or color groups, or the
+/// [`LiveInputs`] have changed since, and on every
/// click while it or the document's symbols or patterns hold a placed document ([`holds_placed`]).
fn live_art(doc: &Document, n: &Node) -> Rc> {
let inputs = live_inputs();
- let kept = EVALUATED.with_borrow_mut(|kept| {
- let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?;
- let e = kept.remove(i);
- let art = e.art.clone();
- kept.insert(0, e);
- Some(art)
- });
- if let Some(art) = kept {
+ if let Some(art) = kept(&EVALUATED, doc, n, inputs) {
return art;
}
#[cfg(test)]
LIVE_EVALUATED.with(|c| c.set(c.get() + 1));
let art = Rc::new(LIVE_ART.get().map_or_else(|| crate::live::expand_live(n), |(f, _)| f(Some(doc), n)));
- let size = art_size(&art);
- if size > LIVE_KEPT_SIZE || holds_placed(doc, n) {
- return art;
- }
- let symbols = doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect();
- let e = EvaluatedLive {
- node: n.clone(),
- symbols,
- patterns: doc.patterns.clone(),
- swatches: doc.swatches.clone(),
- swatch_groups: doc.swatch_groups.clone(),
- inputs,
- art: art.clone(),
- size,
- };
- EVALUATED.with_borrow_mut(|kept| {
- kept.insert(0, e);
- kept.truncate(LIVE_KEPT);
- let mut total = 0usize;
- kept.retain(|e| {
- total = total.saturating_add(e.size);
- total <= LIVE_KEPT_SIZE
- });
- });
+ keep(&EVALUATED, doc, n, inputs, &art, art_size(&art), LIVE_KEPT);
art
}
@@ -257,7 +330,7 @@ pub fn set_drawn_art(f: DrawnArt) {
/// The art of an object found by [`drawn`] (none, or one object), with what it was found from, and
/// the box round everything that art can paint.
struct EvaluatedDrawn {
- of: EvaluatedLive,
+ of: Evaluated>,
reach: Option,
}
@@ -310,7 +383,8 @@ fn plain(mask: bool, f: impl FnOnce() -> T) -> T {
/// nothing is registered, while a [`DrawnOff`] guard lives, for objects whose art is not evaluated
/// ([`evaluates`]), and when nothing in `n`, nor the art of a symbol an instance in it shows, has a
/// visible effect ([`draws_effects`]). The art is evaluated again when `n`, a symbol of the
-/// document, its patterns, swatches or color groups, or the [`LiveInputs`] have changed since, and
+/// document or its 9-slice guides or natural size, its patterns, swatches or color groups, or the
+/// [`LiveInputs`] have changed since, and
/// on every call while it holds a placed document ([`holds_placed`]). When the art kept is full, new
/// art replaces as much other art as it needs room for, and art larger than [`LIVE_KEPT_SIZE`] is
/// kept alone.
@@ -332,16 +406,7 @@ fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc>, Option
let art = Rc::new(art.into_iter().collect::>());
let size = art_size(&art).saturating_add(art_size(std::slice::from_ref(n)));
if !holds_placed(doc, n) {
- let of = EvaluatedLive {
- node: n.clone(),
- symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(),
- patterns: doc.patterns.clone(),
- swatches: doc.swatches.clone(),
- swatch_groups: doc.swatch_groups.clone(),
- inputs,
- art: art.clone(),
- size,
- };
+ let of = Evaluated::new(doc, n, inputs, &art, size);
DRAWN.with_borrow_mut(|(kept, total)| {
if let Some(old) = kept.remove(&n.id) {
*total = total.saturating_sub(old.of.size);
@@ -607,9 +672,11 @@ fn objects_at_repeated(doc: &Document, p: Point, opt: HitOptions, scope: Option<
/// [`objects_at_repeated`] after `tops`, the topmost objects under `p` already found.
fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: Option, mut tops: Vec) -> Vec {
- // Each round leaves out the objects found so far (and everything inside them).
- while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) {
- if tops.contains(&top) {
+ // Each round leaves out the objects found so far (and everything inside them). `found` holds
+ // the same ids as `tops`, which keeps their order.
+ let mut found: HashSet = tops.iter().copied().collect();
+ while let Some(top) = hit_test_skipping(doc, p, opt, &|id| found.contains(&id), true).map(|h| h.top_object(scope)) {
+ if !found.insert(top) {
break;
}
tops.push(top);
@@ -1290,8 +1357,9 @@ fn hit_stroke(n: &Node, bp: &vectorcraft_geom::BezPath, rule: vectorcraft_geom::
stroke_contains(bp, 0.0, opt.tol, p).then_some(HitKind::Outline)
}
-/// Check the body without assembling a `BezPath`. A miss near a joint or cap may still hit a
-/// miter or square cap, so the caller falls back to the full stroke check there.
+/// Check the body without assembling a `BezPath`. Near an end or joint, the caller uses the
+/// full stroke check for non-round caps or joins: Butt and Bevel can reject a radial body hit,
+/// while Miter and Square can extend beyond it.
fn near_path_body(path: &PathData, p: Point, radius: f64, decoration_reach: f64) -> Option<(bool, bool)> {
if !radius.is_finite() || radius < 0.0 || !decoration_reach.is_finite() || decoration_reach < 0.0 {
return None;
@@ -1349,6 +1417,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
}
match &n.kind {
NodeKind::Path { path, rule, .. } => {
+ let has_fill = n.appearance.has_visible_fill();
if opt.outline
&& let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0)
{
@@ -1361,7 +1430,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
}
let mut strokes = n.appearance.painted_strokes();
if !opt.outline
- && n.appearance.fill().is_none_or(|f| f.paint.is_none())
+ && !has_fill
&& let Some(s) = strokes.next()
&& strokes.next().is_none()
&& s.align == StrokeAlign::Center
@@ -1376,10 +1445,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
path,
p,
s.width / 2.0 + opt.tol,
- if s.join == crate::LineJoin::Miter || s.cap == crate::LineCap::Square { s.reach() + opt.tol } else { 0.0 },
+ if s.join != crate::LineJoin::Round || s.cap != crate::LineCap::Round { s.reach() + opt.tol } else { 0.0 },
)
{
- if hit {
+ if hit && !near_decoration {
return Some(HitKind::Stroke);
}
if !near_decoration {
@@ -1390,8 +1459,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
if let Some(k) = hit_stroke(n, &bp, *rule, p, opt) {
return Some(k);
}
- let filled = !n.appearance.fill_paint().is_none();
- if !opt.outline && !opt.path_only && filled && fill_contains(&bp, *rule, p) {
+ if !opt.outline && !opt.path_only && has_fill && fill_contains(&bp, *rule, p) {
return Some(HitKind::Fill);
}
None
@@ -1412,7 +1480,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol {
return Some(HitKind::Outline);
}
- (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill)
+ (!opt.outline && !opt.path_only && n.appearance.has_visible_fill() && fill_contains(&near, *rule, p)).then_some(HitKind::Fill)
}
// The type path lies within the bounds: they rule out the rest before it is measured.
NodeKind::Text(t) if opt.type_path_only => {
@@ -1436,22 +1504,21 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
if opt.outline {
return None;
}
- image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item {
- AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke),
- AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill),
- })
+ hit_painted(n, p, opt, symbols)
}
NodeKind::Text(_) | NodeKind::PlacedDocument(_) => {
n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds)
}
// A symbol instance is hit within its bounds, and outside them where its art paints
- // ([`instance_art_hit`]). In the art of another instance walked outside that instance's
- // bounds, it is hit only where its own art paints ([`ArtOnly`]).
+ // ([`instance_art_hit`]) or where the geometry effects of its active fill or stroke reshape
+ // the art it draws ([`image_paint`]) except in outline mode. In the art of another instance
+ // walked outside that instance's bounds, it is hit only where its own art paints
+ // ([`ArtOnly`]).
NodeKind::SymbolInstance { .. } => {
if !ArtOnly::on() && n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
return Some(HitKind::Bounds);
}
- instance_art_hit(n, p, opt, symbols)
+ instance_art_hit(n, p, opt, symbols).or_else(|| if opt.outline { None } else { hit_painted(n, p, opt, symbols) })
}
// A blend or an envelope is hit within its bounds, and outside them where its evaluated
// art paints: a blend's keys and steps on a spine can reach past the keys and the spine,
@@ -1478,6 +1545,16 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
}
}
+/// What a click at `p` hits among the shapes that the fills and strokes of `n` (an image or a
+/// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a
+/// stroke along its shape, a fill inside it except with Selection by Path Only.
+fn hit_painted(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option {
+ image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item {
+ AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke),
+ AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill),
+ })
+}
+
/// Is `p` within `tol` of the type path of `t` (in `n`), what "Type Object Selection by Path
/// Only" picks type by: its baselines ([`crate::TextObject::baselines`]), area type's frame and
/// type on a path's path, drawn through `n`'s perspective projection if it has one.
diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs
index 39efd78795..9d0133ec60 100644
--- a/crates/doc/src/hit/tests.rs
+++ b/crates/doc/src/hit/tests.rs
@@ -1262,6 +1262,60 @@ fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() {
assert_eq!(evaluated(), before + 2);
}
+/// For instances of the symbol "Painted", a fill that paints the square from (300, 0) to
+/// (320, 20); nothing for anything else.
+fn painted_far_away(_: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
+ match &n.kind {
+ NodeKind::SymbolInstance { symbol, .. } if symbol == "Painted" => {
+ let square = shapes::rectangle(Rect::new(300.0, 0.0, 320.0, 20.0)).to_bezpath();
+ vec![(square, FillRule::NonZero, AppearanceItem::Fill(crate::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))))]
+ }
+ _ => vec![],
+ }
+}
+
+/// Clicks and hovers measure the shapes a symbol instance's fill and stroke effects paint once,
+/// and again only after the instance or the symbols change.
+#[test]
+fn clicks_measure_a_symbol_instances_painted_shapes_once_until_it_changes() {
+ set_image_paint(painted_far_away);
+ let mut d = Document::new(1000.0, 1000.0);
+ let l = d.layers[0].id;
+ let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art());
+ d.symbols.push(crate::Symbol { dynamic: false, name: "Painted".into(), art: Arc::new(art) });
+ let inst = d.alloc_id();
+ let mut n = Node::new(inst, NodeKind::SymbolInstance { symbol: "Painted".into(), xf: vectorcraft_geom::Affine::IDENTITY });
+ n.appearance = Appearance::default_art().into();
+ let offset = crate::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 10}), visible: true };
+ n.appearance.items[0].effects_mut().push(offset);
+ d.insert(Some(l), 0, n).unwrap();
+ let measured = || PAINT_EVALUATED.with(std::cell::Cell::get);
+ let before = measured();
+ let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 10.0), HitOptions::default()).map(|h| h.leaf);
+ assert_eq!(at(&d, 310.0), Some(inst), "a click where the instance's fill paints");
+ assert_eq!(at(&d, 500.0), None);
+ assert_eq!(at(&d, 10.0), Some(inst));
+ assert_eq!(measured(), before + 1);
+ d.node_mut(inst).unwrap().appearance.items[0].effects_mut()[0].params = serde_json::json!({"offset": 12});
+ assert_eq!(at(&d, 310.0), Some(inst));
+ assert_eq!(measured(), before + 2, "a changed instance is measured again");
+ let other = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art());
+ d.symbols.push(crate::Symbol { dynamic: false, name: "Other".into(), art: Arc::new(other) });
+ assert_eq!(at(&d, 310.0), Some(inst));
+ assert_eq!(measured(), before + 3, "changed symbols measure it again");
+ assert_eq!(at(&d, 310.0), Some(inst));
+ assert_eq!(measured(), before + 3);
+ // An image's pixels change when its file is read again, so with one in a symbol's art every
+ // click measures the instance.
+ let xf = vectorcraft_geom::Affine::IDENTITY;
+ let im = crate::ImageObject { key: "k".into(), width: 10, height: 10, xf, link: None, placement: Default::default(), pixels: None };
+ let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)));
+ d.symbols.push(crate::Symbol { dynamic: false, name: "Photo".into(), art: Arc::new(image) });
+ assert_eq!(at(&d, 310.0), Some(inst));
+ assert_eq!(at(&d, 310.0), Some(inst));
+ assert!(measured() >= before + 5, "each click measures it: {}", measured() - before);
+}
+
/// A kept evaluation is the evaluation of the object only while the fonts and plug-ins
/// ([`LiveInputs`]) are as they were.
#[test]
@@ -1274,19 +1328,32 @@ fn a_kept_evaluation_is_stale_after_the_live_inputs_change() {
}
/// An evaluation of `n` in `d`, with inputs 7, holding no symbols, patterns or art.
-fn kept_evaluation(d: &Document, n: &Node) -> EvaluatedLive {
- EvaluatedLive {
+fn kept_evaluation(d: &Document, n: &Node) -> Evaluated> {
+ Evaluated {
node: n.clone(),
symbols: vec![],
patterns: vec![],
swatches: d.swatches.clone(),
swatch_groups: d.swatch_groups.clone(),
+ unknown: d.unknown.clone(),
inputs: 7,
art: std::rc::Rc::new(vec![]),
size: 0,
}
}
+/// A kept evaluation is stale once a symbol's 9-slice guides or natural size change: they place
+/// the symbol's art, and the document keeps them apart from the symbols.
+#[test]
+fn a_kept_evaluation_is_stale_after_a_symbols_placement_changes() {
+ let mut d = Document::new(100.0, 100.0);
+ let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
+ let e = kept_evaluation(&d, &n);
+ assert!(e.is_of(&d, &n, 7));
+ d.unknown.insert(crate::SYMBOL_SIZES.into(), serde_json::json!({"Logo": [40.0, 20.0]}));
+ assert!(!e.is_of(&d, &n, 7));
+}
+
/// A kept evaluation is stale once a swatch changes, in a color group too: a painted live effect's
/// pieces name swatches.
#[test]
@@ -1823,6 +1890,216 @@ fn objects_at_matches_repeated_hits_on_random_documents() {
}
}
+/// [`objects_at_repeated_after`] with each found object looked up in the ordered list itself: the
+/// reference the tests below hold the set lookup to, and the base that `select_behind_isolation_timing` times.
+fn objects_at_repeated_after_by_list(doc: &Document, p: Point, opt: HitOptions, scope: Option, mut tops: Vec) -> Vec {
+ while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) {
+ if tops.contains(&top) {
+ break;
+ }
+ tops.push(top);
+ }
+ tops
+}
+
+/// A layer holding a group of `count` overlapping 50 × 50 squares, member `i` at x = 5 × (`i` mod
+/// 10), with a square at x = 0 below the group and above it, and one at x = 100 above it: the
+/// document, the group and its members, topmost first.
+fn isolated_stack(count: u32) -> (Document, NodeId, Vec) {
+ let mut d = Document::new(200.0, 200.0);
+ let l = d.layers[0].id;
+ let square = |d: &mut Document, x: f64| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default_art());
+ let below = square(&mut d, 0.0);
+ d.insert(Some(l), usize::MAX, below).unwrap();
+ let members: Vec = (0..count).map(|i| square(&mut d, f64::from(i % 10) * 5.0)).collect();
+ let mut ids: Vec = members.iter().map(|n| n.id).collect();
+ let g = d.alloc_id();
+ d.insert(Some(l), usize::MAX, Node::group(g, members.into_iter().map(Arc::new).collect())).unwrap();
+ for x in [0.0, 100.0] {
+ let above = square(&mut d, x);
+ d.insert(Some(l), usize::MAX, above).unwrap();
+ }
+ ids.reverse();
+ (d, g, ids)
+}
+
+/// Select Behind in an isolated group of 40 overlapping squares, with art around the group above
+/// and below them: each member once, front to back, over 41 rounds of hit tests, and nothing where
+/// only the art around the group lies.
+#[test]
+fn select_behind_in_isolation_lists_a_large_stack_once() {
+ let (d, g, ids) = isolated_stack(40);
+ let at = |x: f64, scope| objects_at(&d, Point::new(x, 25.0), HitOptions::default(), scope);
+ assert_eq!(at(47.5, Some(g)), ids);
+ assert_eq!(at(47.5, Some(g)).iter().collect::>().len(), 40, "no object twice");
+ assert_eq!(at(47.5, None).len(), 3, "not isolated: the square above, the group and the square below");
+ // At x = 17.5 only the members at x = 0 to 20 are hit (the one at 20 on its stroke, within
+ // the tolerance): `ids[k]` is member 39 - k.
+ let left: Vec = ids.iter().enumerate().filter(|(k, _)| (39 - k) % 10 <= 4).map(|(_, id)| *id).collect();
+ assert_eq!(left.len(), 20);
+ assert_eq!(at(17.5, Some(g)), left);
+ assert!(at(125.0, Some(g)).is_empty(), "only the square around the group");
+ assert_eq!(at(125.0, None).len(), 1);
+ let isolated = HitOptions { scope: Some(g), ..HitOptions::default() };
+ let p = Point::new(47.5, 25.0);
+ assert_eq!(objects_at_repeated_after(&d, p, isolated, Some(g), ids[..15].to_vec()), ids, "the objects passed in stay first");
+ let (d, g, clip, art) = masked_square(false);
+ let isolated = HitOptions { scope: Some(g), ..SELECTING };
+ for p in [Point::new(140.0, 90.0), Point::new(170.0, 90.0), Point::new(100.0, 90.0)] {
+ let want = objects_at_repeated_after_by_list(&d, p, isolated, Some(g), vec![]);
+ assert_eq!(objects_at(&d, p, SELECTING, Some(g)), want, "clip group isolated, {p:?}");
+ }
+ assert_eq!(objects_at(&d, Point::new(170.0, 90.0), SELECTING, Some(g)), vec![art], "the art its mask hides");
+ assert!(objects_at(&d, Point::new(140.0, 90.0), SELECTING, Some(g)).contains(&clip), "the mask on its outline");
+}
+
+/// Documents built at random (nested groups, clipping groups, envelopes in Edit Contents, hidden
+/// and locked objects), each object in turn isolated, and each list started with some of the
+/// objects already found: the set lookup returns what the ordered-list lookup returns, field for
+/// field.
+#[test]
+fn select_behind_in_isolation_matches_the_list_lookup_on_random_documents() {
+ let mut seed = 0x2545_f491_u32;
+ let mut next = move |n: u32| {
+ seed ^= seed << 13;
+ seed ^= seed >> 17;
+ seed ^= seed << 5;
+ seed % n
+ };
+ fn fill(d: &mut Document, parent: NodeId, depth: u32, next: &mut impl FnMut(u32) -> u32) {
+ for _ in 0..2 + next(5) {
+ let id = d.alloc_id();
+ let rect = |next: &mut dyn FnMut(u32) -> u32| {
+ let (x, y) = (f64::from(next(60)), f64::from(next(60)));
+ Rect::new(x, y, x + 10.0 + f64::from(next(50)), y + 10.0 + f64::from(next(50)))
+ };
+ let mut n = match next(if depth < 3 { 9 } else { 4 }) {
+ 4 | 5 => Node::group(id, Vec::new()),
+ 6 => {
+ let mut g = Node::group(id, Vec::new());
+ g.set_clips(true);
+ g
+ }
+ 7 => {
+ let content =
+ (0..2).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(rect(next)), Appearance::default_art()))).collect();
+ Node::new(
+ id,
+ NodeKind::Envelope {
+ content,
+ kind: Box::new(crate::live::EnvelopeKind::Warp {
+ style: "arc".to_string(),
+ bend: 0.0,
+ h: 0.0,
+ v: 0.0,
+ horizontal: true,
+ version: 0,
+ }),
+ fidelity: 100.0,
+ editing: next(2) == 0,
+ options: Default::default(),
+ frame: Box::new(vectorcraft_geom::Affine::IDENTITY),
+ },
+ )
+ }
+ _ => Node::path(id, shapes::rectangle(rect(next)), if next(4) == 0 { Appearance::default() } else { Appearance::default_art() }),
+ };
+ n.visible = next(8) != 0;
+ n.locked = next(8) == 0;
+ let group = matches!(n.kind, NodeKind::Group { .. });
+ d.insert(Some(parent), usize::MAX, n).unwrap();
+ if group {
+ fill(d, id, depth + 1, next);
+ }
+ }
+ }
+ let mut compared = 0;
+ for round in 0..60 {
+ let mut d = Document::new(120.0, 120.0);
+ let layer = d.layers[0].id;
+ fill(&mut d, layer, 0, &mut next);
+ let mut scopes = vec![None];
+ d.walk(|n| {
+ if n.id != layer {
+ scopes.push(Some(n.id));
+ }
+ });
+ for _ in 0..6 {
+ let p = Point::new(f64::from(next(120)), f64::from(next(120)));
+ let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() };
+ for &scope in &scopes {
+ let opt = HitOptions { scope, ..opt };
+ let want = objects_at_repeated_after_by_list(&d, p, opt, scope, vec![]);
+ let context = format!("round {round}, {p:?}, {opt:?}");
+ assert_eq!(objects_at_repeated_after(&d, p, opt, scope, vec![]), want, "{context}");
+ if scope.is_some() {
+ assert_eq!(objects_at(&d, p, opt, scope), want, "{context}");
+ }
+ for found in 1..want.len() {
+ let start = want[..found].to_vec();
+ assert_eq!(objects_at_repeated_after(&d, p, opt, scope, start.clone()), want, "{context}, {found} found");
+ assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, scope, start), want, "{context}, {found} found");
+ }
+ compared += usize::from(!want.is_empty());
+ }
+ }
+ }
+ assert!(compared > 500, "only {compared} non-empty lists compared");
+}
+
+/// Times Select Behind in an isolated group of 200 and of 1,000 overlapping squares, the set lookup
+/// against the ordered-list lookup, alternating the two in one process:
+/// `cargo test --release -p vectorcraft-doc --lib -- --ignored --nocapture select_behind_isolation_timing`.
+#[test]
+#[ignore = "a timing, not a check"]
+fn select_behind_isolation_timing() {
+ /// This thread's CPU time in nanoseconds on Linux; the elapsed time since `start` elsewhere.
+ fn clock(start: std::time::Instant) -> u128 {
+ let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok();
+ cpu.and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or_else(|| start.elapsed().as_nanos())
+ }
+ type Lookup = fn(&Document, Point, HitOptions, Option, Vec) -> Vec;
+ let start = std::time::Instant::now();
+ println!("clock: {}", if std::fs::metadata("/proc/thread-self/schedstat").is_ok() { "thread CPU time" } else { "wall clock" });
+ let p = Point::new(47.5, 25.0);
+ for count in [200, 1_000] {
+ let (d, g, ids) = isolated_stack(count);
+ let opt = HitOptions { scope: Some(g), ..HitOptions::default() };
+ assert_eq!(objects_at_repeated_after(&d, p, opt, Some(g), vec![]), ids);
+ assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, Some(g), vec![]), ids);
+ // The time per call of `f`: batches of calls double until one takes at least 100 ms.
+ let per_call = |f: Lookup| {
+ let mut calls = 1u32;
+ loop {
+ let t = clock(start);
+ for _ in 0..calls {
+ std::hint::black_box(f(&d, std::hint::black_box(p), opt, Some(g), vec![]));
+ }
+ let spent = clock(start) - t;
+ if spent >= 100_000_000 || calls >= 1 << 20 {
+ return (spent as f64 / f64::from(calls), calls);
+ }
+ calls *= 2;
+ }
+ };
+ let (mut old, mut new) = (vec![], vec![]);
+ for _ in 0..7 {
+ old.push(per_call(objects_at_repeated_after_by_list));
+ new.push(per_call(objects_at_repeated_after));
+ }
+ old.sort_by(|a, b| a.0.total_cmp(&b.0));
+ new.sort_by(|a, b| a.0.total_cmp(&b.0));
+ let (o, n) = (old[3], new[3]);
+ println!(
+ "{count} objects: list lookup {:.2} ms per call ({} calls), set lookup {:.2} ms per call ({} calls), median of 7 runs",
+ o.0 / 1e6,
+ o.1,
+ n.0 / 1e6,
+ n.1
+ );
+ }
+}
+
/// Select Behind finds a symbol instance by its symbol's art, as a click does: art from
/// (100, 60) to (140, 80), outside the 20 × 20 square around the origin, drawn where it lies by
/// one instance and 100 pt lower by an instance in a group.
diff --git a/crates/doc/src/inline.rs b/crates/doc/src/inline.rs
index 86c26e14f4..b22f6cbfc7 100644
--- a/crates/doc/src/inline.rs
+++ b/crates/doc/src/inline.rs
@@ -117,6 +117,29 @@ impl Document {
/// symbol that shows itself inline ([`Self::inline_art_bounds`]) is shown as an empty slot.
/// Returns the ids of the texts in the layers that changed.
pub fn resolve_inline_art_with(&mut self, layout: &mut dyn FnMut(&mut TextObject)) -> Vec {
+ self.resolve_inline_art_since(None, layout).changed
+ }
+
+ /// [`Self::resolve_inline_art_with`], given `last`: a document an earlier pass left resolved,
+ /// with the bounds that pass measured ([`InlinePass::measured`]). When this document has the
+ /// same symbols, graph designs, pattern tiles and foreign data (`unknown`, which holds the
+ /// symbols' natural sizes and 9-slice guides) as `last`, and each symbol name measured then
+ /// still measures the same, the type in the layer trees that are the same nodes as `last`'s
+ /// already has these bounds: only the other layer trees are checked, in the same order, and
+ /// the document and the ids returned are those of the full pass. Otherwise, or without `last`,
+ /// the full pass runs.
+ pub fn resolve_inline_art_since(&mut self, last: Option<(&Document, &InlineMeasured)>, layout: &mut dyn FnMut(&mut TextObject)) -> InlinePass {
+ if let Some((last, kept)) = last
+ && self.same_inline_inputs(last, kept)
+ {
+ let measured = Measured(RefCell::new(kept.0.clone()));
+ let mut changed = vec![];
+ let layers = resolve_kids(Some(&last.layers), &self.layers, &|n| measured.get(n, || self.inline_art_bounds(n)), layout, &mut changed);
+ for (i, layer) in layers {
+ self.layers[i] = layer;
+ }
+ return InlinePass { changed, measured: InlineMeasured(measured.0.into_inner()), partial: true };
+ }
let mut out = vec![];
let mut unused = vec![];
let graph = InlineGraph::of(self);
@@ -147,10 +170,44 @@ impl Document {
}
}
}
- out
+ InlinePass { changed: out, measured: InlineMeasured(measured.0.into_inner()), partial: false }
+ }
+
+ /// Whether the type in this document's layer trees that are the same nodes as `last`'s already
+ /// has the bounds a full pass would give it (see [`Self::resolve_inline_art_since`]).
+ fn same_inline_inputs(&self, last: &Document, kept: &InlineMeasured) -> bool {
+ self.symbols.len() == last.symbols.len()
+ && self.symbols.iter().zip(&last.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
+ && self.graph_designs.len() == last.graph_designs.len()
+ && self.graph_designs.iter().zip(&last.graph_designs).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
+ && self.patterns.len() == last.patterns.len()
+ && self
+ .patterns
+ .iter()
+ .zip(&last.patterns)
+ .all(|(a, b)| a.name == b.name && a.art.len() == b.art.len() && a.art.iter().zip(&b.art).all(|(x, y)| Arc::ptr_eq(x, y)))
+ && crate::Shared::ptr_eq(&self.unknown, &last.unknown)
+ && kept.0.iter().all(|(name, b)| self.inline_art_bounds(name) == *b)
}
}
+/// What a pass of [`Document::resolve_inline_art_since`] did.
+#[derive(Debug)]
+pub struct InlinePass {
+ /// The ids of the texts in the layers that changed, in the order the full pass finds them.
+ pub changed: Vec,
+ /// The bounds the pass gave the inline graphics of each symbol name, for the next pass.
+ pub measured: InlineMeasured,
+ /// Whether only the layer trees that differ from the last resolved document's were checked.
+ pub partial: bool,
+}
+
+/// The art bounds a pass of [`Document::resolve_inline_art_since`] gave the inline graphics of each
+/// symbol name it was asked for. A pass that checks only some layer trees keeps the names the
+/// pass before it measured, so the names of all the type in the document stay listed.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct InlineMeasured(HashMap>);
+
/// Whether `t` has inline graphics whose bounds differ from what `bounds` gives their symbols.
fn stale_by(t: &TextObject, bounds: &dyn Fn(&str) -> Option) -> bool {
t.runs.iter().filter_map(|r| r.inline.as_ref()).any(|a| a.bounds != bounds(&a.symbol))
@@ -185,6 +242,22 @@ fn resolve_tree(
layout: &mut dyn FnMut(&mut TextObject),
changed: &mut Vec,
) -> bool {
+ resolve_since(None, n, bounds, layout, changed)
+}
+
+/// [`resolve_tree`], given `old`: the node `n` was before an edit, in a document whose type was
+/// resolved with the same `bounds`. The opacity mask art and children of `n` that are the same
+/// nodes as `old`'s are skipped: their type already has these bounds. Without `old`, every node
+/// of the tree is visited.
+fn resolve_since(
+ old: Option<&Node>,
+ n: &mut Arc,
+ bounds: &dyn Fn(&str) -> Option,
+ layout: &mut dyn FnMut(&mut TextObject),
+ changed: &mut Vec,
+) -> bool {
+ #[cfg(test)]
+ tests::VISITS.with(|v| v.set(v.get() + 1));
let mut copied = false;
if matches!(&n.kind, NodeKind::Text(t) if stale_by(t, bounds)) {
let node = Arc::make_mut(n);
@@ -196,17 +269,17 @@ fn resolve_tree(
}
copied = true;
}
+ let old_mask = old.and_then(|o| o.extras().mask.as_deref()).map(|m| &m.art);
let mask = n.extras().mask.as_deref().and_then(|m| {
- let mut art = m.art.clone();
- resolve_tree(&mut art, bounds, layout, changed).then_some(art)
- });
- let mut kids = vec![];
- for (i, c) in n.children().into_iter().flatten().enumerate() {
- let mut c = c.clone();
- if resolve_tree(&mut c, bounds, layout, changed) {
- kids.push((i, c));
+ if old_mask.is_some_and(|o| Arc::ptr_eq(o, &m.art)) {
+ return None;
}
- }
+ let mut art = m.art.clone();
+ let old_art = old_mask.filter(|o| o.id == art.id).map(|o| &**o);
+ resolve_since(old_art, &mut art, bounds, layout, changed).then_some(art)
+ });
+ let old_kids = old.map(|o| o.children().map_or(&[][..], Vec::as_slice));
+ let kids = resolve_kids(old_kids, n.children().map_or(&[][..], Vec::as_slice), bounds, layout, changed);
if mask.is_none() && kids.is_empty() {
return copied;
}
@@ -224,6 +297,35 @@ fn resolve_tree(
true
}
+/// Resolves the trees `kids` as [`resolve_since`] does, each with the node of `old` (the same list
+/// before an edit) that has its id, found at the same position or else by id, and skips those that
+/// are the same nodes as theirs. Without `old`, every tree is visited. Returns the position and new
+/// node of each tree that changed.
+fn resolve_kids(
+ old: Option<&[Arc]>,
+ kids: &[Arc],
+ bounds: &dyn Fn(&str) -> Option,
+ layout: &mut dyn FnMut(&mut TextObject),
+ changed: &mut Vec,
+) -> Vec<(usize, Arc)> {
+ let mut by_id: Option>> = None;
+ let mut out = vec![];
+ for (i, c) in kids.iter().enumerate() {
+ let o = old.and_then(|old| match old.get(i) {
+ Some(b) if b.id == c.id => Some(b),
+ _ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
+ });
+ if o.is_some_and(|o| Arc::ptr_eq(o, c)) {
+ continue;
+ }
+ let mut c = c.clone();
+ if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) {
+ out.push((i, c));
+ }
+ }
+ out
+}
+
/// The art bounds of each symbol, measured once in a pass of [`Document::resolve_inline_art_with`].
/// A symbol is first asked for after its own type is resolved (the pass goes in
/// [`InlineGraph::order`]), so its measurement stays current for the rest of the pass.
@@ -436,6 +538,112 @@ impl std::fmt::Debug for InlineCycles {
mod tests {
use super::*;
+ thread_local! {
+ /// How many nodes [`resolve_since`] has visited on this thread.
+ pub(super) static VISITS: std::cell::Cell = const { std::cell::Cell::new(0) };
+ }
+
+ /// The nodes visited since the last call.
+ fn visits() -> usize {
+ VISITS.with(|v| v.replace(0))
+ }
+
+ /// A copy of `d` resolved by the full pass, and the ids that pass returns.
+ fn fully_resolved(d: &Document) -> (Document, Vec) {
+ let mut full = d.clone();
+ let ids = full.resolve_inline_art_with(&mut |_| {});
+ (full, ids)
+ }
+
+ /// The children of the layer at `i`, for an edit.
+ fn layer_kids(d: &mut Document, i: usize) -> &mut Vec> {
+ match Arc::make_mut(&mut d.layers[i]).children_mut() {
+ Some(kids) => kids,
+ None => panic!("layer {i} is a group"),
+ }
+ }
+
+ /// 50 groups of 20 squares, symbol `S`, type showing `S` in the first group, and type showing
+ /// `S` in the opacity mask of the second.
+ fn many_groups() -> Document {
+ let mut d = Document::new(500.0, 500.0);
+ let square = stroked(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0));
+ symbol(&mut d, "S", vec![square]);
+ for _ in 0..50 {
+ let kids = (0..20).map(|_| stroked(&mut d, Rect::new(0.0, 0.0, 5.0, 5.0))).collect();
+ let group = Node::group(d.alloc_id(), kids);
+ d.layers.push(Arc::new(group));
+ }
+ let t = showing(&mut d, "S");
+ layer_kids(&mut d, 0).push(t);
+ let masked = showing(&mut d, "S");
+ Arc::make_mut(&mut d.layers[1]).extras_mut().mask = Some(Box::new(crate::OpacityMask::new((*masked).clone(), true)));
+ d
+ }
+
+ #[test]
+ fn a_pass_after_an_edit_checks_only_the_trees_the_edit_changed() {
+ let mut d = many_groups();
+ let first = d.resolve_inline_art_since(None, &mut |_| {});
+ assert!(!first.partial);
+ assert_eq!(first.changed.len(), 2);
+ let last = d.clone();
+ visits();
+ let _ = fully_resolved(&d);
+ let full_visits = visits();
+ // The edit moves a square in the 31st group, adds type showing S to the 41st, and gives the
+ // second group's opacity mask new type: its 20 squares stay the same nodes.
+ let moved = stroked(&mut d, Rect::new(1.0, 1.0, 6.0, 6.0));
+ layer_kids(&mut d, 30)[5] = moved;
+ let added = showing(&mut d, "S");
+ layer_kids(&mut d, 40).push(added.clone());
+ let mask_type = showing(&mut d, "S");
+ if let Some(m) = Arc::make_mut(&mut d.layers[1]).extras_if_any().and_then(|e| e.mask.as_deref_mut()) {
+ m.art = mask_type.clone();
+ }
+ let (want, ids) = fully_resolved(&d);
+ assert_eq!(ids, [mask_type.id, added.id]);
+ visits();
+ let pass = d.resolve_inline_art_since(Some((&last, &first.measured)), &mut |_| {});
+ let partial_visits = visits();
+ assert!(pass.partial);
+ assert_eq!(pass.changed, ids);
+ assert_eq!(d, want);
+ // The three changed groups, the mask's new type, the moved square and the added type.
+ assert_eq!(partial_visits, 6);
+ assert!(full_visits > 1000, "{full_visits}");
+ assert_eq!(pass.measured, first.measured);
+ }
+
+ #[test]
+ fn changed_symbols_or_symbol_sizes_take_the_full_pass() {
+ let mut d = many_groups();
+ let mut pass = d.resolve_inline_art_since(None, &mut |_| {});
+ // A natural size for S, its art unchanged.
+ let last = d.clone();
+ d.unknown.insert(SYMBOL_SIZES.into(), serde_json::json!({ "S": [40.0, 20.0] }));
+ let (want, ids) = fully_resolved(&d);
+ assert_eq!(ids.len(), 2);
+ pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {});
+ assert!(!pass.partial);
+ assert_eq!((&d, &pass.changed), (&want, &ids));
+ // New art for S.
+ let last = d.clone();
+ let bigger = stroked(&mut d, Rect::new(0.0, 0.0, 30.0, 30.0));
+ d.symbols[0].art = Arc::new(Node::group(d.alloc_id(), vec![bigger]));
+ let (want, ids) = fully_resolved(&d);
+ assert_eq!(ids.len(), 2);
+ pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {});
+ assert!(!pass.partial);
+ assert_eq!((&d, &pass.changed), (&want, &ids));
+ // A measurement that no longer holds, with the same symbols and foreign data.
+ let last = d.clone();
+ let stale = InlineMeasured(HashMap::from([("S".to_owned(), Some(Rect::new(0.0, 0.0, 1.0, 1.0)))]));
+ pass = d.resolve_inline_art_since(Some((&last, &stale)), &mut |_| {});
+ assert!(!pass.partial);
+ assert!(pass.changed.is_empty());
+ }
+
/// The position of each node in `order`.
fn positions(order: &[usize]) -> Vec {
let mut at = vec![0; order.len()];
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 18974db32a..7ad3a8d108 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -31,7 +31,7 @@ mod symbol_nine_slice;
pub mod symbol_overrides;
mod symbol_pixel_aligned;
mod symbol_registration;
-pub use inline::{SYMBOL_HALF, SYMBOL_SIZES};
+pub use inline::{InlineMeasured, InlinePass, SYMBOL_HALF, SYMBOL_SIZES};
pub use shared::Shared;
pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType};
pub use symbol_nine_slice::{
diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs
index 28fd1dc632..337634db2e 100644
--- a/crates/doc/src/live.rs
+++ b/crates/doc/src/live.rs
@@ -66,7 +66,8 @@ pub use expand::{
use mesh::grid_eval;
pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds};
pub use warp::{
- WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net, warp_point, warp_version,
+ WARP_NET, WarpNet, WarpStyle, fit_piece, map_handles_within, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net,
+ warp_point, warp_version,
};
#[cfg(test)]
diff --git a/crates/doc/src/live/warp.rs b/crates/doc/src/live/warp.rs
index dd48e8ef65..a921c7d2ff 100644
--- a/crates/doc/src/live/warp.rs
+++ b/crates/doc/src/live/warp.rs
@@ -508,6 +508,17 @@ pub fn map_smooth_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn
map_pieces_within(path, max_piece, max, &f, |p, h| mapped_handle(&f, p, h))
}
+/// [`map_nonlinear_within`] with `handle(point, handle)` supplying each mapped handle position.
+pub fn map_handles_within(
+ path: &PathData,
+ max_piece: f64,
+ max: usize,
+ f: impl Fn(Point) -> Point,
+ handle: impl Fn(Point, Point) -> Point,
+) -> PathData {
+ map_pieces_within(path, max_piece, max, &f, handle)
+}
+
/// Handle `h` of point `p` mapped through `f`: `f(p)` plus `f`'s derivative at `p` along `h - p`
/// (a central difference), so the image curve leaves `f(p)` the way `f` takes the curve.
fn mapped_handle(f: &impl Fn(Point) -> Point, p: Point, h: Point) -> Point {
@@ -553,7 +564,8 @@ fn map_pieces_within(path: &PathData, max_piece: f64, max: usize, f: &impl Fn(Po
let c = seg_cubic(sp, i);
let k = pieces(poly_len(&c), max_piece, MAX_PIECES);
for j in 0..k {
- let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64));
+ // Evaluating an unchanged curve can overflow even when its control points are finite.
+ let sub = if k == 1 { c } else { c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64)) };
if let Some(last) = res.last_mut() {
last.h_out = handle(sub.p0, sub.p1);
}
@@ -613,3 +625,53 @@ pub(super) fn resample(poly: &[Point], m: usize) -> Vec {
}
out
}
+
+#[cfg(test)]
+mod handle_tests {
+ use super::*;
+
+ #[test]
+ fn an_unsplit_curve_keeps_its_finite_control_points() {
+ let start = Point::new(1e308, 0.0);
+ let end = Point::new(1.03e308, 0.0);
+ let path = PathData::new(vec![SubPath::new(
+ vec![Anchor::with_handles(start, start, Point::new(1.01e308, 1.0)), Anchor::with_handles(end, Point::new(1.02e308, 1.0), end)],
+ false,
+ )]);
+ assert_eq!(map_handles_within(&path, 1.0, 2, |p| p, |_, h| h), path);
+ }
+
+ #[test]
+ fn rounded_samples_preserve_a_smooth_interior_join() {
+ let center = Point::new(1e16, 0.0);
+ let path = PathData::new(vec![SubPath::new(
+ vec![
+ Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(-18.0, 0.0)),
+ Anchor::with_handles(
+ center,
+ center + vectorcraft_geom::kurbo::Vec2::new(-6.0, 0.0),
+ center + vectorcraft_geom::kurbo::Vec2::new(6.0, 0.0),
+ ),
+ Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(18.0, 0.0)),
+ ],
+ false,
+ )]);
+ let mapped = map_smooth_within(&path, f64::INFINITY, 3, |p| Point::new(p.x, p.y + (p.x - center.x).powi(2) * 0.1));
+ let join = &mapped.subpaths[0].anchors[1];
+ let incoming = join.p - join.h_in;
+ let outgoing = join.h_out - join.p;
+ assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}");
+ assert!(incoming.dot(outgoing) > 0.0);
+ }
+
+ #[test]
+ fn a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction() {
+ for x in [1e16, 1e16 + 2.0, -1e16] {
+ for offset in [-6.0, -2.0, 2.0, 6.0] {
+ let p = Point::new(x, 0.0);
+ let h = Point::new(x + offset, 0.0);
+ assert_eq!(mapped_handle(&|point| point, p, h), h);
+ }
+ }
+ }
+}
diff --git a/crates/doc/src/node/live_shape.rs b/crates/doc/src/node/live_shape.rs
index 9ddc4e1bb6..a384836442 100644
--- a/crates/doc/src/node/live_shape.rs
+++ b/crates/doc/src/node/live_shape.rs
@@ -179,6 +179,48 @@ impl LiveShape {
*xf = Affine::rotate_about((now - angle).to_radians(), centre) * *xf;
}
}
+ /// A line's length in the document, from its first end to its second. None for other shapes.
+ pub fn line_length(&self) -> Option {
+ let LiveShape::Line { a, b } = self else { return None };
+ Some((*b - *a).hypot())
+ }
+ /// A line's angle: the counterclockwise degrees in [0, 360) from the page's horizontal to the
+ /// direction from its first end to its second (the Rotate field's sense). 0 for a line whose
+ /// ends meet. None for other shapes.
+ pub fn line_angle(&self) -> Option {
+ let LiveShape::Line { a, b } = self else { return None };
+ if a == b {
+ return Some(0.0);
+ }
+ // No −0° or 360° from rounding: a line drawn left to right reads 0°.
+ let a = (-self.angle_deg()).rem_euclid(360.0);
+ Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 })
+ }
+ /// Make a line `len` long (0 or more), keeping its first end in place and its direction, or
+ /// pointing it to the right when its ends meet.
+ pub fn set_line_length(&mut self, len: f64) {
+ let LiveShape::Line { a, b } = self else { return };
+ if !len.is_finite() || len < 0.0 {
+ return;
+ }
+ let now = (*b - *a).hypot();
+ *b = if now > 0.0 { *a + (*b - *a) * (len / now) } else { Point::new(a.x + len, a.y) };
+ }
+ /// Turn a line about its midpoint to `angle` (degrees, as [`LiveShape::line_angle`]). A line
+ /// whose ends meet stays as it is.
+ pub fn set_line_angle(&mut self, angle: f64) {
+ let LiveShape::Line { a, b } = self else { return };
+ let half = (*b - *a).hypot() / 2.0;
+ if !angle.is_finite() || half <= 0.0 {
+ return;
+ }
+ let mid = a.midpoint(*b);
+ let t = angle.to_radians();
+ // The page's y axis points down, so a counterclockwise angle goes up the page.
+ let (dx, dy) = (half * t.cos(), -half * t.sin());
+ *a = Point::new(mid.x - dx, mid.y - dy);
+ *b = Point::new(mid.x + dx, mid.y + dy);
+ }
/// Make a polygon's sides equal (Make Sides Equal): drop the uneven scale and the shear from
/// `xf`, keeping its centre, angle, reflection and [`LiveShape::polygon_radius`].
pub fn make_sides_equal(&mut self) {
diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs
index a616080bce..42978c81b0 100644
--- a/crates/doc/src/node/ops.rs
+++ b/crates/doc/src/node/ops.rs
@@ -216,8 +216,10 @@ impl Node {
/// path give it ([`crate::hit::set_clip_region`]). An image's box takes in
/// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers
/// without a clipping mask and Intertwine groups take in their members' boxes, grown by their
- /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box
- /// takes in where its spine can put its keys and steps.
+ /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`], taking in the
+ /// shapes their art paints with the geometry effects of their own fill or stroke
+ /// ([`crate::hit::set_image_paint`]). A blend's box takes in where its spine can put its keys
+ /// and steps.
pub fn reach_bounds(&self) -> Option {
self.reach(None)
}
@@ -254,14 +256,8 @@ impl Node {
.map(|b| b.inflate(o, o))
}
NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))),
- // The frame and each shape the image's own fills and strokes paint, a stroke's grown by
- // the farthest it can reach from its shape.
- NodeKind::Image(_) => {
- crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| {
- let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
- vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
- })
- }
+ // The frame and each shape the image's own fills and strokes paint.
+ NodeKind::Image(_) => self.with_own_paint(self.geometric(symbols), symbols),
// Keys and steps placed on a spine, turned to it with Align to Path, can reach past the
// keys and the spine.
NodeKind::Blend { children, spec } => {
@@ -272,13 +268,15 @@ impl Node {
NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => {
vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c)))
}
- // The live geometry effects of the clipping paths in the art can draw it past its box.
+ // The live geometry effects of the clipping paths in the art can draw it past its box,
+ // and the box takes in each shape the art paints with the geometry effects of the
+ // instance's own fill or stroke.
NodeKind::SymbolInstance { symbol, xf } => {
let Some((s, art, region)) = symbols.and_then(|s| {
let a = s.art(symbol)?;
Some((s, a, a.reshaped?))
}) else {
- return self.visual(symbols);
+ return self.with_own_paint(self.visual(symbols), symbols);
};
let map = s.document().symbol_slice_map_of(symbol, art.geometric, *xf);
let placed = if moves_only(*xf) && map.is_none() {
@@ -294,12 +292,22 @@ impl Node {
map.map_or_else(|| xf.transform_rect_bbox(all), |m| m.placement_bounds(all)).inflate(grow, grow)
};
let o = self.appearance.outset();
- vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o)))
+ self.with_own_paint(vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o))), symbols)
}
_ => self.visual(symbols),
}
}
+ /// `start` grown by each shape the node's own fills and strokes paint
+ /// ([`crate::hit::set_image_paint`]), a stroke's grown by the farthest it can reach from its
+ /// shape.
+ fn with_own_paint(&self, start: Option, symbols: Option<&SymbolBoxes>) -> Option {
+ crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(start, |acc, (bp, _, item)| {
+ let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
+ vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
+ })
+ }
+
/// Geometric bounds (no stroke), recursively. Clip groups are bounded by their clip path. A
/// symbol instance is measured as its transform applied to the 20 × 20 square around the origin
/// that symbols made in the app keep their art in ([`Node::geometric_bounds_with`] measures
diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs
index 9c25427846..0ee84dc32c 100644
--- a/crates/doc/src/swatches.rs
+++ b/crates/doc/src/swatches.rs
@@ -187,8 +187,9 @@ impl Document {
/// [`Document::map_solid_paints`] limited to the art in the subtrees of `ids` (each paint
/// visited once even when an id is inside another).
pub fn map_solid_paints_in(&mut self, ids: &[NodeId], f: &mut LinkFn) -> usize {
+ let listed: HashSet = ids.iter().copied().collect();
let roots: Vec =
- ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect();
+ ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect();
let mut n = 0;
let mut g = relink(f);
for id in roots {
@@ -844,6 +845,77 @@ mod tests {
assert_eq!(colors, [(Color::rgb(1.0, 0.0, 0.0), None)]);
}
+ /// [`Document::map_solid_paints_in`] with each ancestor searched for in `ids` rather than looked up in a set.
+ fn map_solid_paints_in_by_search(d: &mut Document, ids: &[NodeId], f: &mut LinkFn) -> usize {
+ let roots: Vec =
+ ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect();
+ let mut n = 0;
+ let mut g = relink(f);
+ for id in roots {
+ let Some(node) = d.node(id) else { continue };
+ if let Some((new, count)) = map_node(node, &mut g)
+ && let Some(slot) = d.node_mut(id)
+ {
+ *slot = new;
+ n += count;
+ }
+ }
+ n
+ }
+
+ #[test]
+ fn mapping_within_ids_matches_a_search_of_the_ids() {
+ // Two layers: the first holds group `outer` (group `inner` with two rectangles, and a
+ // rectangle) and a rectangle; the second holds a rectangle. Each rectangle has its own color.
+ let mut d = Document::new(100.0, 100.0);
+ let first = d.layers[0].id;
+ let second = d.alloc_id();
+ d.insert(None, usize::MAX, Node::layer(second, "Second", crate::LayerColor::Preset(1))).unwrap();
+ let rect = |d: &mut Document, i: u8| {
+ let id = d.alloc_id();
+ let r = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
+ let color = Color::rgb(f32::from(i) / 8.0, 0.0, 0.0);
+ (id, Arc::new(Node::path(id, r, Appearance::basic(Paint::solid(color), Paint::solid(color), 1.0))))
+ };
+ let (r1, n1) = rect(&mut d, 1);
+ let (r2, n2) = rect(&mut d, 2);
+ let (r3, n3) = rect(&mut d, 3);
+ let (r4, n4) = rect(&mut d, 4);
+ let (r5, n5) = rect(&mut d, 5);
+ let (inner, outer) = (d.alloc_id(), d.alloc_id());
+ let outer_node = Node::group(outer, vec![Arc::new(Node::group(inner, vec![n1, n2])), n3]);
+ d.insert(Some(first), usize::MAX, outer_node).unwrap();
+ d.insert(Some(first), usize::MAX, Arc::unwrap_or_clone(n4)).unwrap();
+ d.insert(Some(second), usize::MAX, Arc::unwrap_or_clone(n5)).unwrap();
+ let missing = NodeId(u64::MAX);
+ let all = [first, second, outer, inner, r1, r2, r3, r4, r5, missing];
+ // Every list of up to three of them: nested ids in both orders, duplicates, a missing id and none.
+ let mut lists: Vec> = vec![vec![]];
+ let mut shorter: Vec> = vec![vec![]];
+ for _ in 0..3 {
+ shorter = shorter.iter().flat_map(|l| all.map(|id| [l.as_slice(), &[id]].concat())).collect();
+ lists.extend(shorter.iter().cloned());
+ }
+ assert_eq!(lists.len(), 1 + 10 + 100 + 1000);
+ for ids in &lists {
+ // A callback that changes every paint it visits, so a paint visited twice counts twice.
+ let run = |map: &dyn Fn(&mut Document, &[NodeId], &mut LinkFn) -> usize| {
+ let mut d = d.clone();
+ let mut visits = vec![];
+ let n = map(&mut d, ids, &mut |c, s, t| {
+ visits.push((*c, s.clone(), *t));
+ *s = Some(format!("{}", visits.len()));
+ *t *= 0.5;
+ true
+ });
+ (n, visits, d.layers)
+ };
+ let by_set = run(&|d, ids, f| d.map_solid_paints_in(ids, f));
+ let by_search = run(&|d, ids, f| map_solid_paints_in_by_search(d, ids, f));
+ assert_eq!(by_set, by_search, "{ids:?}");
+ }
+ }
+
/// The colors [`node_colors`] visits, in its order, by a [`Node::walk`] that reads the whole subtree.
fn full_walk(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) {
n.walk(&mut |m| {
diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs
index 274f9bdcc4..36418ac913 100644
--- a/crates/effects/src/bake.rs
+++ b/crates/effects/src/bake.rs
@@ -28,7 +28,8 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Vec2};
use crate::distort::{transform_move, transform_offsets};
use crate::group::{has_own_paint, paints};
use crate::reshape::{
- as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, paint_type_clip, reshape_leaves,
+ as_art, clip_region_path, clipping_text_outline, dressed, geometry_effects, glyph_outlines, knockout_inside, outline_nested_text,
+ paint_type_clip, reshape_leaves,
};
use crate::{
GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry,
@@ -502,13 +503,7 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option {
{
return None;
}
- let (bp, rule) = crate::clip_outline(first)?;
- let mut clip = Node::path(first.id, PathData::from_bezpath(&bp), Appearance::default());
- if let NodeKind::Path { rule: r, clipping, .. } = &mut clip.kind {
- (*r, *clipping) = (rule, true);
- }
- clip.name = first.name.clone();
- clip.visible = first.visible;
+ let clip = clip_region_path(first)?;
let paint = first.clip_paint();
// The type's fills and strokes as art: baked with the type's id, as the renderer draws them,
// then given ids of their own.
@@ -532,7 +527,8 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option {
return Some(m);
};
// `n` keeps its id, name and transparency, and holds the clip group and the strokes over it.
- let inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true });
+ let mut inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true });
+ knockout_inside(&mut m, &mut inner);
match &mut m.kind {
NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } => {
*children = vec![Arc::new(inner), stroke];
diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs
index deb705752f..70bdc7731b 100644
--- a/crates/effects/src/bake/tests.rs
+++ b/crates/effects/src/bake/tests.rs
@@ -776,7 +776,7 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() {
let mut shadowed = type_node(55);
shadowed.opacity = 0.5;
shadowed.appearance.effects.push(fx("stylize.dropShadow", json!({})));
- // Type that clips a group is outlined as the plain outlines it clips by.
+ // Type that clips a group is outlined as a plain path of the region it clips by.
let square = Node::path(NodeId(57), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art());
let clip = Node::new(NodeId(58), NodeKind::Group { children: vec![Arc::new(type_node(56)), Arc::new(square)], clip: true });
g.children_mut().unwrap().extend([Arc::new(shadowed), Arc::new(clip)]);
@@ -789,7 +789,10 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() {
let b = o.geometric_bounds().unwrap();
assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}");
let clipped = d.node(NodeId(58)).and_then(|n| n.children()).and_then(|c| c.first()).unwrap();
- assert!(matches!(clipped.kind, NodeKind::Group { .. }) && clipped.opacity == 1.0, "{clipped:?}");
+ assert!(matches!(clipped.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && clipped.opacity == 1.0, "{clipped:?}");
+ // The region is copied with the type.
+ let b = clipped.geometric_bounds().unwrap();
+ assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}");
}
#[test]
diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs
index ea727b804c..91c709add6 100644
--- a/crates/effects/src/catalog.rs
+++ b/crates/effects/src/catalog.rs
@@ -277,7 +277,13 @@ pub fn effect_catalog() -> Vec {
"{h: amount (10), v: amount (10), relative: bool (true: % of size), anchors: bool (true), in: bool (true), out: bool (true), seed: int (0)}",
json!({"h": 10.0, "v": 10.0, "relative": true, "anchors": true, "in": true, "out": true, "seed": 0}),
),
- g("distort.twist", "Twist…", DT, "{angle: deg (-3600..3600, 10)}", json!({"angle": 10.0})),
+ g(
+ "distort.twist",
+ "Twist…",
+ DT,
+ "{angle: deg (-3600..3600, 10)} Outer-circle anchors stay fixed; their handles follow the inward tangent.",
+ json!({"angle": 10.0}),
+ ),
g(
"distort.zigZag",
"Zig Zag…",
diff --git a/crates/effects/src/distort.rs b/crates/effects/src/distort.rs
index 7a03a2f3aa..3fa1f3d152 100644
--- a/crates/effects/src/distort.rs
+++ b/crates/effects/src/distort.rs
@@ -6,7 +6,7 @@ use vectorcraft_geom::{Affine, Anchor, ParamCurve, PathData, Point, Rect, SubPat
use vectorcraft_pathops::addons::pathtools::insert_at;
use crate::util::{
- catmull_rom, fit_piece, flag, map_nonlinear_within, map_smooth_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points,
+ catmull_rom, fit_piece, flag, map_handles_within, map_nonlinear_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points,
};
fn diag(b: Rect) -> f64 {
@@ -328,7 +328,7 @@ pub fn tweak(path: &PathData, b: Rect, p: &Value) -> PathData {
/// Twist: rotation that is strongest at the centre and fades to zero at the bounding circle,
/// clockwise on the page for a positive `angle`, making at most `max` anchors. Its handles follow
-/// the rotation's derivative ([`map_smooth_within`]), so the pieces join without kinks (#7069).
+/// the rotation's directional derivative, including each side of the outer circle.
pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData {
let ang = angle.clamp(-3600.0, 3600.0).to_radians();
if ang == 0.0 {
@@ -336,16 +336,46 @@ pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData {
}
let c = b.center();
let r = diag(b) / 2.0;
+ let half = Vec2::new(b.width() * 0.5, b.height() * 0.5);
+ let boundary = move |p: Point, length: f64| {
+ if length == r {
+ return true;
+ }
+ if !r.is_finite() || (length - r).abs() > 8.0 * f64::EPSILON * r {
+ return false;
+ }
+ // A bounds-relative distance identifies boundary points affected by center rounding.
+ (Vec2::new(p.x - b.x0, p.y - b.y0) - half).hypot() == r
+ };
let f = move |q: Point| {
let d = q - c;
- let t = (1.0 - d.hypot() / r).max(0.0);
+ let length = d.hypot();
+ let t = (1.0 - length / r).max(0.0);
// y runs down, so a positive turn is clockwise on the page.
let a = ang * t;
+ if a == 0.0 {
+ return q;
+ }
let (s, co) = a.sin_cos();
c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co)
};
let piece = (r / 8.0).min(r / (1.0 + ang.abs() * 2.0));
- map_smooth_within(path, piece, max, f)
+ map_handles_within(path, piece, max, f, |p, h| {
+ let v = h - p;
+ if !v.hypot().is_finite() {
+ return f(p);
+ }
+ let d = p - c;
+ let length = d.hypot();
+ let radial = if length > 0.0 { (d / length).dot(v) } else { 0.0 };
+ // The clamped rotation has different inward and outward derivatives at the circle.
+ let inside = if boundary(p, length) { radial < 0.0 } else { length < r };
+ let gradient = if inside { -ang / r * radial } else { 0.0 };
+ let tangent = if gradient == 0.0 { v } else { v + Vec2::new(-d.y, d.x) * gradient };
+ let a = ang * (1.0 - length / r).max(0.0);
+ let (s, co) = a.sin_cos();
+ f(p) + Vec2::new(tangent.x * co - tangent.y * s, tangent.x * s + tangent.y * co)
+ })
}
const ZIGZAG_ARCLEN_ACCURACY: f64 = 1e-4;
diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs
index 9531159e01..e52a85e125 100644
--- a/crates/effects/src/group.rs
+++ b/crates/effects/src/group.rs
@@ -110,13 +110,15 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option, nodes: &S
// Every path of the outline art, at any depth, is drawn inside the object's opacity
// and blend mode. A symbol's art comes with the live objects and the instances of
// other symbols inside it given as their art, and the type inside it outlined, so the
- // art has nothing left for `hook` to give.
+ // art has nothing left for `hook` to give. Its fills and strokes carry the geometry
+ // effects of the instance's active fill and stroke, as the canvas draws them.
if let Some(h) = hook
&& let Some(art) = h(n)
{
let art = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if nodes.charge(&art) => {
- let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
+ let mut art = instance_art(doc, &art, h, nodes, symbol);
+ crate::reshape::add_instance_row_effects(doc, n, &mut art);
crate::reshape::outline_nested_text(doc, &mut art, false);
transparency_into_members(&mut art);
art
@@ -134,6 +136,19 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option, nodes: &S
}
}
+/// `art`, the art `hook` gave an instance of the symbol named `symbol`, with the live objects and
+/// the instances of other symbols inside it given as their art
+/// ([`crate::reshape::symbol_art_with`]). The art of each of those instances carries the geometry
+/// effects of its own active fill and stroke ([`crate::reshape::add_instance_row_effects`]).
+fn instance_art(doc: Option<&Document>, art: &Node, hook: OutlineHook, nodes: &SymbolNodes, symbol: &str) -> Node {
+ let drawn = |m: &Node| {
+ let mut a = hook(m)?;
+ crate::reshape::add_instance_row_effects(doc, m, &mut a);
+ Some(a)
+ };
+ crate::reshape::symbol_art_with(art, &drawn, nodes, symbol)
+}
+
/// `l`, a path drawn inside `n`: its opacity multiplied by `n`'s, and `n`'s blend mode when it is
/// not Normal.
fn within(l: &mut Node, n: &Node) {
@@ -221,13 +236,15 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option, nod
}
},
// A symbol instance with a warp: its symbol's art placed by the instance, with the type
- // inside it outlined, reshaped as one piece, as the renderer draws it.
+ // inside it outlined, reshaped as one piece, as the renderer draws it. The fills and strokes
+ // of the art then carry the geometry effects of the instance's active fill and stroke.
NodeKind::SymbolInstance { symbol, .. } if !fx.is_empty() => {
let h = hook?;
let art = h(n).filter(|art| nodes.charge(art))?;
- let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
+ let mut art = instance_art(doc, &art, h, nodes, symbol);
crate::reshape::outline_nested_text(doc, &mut art, false);
members_as_drawn(doc, &mut art);
+ crate::reshape::add_instance_row_effects(doc, n, &mut art);
let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc);
// The art's own fills and strokes follow the effects as its members do.
if carry.moves(&art.appearance) {
@@ -703,6 +720,11 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul
}
}
fn members(doc: Option<&Document>, n: &Node, out: &mut Vec<(PathData, FillRule)>) {
+ // A clip group whose clipping type's strokes paint around it is outlined as that clip
+ // group: the strokes outside the clip add nothing.
+ if let Some(inner) = crate::reshape::painted_clip_inner(n) {
+ return members(doc, inner, out);
+ }
// A clip group shows its members only inside its clipping path: its outline is that
// region, not the clipped members' own shapes, which may reach far outside it (#7289).
if n.clips() {
@@ -884,14 +906,18 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option {
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
m.appearance.effects.retain(|e| !is_pathfinder(&e.id));
if paint {
- let shapes = member_shapes(doc, &m);
- let bounds = m.geometric_bounds();
+ // A clip group whose clipping type paints strokes is now a group of a clip group and those
+ // strokes ([`crate::reshape::paint_type_clip`]): its own fills and strokes paint inside
+ // that clip group. Such groups among the members are measured as their clip groups.
+ let wrapped = n.clips() && crate::reshape::painted_clip_inner(&m).is_some();
+ let (shapes, bounds) = (member_shapes(doc, &m), crate::reshape::clip_bounds(&m));
let art =
|items: &[AppearanceItem]| -> Vec> { items.iter().filter_map(|i| item_art(n.id, i, &shapes, bounds)).map(Arc::new).collect() };
let (below, above) = m.appearance.split_contents();
let (below, above) = (art(below), art(above));
- let at = usize::from(m.clips());
- if let Some(ch) = m.children_mut() {
+ let at = usize::from(wrapped || m.clips());
+ let target = if wrapped { m.children_mut().and_then(|ch| ch.first_mut()).map(Arc::make_mut) } else { Some(&mut m) };
+ if let Some(ch) = target.and_then(Node::children_mut) {
let at = at.min(ch.len());
ch.splice(at..at, below);
ch.extend(above);
diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs
index 50ecc6b549..00bf169b93 100644
--- a/crates/effects/src/reshape.rs
+++ b/crates/effects/src/reshape.rs
@@ -387,7 +387,7 @@ fn row_effects_of(fx: &[Effect]) -> Vec {
/// of a symbol whose art (in `doc`) holds an instance of `n`'s symbol, at any depth, keeps its
/// appearance, so the effects never pass round a symbol that holds itself. Without `doc`, no
/// instance in the art takes them.
-fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) {
+pub(crate) fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) {
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return };
let fill = active_fill(n).map_or(vec![], |f| row_effects_of(&f.effects));
let stroke = active_stroke(n).map_or(vec![], |s| row_effects_of(&s.effects));
@@ -613,32 +613,101 @@ fn traced_opaque_area(bytes: &[u8]) -> Traced {
/// rule and the fill or stroke that paints it: the paths (or compound paths) that [`reshape`]
/// makes along its frame or, for those whose first effect is Outline Object, along the outline of
/// its opaque area ([`opaque_area`]), with each fill's or stroke's geometry effects applied as the
-/// renderer applies them. Empty for anything but an image with such fills or strokes. The swatches
-/// and patterns that live-effect plug-ins painting their pieces name are looked up in `doc`, and
-/// the image's pixels in `doc` when the image does not hold them.
+/// renderer applies them. For a symbol instance whose active fill or stroke has a visible geometry
+/// effect ([`has_item_geometry`]), the shapes that the fills and strokes of the art it draws paint
+/// ([`instance_paint`]). Empty for anything else. The swatches and patterns that live-effect
+/// plug-ins painting their pieces name are looked up in `doc`, and the image's pixels in `doc` when
+/// the image does not hold them.
pub fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
- if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) {
- return vec![];
- }
- let Some(art) = reshape(doc, n, None) else { return vec![] };
let mut out = vec![];
- art.walk(&mut |c| {
- let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return };
- let Some(g) = c.stroke_path() else { return };
- let ctx = GeomContext { doc, ..GeomContext::of(c) };
- for item in c.appearance.items.iter().filter(|i| crate::paints(i)) {
- let fx = item.effects();
- let shape = if crate::has_geometry(fx) && !g.elements().is_empty() {
- crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item))
- } else {
- g.clone()
- };
- out.push((shape, *rule, item.clone()));
- }
- });
+ if matches!(n.kind, NodeKind::SymbolInstance { .. }) {
+ let mut budget = SYMBOL_ART_MAX_NODES;
+ instance_paint(doc, n, 1, &mut budget, &mut out);
+ return out;
+ }
+ if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) {
+ return out;
+ }
+ let Some(art) = reshape(doc, n, None) else { return out };
+ art.walk(&mut |c| push_painted(doc, c, &mut out));
out
}
+/// The shapes that the fills and strokes of path or compound path `c` paint, each with the
+/// geometry effects of that fill or stroke applied ([`image_paint`]); nothing for other objects.
+fn push_painted(doc: Option<&Document>, c: &Node, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) {
+ let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return };
+ let Some(g) = c.stroke_path() else { return };
+ let ctx = GeomContext { doc, ..GeomContext::of(c) };
+ for item in c.appearance.items.iter().filter(|i| crate::paints(i)) {
+ let fx = item.effects();
+ let shape = if crate::has_geometry(fx) && !g.elements().is_empty() {
+ crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item))
+ } else {
+ g.clone()
+ };
+ out.push((shape, *rule, item.clone()));
+ }
+}
+
+/// The shapes that symbol instance `n`, `depth` instances deep, paints with the geometry effects of
+/// its active fill and stroke ([`has_item_geometry`]): the paths of the art [`reshape`] makes of it,
+/// each with its own geometry effects and those of each fill and stroke applied
+/// ([`crate::bake_type_appearance`], [`push_painted`]), the paths that the own fills and strokes of
+/// the groups and layers in the art paint and the results of their Pathfinder effects
+/// ([`crate::evaluate_container`]), the shapes that the own fills and strokes of the images in the
+/// art paint ([`image_paint`]), and the instances in that art that took those effects, in turn.
+/// Hidden objects, clipping paths, guides, the members of clip groups and the original shapes of
+/// Shaper groups add nothing, and neither does an instance more than
+/// [`vectorcraft_doc::depth::MAX_DEPTH`] deep or whose symbol's art would take the objects measured
+/// so far past `budget`.
+fn instance_paint(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) {
+ let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return };
+ if depth >= vectorcraft_doc::depth::MAX_DEPTH || !has_item_geometry(n) {
+ return;
+ }
+ let Some(sym) = doc.and_then(|d| d.symbols.iter().find(|s| s.name == *symbol)) else { return };
+ let count = sym.art.count() as u64;
+ if count > *budget {
+ return;
+ }
+ *budget -= count;
+ let Some(art) = reshape(doc, n, Some(&vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n))) else { return };
+ painted_in(doc, &art, depth, budget, out);
+}
+
+/// [`instance_paint`] of the objects in `n`, art of an instance `depth` instances deep.
+fn painted_in(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) {
+ if !n.visible {
+ return;
+ }
+ match &n.kind {
+ NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. } => match crate::bake_type_appearance(doc, n) {
+ // One path for each fill and stroke, its effects applied.
+ Some(pieces) => painted_in(doc, &pieces, depth, budget, out),
+ None => push_painted(doc, n, out),
+ },
+ NodeKind::Path { .. } => {}
+ NodeKind::Image(_) => out.extend(image_paint(doc, n)),
+ NodeKind::SymbolInstance { .. } => instance_paint(doc, n, depth + 1, budget, out),
+ _ if n.clips() => {}
+ _ => {
+ // A Pathfinder effect paints its result, not the members it combines.
+ let evaluated = (crate::has_container_appearance(n) || crate::has_pathfinder(n)).then(|| crate::evaluate_container(doc, n)).flatten();
+ let g = evaluated.as_ref().unwrap_or(n);
+ if g.clips() {
+ return;
+ }
+ // A Shaper group's first member holds its original shapes, which are not drawn. The
+ // group's own fills and strokes can be painted before it, so it is found by its id.
+ let sources = n.extras().shaper.is_some().then(|| n.children().and_then(|c| c.first()).map(|c| c.id)).flatten();
+ for c in g.children().into_iter().flatten().filter(|c| Some(c.id) != sources) {
+ painted_in(doc, c, depth, budget, out);
+ }
+ }
+ }
+}
+
/// The glyph outlines of type `t` in text space with its underline and strikethrough bars: one
/// path per run, and all of them as one.
pub(crate) fn glyph_outlines(t: &vectorcraft_doc::TextObject) -> (Vec, kurbo::BezPath) {
@@ -954,6 +1023,74 @@ pub(crate) fn clipping_text_outline(t: &Node) -> Option {
Some(Node { visible: t.visible, ..o })
}
+/// Clipping path `clip` of a clip group as a clipping path of the region it clips to
+/// ([`crate::clip_outline`]), with its id, name and visibility. For type that paints, the geometry
+/// effects of its fills and strokes reshape what they paint and leave that region as it is.
+/// `None` when it has nothing to clip by.
+pub(crate) fn clip_region_path(clip: &Node) -> Option {
+ let (bp, rule) = crate::clip_outline(clip)?;
+ let mut p = Node::path(clip.id, PathData::from_bezpath(&bp), Appearance::default());
+ if let NodeKind::Path { rule: r, clipping, .. } = &mut p.kind {
+ (*r, *clipping) = (rule, true);
+ }
+ p.name = clip.name.clone();
+ p.visible = clip.visible;
+ Some(p)
+}
+
+/// Knockout Group for clip group `m` turned into a group around `inner`, a clip group of its
+/// members, and its clipping path's strokes: `inner` takes `m`'s setting, so the clipped art knocks
+/// out as before, and `m` is set Off so the strokes paint over it, as the renderer draws them. A
+/// neutral `m` stays neutral, so both take the setting of the groups around them.
+pub(crate) fn knockout_inside(m: &mut Node, inner: &mut Node) {
+ inner.knockout = m.knockout;
+ if m.knockout != vectorcraft_doc::Knockout::Neutral {
+ m.knockout = vectorcraft_doc::Knockout::Off;
+ }
+}
+
+/// The clip group in `n` when `n` is a group or layer that [`paint_type_clip`] made of a clip
+/// group and its clipping type's strokes: a group that does not clip whose first member is a clip
+/// group with `n`'s id and whose second member has the id of that clip group's clipping path. The
+/// clip group's region is what `n` stands for, as the clip group it was made from: the strokes
+/// paint outside it and add nothing to its outline ([`crate::member_shapes`]) or its bounds
+/// ([`clip_bounds`]).
+pub(crate) fn painted_clip_inner(n: &Node) -> Option<&Node> {
+ if n.clips() || !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) {
+ return None;
+ }
+ let [inner, stroke, ..] = n.children()?.as_slice() else { return None };
+ let clip = inner.children()?.first()?;
+ (inner.clips() && inner.id == n.id && stroke.id == clip.id && !stroke.clips()).then_some(&**inner)
+}
+
+/// The geometric bounds of `n` ([`Node::geometric_bounds`]) with each group or layer in it that
+/// [`painted_clip_inner`] finds measured as its clip group, so the strokes of a clipping type
+/// outside the clip do not widen them.
+pub(crate) fn clip_bounds(n: &Node) -> Option {
+ fn holds(n: &Node) -> bool {
+ painted_clip_inner(n).is_some() || n.children().into_iter().flatten().any(|c| holds(c))
+ }
+ fn unwrap(n: &mut Node) {
+ if let Some(inner) = painted_clip_inner(n) {
+ let mut inner = inner.clone();
+ inner.visible = n.visible;
+ *n = inner;
+ }
+ for c in n.children_mut().into_iter().flatten() {
+ if holds(c) {
+ unwrap(Arc::make_mut(c));
+ }
+ }
+ }
+ if !holds(n) {
+ return n.geometric_bounds();
+ }
+ let mut probe = n.clone();
+ unwrap(&mut probe);
+ probe.geometric_bounds()
+}
+
/// Replace type anywhere inside `n` by its outlines, as art that keeps the type's look
/// ([`as_art`]). Type in a clip group's clipping path (all of `n` when `clipping` is set) becomes
/// its outlines with its visibility and effects ([`clipping_text_outline`]), and its fills and
@@ -981,32 +1118,41 @@ pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping
}
/// When `n` is a clip group or clipping layer whose clipping path is type that paints
-/// ([`Node::clip_paint`]), make it the art the canvas draws for it: the type's outlines clip
-/// ([`clipping_text_outline`]), its fills as art ([`as_art`]) paint behind the clipped art inside
-/// the clip, and its strokes as art paint over it, outside the clip, in a group that `n` becomes
-/// (keeping its id, name and transparency) with the clip group inside. The other members stay as
-/// they are. Hidden type paints nothing.
+/// ([`Node::clip_paint`]), make it the art the canvas draws for it: a path of the region the type
+/// clips to clips ([`clip_region_path`]), its fills as art ([`as_art`]) paint behind the clipped
+/// art inside the clip, and its strokes as art paint over it, outside the clip. Each part is the
+/// type's art with only those fills or strokes, their own geometry effects applied. With strokes,
+/// `n` becomes a group (keeping its id, name, visibility and transparency) that holds a clip group
+/// of the clipping path, the fills and the other members, with `n`'s id, then the strokes; a
+/// clipping layer keeps its ruler guides last. [`knockout_inside`] sets the Knockout Group of both,
+/// and [`painted_clip_inner`] finds that clip group. The other members stay as they are. Hidden
+/// type paints nothing.
pub(crate) fn paint_type_clip(doc: Option<&Document>, n: &mut Node) {
- let Some((first, rest)) = n.children().and_then(|ch| ch.split_first()) else { return };
- if !n.clips() || !matches!(first.kind, NodeKind::Text(_)) || !first.visible {
+ let Some(first) = n.children().and_then(|ch| ch.first()).filter(|_| n.clips()) else { return };
+ if !matches!(first.kind, NodeKind::Text(_)) || !first.visible {
return;
}
let paint = first.clip_paint();
if paint.fill.is_none() && paint.stroke.is_none() {
return;
}
- let Some(clip) = clipping_text_outline(first) else { return };
+ let Some(clip) = clip_region_path(first) else { return };
let art = |part: Option| part.and_then(|p| as_art(doc, &p, None)).map(Arc::new);
- let members: Vec> = std::iter::once(Arc::new(clip)).chain(art(paint.fill)).chain(rest.iter().cloned()).collect();
- let stroke = art(paint.stroke);
+ let (fill, stroke) = (art(paint.fill), art(paint.stroke));
let id = n.id;
- match (&mut n.kind, stroke) {
- (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }, None) => *children = members,
- (NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. }, Some(stroke)) => {
- *children = vec![Arc::new(Node::new(id, NodeKind::Group { children: members, clip: true })), stroke];
- *clip = false;
- }
- _ => {}
+ let Some(ch) = n.children_mut() else { return };
+ let Some(slot) = ch.first_mut() else { return };
+ *slot = Arc::new(clip);
+ if let Some(fill) = fill {
+ ch.insert(1, fill);
+ }
+ let Some(stroke) = stroke else { return };
+ let guides = ch.split_off(Node::guide_run_start(ch));
+ let mut inner = Node::new(id, NodeKind::Group { children: std::mem::take(ch), clip: true });
+ knockout_inside(n, &mut inner);
+ if let NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } = &mut n.kind {
+ *children = [Arc::new(inner), stroke].into_iter().chain(guides).collect();
+ *clip = false;
}
}
@@ -1822,7 +1968,7 @@ impl Step<'_> {
if !groups.is_empty() {
carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, params, bounds, from, to, seed));
}
- let drawn = warped.as_deref().map_or_else(|| art.geometric_bounds(), |w| w.bounds(art));
+ let drawn = warped.as_deref().map_or_else(|| clip_bounds(art), |w| w.bounds(art));
let whole = (follows && !held).then(|| crate::Carry::of(&e.id, params, bounds, Some(bounds), drawn, seed));
Ran { kept: !kept_ids.is_empty(), took, masks, short, whole }
}
@@ -3247,6 +3393,9 @@ fn group_marks(
NodeKind::Image(_) => (images.map_or_else(|| n.geometric_bounds(), |w| w.image_bounds(n)), false),
NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } if !n.extras().type_outlines => {
let layer = matches!(n.kind, NodeKind::Layer { .. });
+ // A clip group whose clipping type's strokes paint around it is measured as that clip
+ // group: the strokes outside the clip do not widen it ([`clip_bounds`]).
+ let clip = *clip || painted_clip_inner(n).is_some();
let skip = children.len().saturating_sub(n.editing_children().len());
let (mut bounds, mut held) = (None, false);
for (i, c) in children.iter().enumerate() {
@@ -3257,7 +3406,7 @@ fn group_marks(
}
at.pop();
// Only members measured in the bounds hold the group's gradients in place.
- let counts = if *clip { i == 0 } else { i >= skip && (c.visible || !layer) };
+ let counts = if clip { i == 0 } else { i >= skip && (c.visible || !layer) };
if counts {
bounds = vectorcraft_geom::union_opt(bounds, b);
held |= h;
@@ -3473,16 +3622,17 @@ impl WarpedImages {
/// The geometric bounds of `art` as it draws after the effects so far: each image this table
/// lists measured by the pieces the warps and moves it took would cut it into, when the art
- /// has room for them ([`cut_warped_images`]).
+ /// has room for them ([`cut_warped_images`]). The strokes of clipping type outside its clip
+ /// are left out ([`clip_bounds`]).
pub(crate) fn bounds(&self, art: &Node) -> Option {
if self.images.is_empty() || !self.fits(art, crate::distort::MAX_COPY_OBJECTS) {
- return art.geometric_bounds();
+ return clip_bounds(art);
}
// The pieces the images would be cut into now: each group of pieces is shown or hidden as
// its image is, and hidden objects are left out of a layer's bounds.
let mut probe = art.clone();
restore_warped_images(&mut probe, self, true);
- probe.geometric_bounds()
+ clip_bounds(&probe)
}
/// The geometric bounds of image `n`: when this table lists it, measured by the pieces the
diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs
index 52b38f986d..2a34fb1d07 100644
--- a/crates/effects/src/tests.rs
+++ b/crates/effects/src/tests.rs
@@ -1708,6 +1708,115 @@ fn twist_joins_its_pieces_smoothly() {
}
}
+#[test]
+fn twist_boundary_handles_follow_the_inward_tangent() {
+ let line = PathData::single(SubPath::polyline(&[Point::new(40.0, 30.0), Point::new(60.0, 30.0)], false));
+ let bounds = Rect::new(40.0, 30.0, 60.0, 30.0);
+ for angle in [90.0_f64, 400.0, -720.0] {
+ let out = apply_geometry(&[fx("distort.twist", json!({"angle": angle}))], &line, bounds);
+ let anchors = &out.subpaths[0].anchors;
+ let start = anchors.first().unwrap();
+ let end = anchors.last().unwrap();
+ assert_eq!(start.p, Point::new(40.0, 30.0));
+ assert_eq!(end.p, Point::new(60.0, 30.0));
+ for (actual, expected) in [
+ (start.h_out - start.p, vectorcraft_geom::Vec2::new(1.0, -angle.to_radians())),
+ (end.h_in - end.p, vectorcraft_geom::Vec2::new(-1.0, angle.to_radians())),
+ ] {
+ assert!(actual.hypot() > 1e-9);
+ let error = (actual.x * expected.y - actual.y * expected.x).atan2(actual.dot(expected)).to_degrees().abs();
+ assert!(error < 0.05, "{angle} degrees: boundary tangent differs by {error} degrees");
+ }
+ }
+}
+
+#[test]
+fn twist_large_coordinate_joins_preserve_boundary_sides() {
+ use vectorcraft_geom::Anchor;
+
+ let center = 1e16;
+ for offset in [32.0, 64.0] {
+ let p = Point::new(center + offset, 0.0);
+ let line = PathData::single(SubPath::new(
+ vec![
+ Anchor::corner(Point::new(p.x - 18.0, 0.0)),
+ Anchor::with_handles(p, Point::new(p.x - 6.0, 0.0), Point::new(p.x + 6.0, 0.0)),
+ Anchor::corner(Point::new(p.x + 18.0, 0.0)),
+ ],
+ false,
+ ));
+ let out = crate::distort::twist(&line, Rect::new(center - 64.0, 0.0, center + 64.0, 0.0), 90.0, 3);
+ let join = &out.subpaths[0].anchors[1];
+ if offset == 64.0 {
+ assert_eq!(join.h_out, Point::new(p.x + 6.0, 0.0));
+ let actual = join.h_in - join.p;
+ let expected = vectorcraft_geom::Vec2::new(-1.0, std::f64::consts::FRAC_PI_2);
+ let error = actual.cross(expected).atan2(actual.dot(expected)).abs();
+ assert!(error < 1e-9, "{actual:?}");
+ } else {
+ let incoming = join.p - join.h_in;
+ let outgoing = join.h_out - join.p;
+ assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}");
+ assert!(incoming.dot(outgoing) > 0.0);
+ }
+ }
+}
+
+#[test]
+fn twist_fractional_boundary_handles_use_each_sides_derivative() {
+ use vectorcraft_geom::Anchor;
+
+ for (bounds, step) in [(Rect::new(40.1, 30.0, 60.3, 30.0), 1.0), (Rect::new(-60.3, 30.0, -40.1, 30.0), 1.0)] {
+ for x in [bounds.x0, bounds.x1] {
+ for angle in [90.0_f64, 400.0, -720.0] {
+ let p = Point::new(x, 30.0);
+ let line = PathData::single(SubPath::new(
+ vec![
+ Anchor::corner(Point::new(x - 3.0 * step, 30.0)),
+ Anchor::with_handles(p, Point::new(x - step, 30.0), Point::new(x + step, 30.0)),
+ Anchor::corner(Point::new(x + 3.0 * step, 30.0)),
+ ],
+ false,
+ ));
+ let out = crate::distort::twist(&line, bounds, angle, 3);
+ assert!(
+ out.subpaths[0].anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()),
+ "x={x} angle={angle}: {:?}",
+ out.subpaths[0].anchors
+ );
+ let join = &out.subpaths[0].anchors[1];
+ assert!(join.p.distance(p) < 1e-10, "{:?}", join.p);
+ let a = angle.to_radians();
+ let expected = if x == bounds.x0 { [(-1.0, 0.0), (1.0, -a)] } else { [(-1.0, a), (1.0, 0.0)] };
+ for (actual, (dx, dy)) in [join.h_in - join.p, join.h_out - join.p].into_iter().zip(expected) {
+ let expected = vectorcraft_geom::Vec2::new(dx, dy);
+ let error = actual.cross(expected).atan2(actual.dot(expected)).abs();
+ assert!(error < 1e-9, "x={x} angle={angle}: {actual:?}, join={join:?}, source={:?}", line.subpaths[0].anchors[1]);
+ }
+ }
+ }
+ }
+ let bounds = Rect::new(1e16, 30.0, 1e16 + 18.0, 30.0);
+ let center = bounds.center();
+ let line = PathData::single(SubPath::polyline(&[Point::new(center.x - 4.0, center.y), center, Point::new(center.x + 4.0, center.y)], false));
+ let out = crate::distort::twist(&line, bounds, 90.0, 3);
+ assert_eq!(out.subpaths[0].anchors[1].p, center);
+ let bounds = Rect::new(0.0, 30.0, 2e16, 30.0);
+ let p = Point::new(bounds.x1 - 8.0, 30.0);
+ let line = PathData::single(SubPath::new(
+ vec![
+ Anchor::corner(Point::new(p.x - 12.0, p.y)),
+ Anchor::with_handles(p, Point::new(p.x - 4.0, p.y), Point::new(p.x + 4.0, p.y)),
+ Anchor::corner(Point::new(p.x + 12.0, p.y)),
+ ],
+ false,
+ ));
+ let out = crate::distort::twist(&line, bounds, 90.0, 3);
+ let join = &out.subpaths[0].anchors[1];
+ assert!(join.p.y - p.y > 10.0, "{:?}", join.p);
+ assert!(join.h_out.y - join.p.y < -4.0, "{join:?}");
+}
+
#[test]
fn twist_fixes_the_outer_circle_and_rotates_inside() {
let out = run("distort.twist", json!({"angle": 0}), &square());
diff --git a/crates/effects/src/tests/clipfx.rs b/crates/effects/src/tests/clipfx.rs
index 57566fbb28..d13c59f229 100644
--- a/crates/effects/src/tests/clipfx.rs
+++ b/crates/effects/src/tests/clipfx.rs
@@ -543,3 +543,337 @@ fn raster_and_hidden_effects_leave_the_clip_as_it_is() {
assert_eq!(bounds(&clipping_path(1, effects)), Rect::new(50.0, 50.0, 150.0, 150.0));
}
}
+
+fn blue() -> Paint {
+ Paint::solid(Color::rgb(0.0, 0.0, 1.0))
+}
+
+fn green() -> Paint {
+ Paint::solid(Color::rgb(0.0, 1.0, 0.0))
+}
+
+/// "IIII" at 40 pt from (5, 60) in a test font built from the bundled Source Sans 3
+/// ([`vectorcraft_text::test_fonts::height_font`]), its characters filled blue when `fill` and
+/// stroked green 2 pt wide when `stroke`.
+fn painted_type(id: u64, fill: bool, stroke: bool) -> Node {
+ use vectorcraft_doc::text::{CharStyle, TextObject};
+ use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
+ static FONT: std::sync::Once = std::sync::Once::new();
+ FONT.call_once(|| {
+ vectorcraft_text::FontDb::global().add_font(height_font(true).expect("the test font builds"));
+ });
+ let style = CharStyle {
+ font_family: HEIGHT_FAMILY.into(),
+ size: 40.0,
+ fill: if fill { blue() } else { Paint::None },
+ stroke: if stroke { green() } else { Paint::None },
+ stroke_width: 2.0,
+ ..Default::default()
+ };
+ Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(vectorcraft_geom::Point::new(5.0, 60.0), "IIII", style))))
+}
+
+/// Does `n` or an object in it have a blue fill (`fill`) or a green stroke?
+fn paints(n: &Node, fill: bool) -> bool {
+ use vectorcraft_doc::AppearanceItem;
+ let own = n.appearance.items.iter().any(|i| match i {
+ AppearanceItem::Fill(f) => fill && f.paint == blue(),
+ AppearanceItem::Stroke(s) => !fill && s.paint == green() && s.width > 0.0,
+ });
+ own || n.children().into_iter().flatten().any(|c| paints(c, fill))
+}
+
+/// What the first clip group in `n` paints: the bounds of the region it clips to, the bounds of
+/// the blue fill art right after its clipping path (behind the clipped art), the bounds of the
+/// green stroke art right after the clip group (over it, outside the clip), and whether a green
+/// stroke paints inside the clip group.
+type Painted = (Rect, Option, Option, bool);
+
+fn painted_clip(n: &Node) -> Option {
+ let ch = n.children()?;
+ for (i, c) in ch.iter().enumerate() {
+ if let NodeKind::Group { children, clip: true } = &c.kind {
+ let region = clip_outline(children.first()?)?.0.bounding_box();
+ let fill = children.get(1).filter(|f| paints(f, true)).and_then(|f| f.geometric_bounds());
+ let stroke = ch.get(i + 1).filter(|s| paints(s, false)).and_then(|s| s.geometric_bounds());
+ let inside = children.iter().skip(1).any(|m| paints(m, false));
+ return Some((region, fill, stroke, inside));
+ }
+ if let Some(found) = painted_clip(c) {
+ return Some(found);
+ }
+ }
+ None
+}
+
+fn near_rect(a: Rect, b: Rect) -> bool {
+ (a.x0 - b.x0).abs() < 0.5 && (a.y0 - b.y0).abs() < 0.5 && (a.x1 - b.x1).abs() < 0.5 && (a.y1 - b.y1).abs() < 0.5
+}
+
+#[test]
+fn painted_clipping_type_survives_enclosing_geometry_effect() {
+ // Type that paints a fill, a stroke, both or neither clips a red square, in a group whose
+ // Transform (moving everything 10 pt down, beside other type that stays type in the export) or
+ // Offset Path reshapes its members: the canvas and the export keep the type's fill as art
+ // behind the square inside the clip and its stroke as art over the clip group, both reshaped
+ // with the clip.
+ let plain = clip_outline(&painted_type(3, false, false)).expect("the type clips").0.bounding_box();
+ assert!(plain.width() > 10.0 && plain.height() > 10.0, "the type has glyph outlines: {plain:?}");
+ let effects = [fx("distort.transform", json!({"moveV": 10})), fx("path.offsetPath", json!({"offset": 1}))];
+ for effect in effects {
+ for (fill, stroke) in [(true, false), (false, true), (true, true), (false, false)] {
+ let clipped = clip_group(2, painted_type(3, fill, stroke));
+ let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped), Arc::new(painted_type(5, true, false))]);
+ outer.appearance.effects.push(effect.clone());
+ let canvas = crate::evaluate_container(None, &outer).unwrap();
+ let mut d = Document::new(400.0, 400.0);
+ let layer = d.layers[0].id;
+ d.insert(Some(layer), 0, outer).unwrap();
+ let baked = bake_document(&d).unwrap();
+ let exported = baked.layers.iter().find_map(|l| painted_clip(l));
+ for (what, found) in [("canvas", painted_clip(&canvas)), ("export", exported)] {
+ let case = format!("{what}, {}, fill {fill}, stroke {stroke}", effect.id);
+ let (region, fills, strokes, inside) = found.unwrap_or_else(|| panic!("{case}: no clip group"));
+ if effect.id == "distort.transform" {
+ assert!((region.y0 - plain.y0 - 10.0).abs() < 0.5 && (region.x0 - plain.x0).abs() < 0.5, "{case}: {region:?} from {plain:?}");
+ } else {
+ let grown = Rect::new(plain.x0 - 1.0, plain.y0 - 1.0, plain.x1 + 1.0, plain.y1 + 1.0);
+ assert!(near_rect(region, grown), "{case}: {region:?} is {plain:?} offset by 1 pt");
+ }
+ assert_eq!(fills.is_some(), fill, "{case}: fill art {fills:?}");
+ assert_eq!(strokes.is_some(), stroke, "{case}: stroke art {strokes:?}");
+ assert!(!inside, "{case}: the stroke paints outside the clip");
+ for art in fills.into_iter().chain(strokes) {
+ assert!(near_rect(art, region), "{case}: the paint {art:?} follows the clip {region:?}");
+ }
+ }
+ }
+ }
+}
+
+/// The group in `n` that holds a clip group and then the green stroke art of its clipping type,
+/// with that clip group.
+fn stroke_wrapper(n: &Node) -> Option<(&Node, &Node)> {
+ let ch = n.children()?;
+ if let [inner, stroke, ..] = ch.as_slice()
+ && matches!(inner.kind, NodeKind::Group { clip: true, .. })
+ && !n.clips()
+ && paints(stroke, false)
+ {
+ return Some((n, inner));
+ }
+ ch.iter().find_map(|c| stroke_wrapper(c))
+}
+
+#[test]
+fn clipping_type_strokes_paint_over_a_knockout_clip_group() {
+ // A clip group set to Knockout Group On, Off or neutral, clipped by type that strokes: its
+ // clipped art knocks out as the clip group says, and the type's stroke paints over it without
+ // knocking it out, as the canvas draws the live clip group. The type is reshaped by a group's
+ // Transform around it, or by its own Offset Path.
+ use vectorcraft_doc::Knockout;
+ for (knockout, around) in [(Knockout::On, Knockout::Off), (Knockout::Off, Knockout::Off), (Knockout::Neutral, Knockout::Neutral)] {
+ for own in [false, true] {
+ let mut ty = painted_type(3, true, true);
+ if own {
+ ty.appearance.effects.push(fx("path.offsetPath", json!({"offset": 1})));
+ }
+ let mut clipped = clip_group(2, ty);
+ clipped.knockout = knockout;
+ let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped)]);
+ if !own {
+ outer.appearance.effects.push(fx("distort.transform", json!({"moveV": 10})));
+ }
+ let mut d = Document::new(400.0, 400.0);
+ let layer = d.layers[0].id;
+ d.insert(Some(layer), 0, outer.clone()).unwrap();
+ let baked = bake_document(&d).unwrap();
+ let canvas = if own { None } else { crate::evaluate_container(None, &outer) };
+ let exported = baked.layers.iter().find_map(|l| stroke_wrapper(l));
+ for (what, found) in [("canvas", canvas.as_ref().and_then(stroke_wrapper)), ("export", exported)] {
+ if own && what == "canvas" {
+ continue;
+ }
+ let case = format!("{what}, own effect {own}, knockout {knockout:?}");
+ let (wrapper, inner) = found.unwrap_or_else(|| panic!("{case}: no group around the clip"));
+ assert_eq!(inner.knockout, knockout, "{case}: the clipped art knocks out as before");
+ assert_eq!(wrapper.knockout, around, "{case}: the stroke does not knock out the clipped art");
+ }
+ }
+ }
+}
+
+#[test]
+fn a_clip_groups_own_fill_stays_in_the_clip_when_its_clipping_type_strokes() {
+ // A clip group with a yellow fill of its own and an Offset Path effect, clipped by type that
+ // strokes: the group's fill still paints inside the clip, and the type's stroke over it.
+ let yellow = Paint::solid(Color::rgb(1.0, 1.0, 0.0));
+ let mut group = clip_group(2, painted_type(3, false, true));
+ group.appearance =
+ Appearance { effects: vec![fx("path.offsetPath", json!({"offset": 0}))], ..Appearance::basic(yellow.clone(), Paint::None, 0.0) }.into();
+ let canvas = crate::evaluate_container(None, &group).unwrap();
+ let (_, _, strokes, inside) = painted_clip(&Node::group(NodeId(9), vec![Arc::new(canvas.clone())])).unwrap();
+ assert!(strokes.is_some() && !inside, "{canvas:?}");
+ let NodeKind::Group { children, clip: false } = &canvas.kind else { panic!("not a group around the clip: {canvas:?}") };
+ let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("no clip group first: {children:?}") };
+ let yellow_in = |n: &Node| n.appearance.items.iter().any(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(f) if f.paint == yellow));
+ assert!(clipped.iter().skip(1).any(|c| yellow_in(c)), "the group's fill paints inside the clip: {clipped:?}");
+ assert!(!children.iter().skip(1).any(|c| yellow_in(c)), "{children:?}");
+}
+
+#[test]
+fn a_clip_groups_own_gradient_spans_the_clip_when_its_clipping_type_strokes() {
+ // A clip group with an unplaced linear gradient fill of its own and an Offset Path effect,
+ // clipped by type with a stroke whose Transform effect moves it 60 pt right: the gradient
+ // spans the region the clipping path clips to.
+ use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
+ let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
+ let unplaced = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
+ let mut ty = painted_type(3, false, false);
+ ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into();
+ for item in &mut ty.appearance.items {
+ if let vectorcraft_doc::AppearanceItem::Stroke(s) = item {
+ s.effects.push(fx("distort.transform", json!({"moveH": 60})));
+ }
+ }
+ let mut group = clip_group(2, ty);
+ group.appearance =
+ Appearance { effects: vec![fx("path.offsetPath", json!({"offset": 0}))], ..Appearance::basic(unplaced, Paint::None, 0.0) }.into();
+ let canvas = crate::evaluate_container(None, &group).unwrap();
+ let NodeKind::Group { children, clip: false } = &canvas.kind else { panic!("not a group around the clip: {canvas:?}") };
+ let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("no clip group first: {children:?}") };
+ let region = clip_outline(&clipped[0]).expect("the type clips").0.bounding_box();
+ let fill = clipped.iter().skip(1).find_map(|c| match c.appearance.fill_paint() {
+ Paint::Gradient(g) => g.geom,
+ _ => None,
+ });
+ let geom = fill.unwrap_or_else(|| panic!("no gradient fill inside the clip: {clipped:?}"));
+ let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x));
+ assert!((left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5, "the gradient {geom:?} spans the clip {region:?}");
+}
+
+#[test]
+fn a_groups_own_fill_paints_only_the_clip_of_clipping_type_whose_stroke_moves() {
+ // A group with a fill of its own (solid, or an unplaced linear gradient) and a Transform effect
+ // (moving everything 10 pt down, or scaling it to half its width around its middle) holds a
+ // clip group clipped by type whose stroke has a Transform effect moving it 60 pt right,
+ // outside the clip. On the canvas and in the export, the clip region is the type's glyphs
+ // reshaped by the group's effect, and the group's fill paints that region alone, its gradient
+ // spanning it: the moved stroke adds nothing to the region, the fill or the box the group's
+ // effect scales around.
+ use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
+ let yellow = Paint::solid(Color::rgb(1.0, 1.0, 0.0));
+ let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
+ let unplaced = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
+ let mut ty = painted_type(3, false, false);
+ ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into();
+ for item in &mut ty.appearance.items {
+ if let vectorcraft_doc::AppearanceItem::Stroke(s) = item {
+ s.effects.push(fx("distort.transform", json!({"moveH": 60})));
+ }
+ }
+ let live = clip_outline(&ty).expect("the type clips").0.bounding_box();
+ let moved = Rect::new(live.x0, live.y0 + 10.0, live.x1, live.y1 + 10.0);
+ // Scaled to half its width around the middle of the clip, which the stroke does not move.
+ let (mid, quarter) = ((live.x0 + live.x1) / 2.0, live.width() / 4.0);
+ let narrowed = Rect::new(mid - quarter, live.y0, mid + quarter, live.y1);
+ // The group's own fill art: every object outside the clip groups whose own fill is `paint`.
+ fn own_fills<'a>(n: &'a Node, paint: &Paint, out: &mut Vec<&'a Node>) {
+ let mine = n.appearance.items.iter().any(|i| match (i, paint) {
+ (vectorcraft_doc::AppearanceItem::Fill(f), Paint::Gradient(_)) => matches!(f.paint, Paint::Gradient(_)),
+ (vectorcraft_doc::AppearanceItem::Fill(f), p) => f.paint == *p,
+ _ => false,
+ });
+ if mine {
+ out.push(n);
+ }
+ for c in n.children().into_iter().flatten().filter(|c| !c.clips()) {
+ own_fills(c, paint, out);
+ }
+ }
+ let cases = [(json!({"moveV": 10}), moved), (json!({"scaleH": 50, "scaleV": 100}), narrowed)];
+ for ((params, region), paint) in cases.iter().flat_map(|c| [yellow.clone(), unplaced.clone()].map(|p| (c.clone(), p))) {
+ let mut outer = Node::group(NodeId(1), vec![Arc::new(clip_group(2, ty.clone()))]);
+ outer.appearance =
+ Appearance { effects: vec![fx("distort.transform", params.clone())], ..Appearance::basic(paint.clone(), Paint::None, 0.0) }.into();
+ let canvas = crate::evaluate_container(None, &outer).unwrap();
+ let mut d = Document::new(400.0, 400.0);
+ let layer = d.layers[0].id;
+ d.insert(Some(layer), 0, outer).unwrap();
+ let baked = bake_document(&d).unwrap();
+ let exported = baked.layers[0].children().and_then(|ch| ch.first()).cloned().expect("the export holds the group");
+ for (what, art) in [("canvas", &canvas), ("export", &*exported)] {
+ let case = format!("{what}, {params}, {}", if matches!(paint, Paint::Gradient(_)) { "gradient" } else { "solid" });
+ let (clip, _, strokes, _) = painted_clip(art).unwrap_or_else(|| panic!("{case}: no clip group in {art:?}"));
+ assert!(near_rect(clip, region), "{case}: the clip {clip:?} is the type's glyphs reshaped {region:?}");
+ let strokes = strokes.unwrap_or_else(|| panic!("{case}: no stroke art"));
+ assert!(strokes.x1 > region.x1 + 25.0, "{case}: the stroke {strokes:?} moves outside the clip {region:?}");
+ let mut fills = vec![];
+ own_fills(art, &paint, &mut fills);
+ assert!(!fills.is_empty(), "{case}: no fill art of the group in {art:?}");
+ let painted = fills.iter().filter_map(|f| f.geometric_bounds()).reduce(|a, b| a.union(b)).unwrap();
+ assert!(near_rect(painted, region), "{case}: the group's fill {painted:?} paints the clip {region:?}");
+ if let Paint::Gradient(_) = paint {
+ for fill in fills {
+ let geom = match fill.appearance.fill_paint() {
+ Paint::Gradient(g) => g.geom,
+ _ => None,
+ };
+ let geom = geom.unwrap_or_else(|| panic!("{case}: the gradient is not placed: {fill:?}"));
+ let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x));
+ assert!(
+ (left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5,
+ "{case}: the gradient {geom:?} spans the clip {region:?}"
+ );
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn a_clip_groups_placed_gradient_follows_free_distort_by_the_clip_when_its_clipping_type_strokes() {
+ // A clip group with a placed linear gradient fill of its own, in a group with Free Distort,
+ // clipped by type whose stroke has a Transform effect moving it 60 pt right, outside the clip:
+ // the gradient moves and scales from the clip's bounds, as for the same clip group whose type
+ // does not stroke. The moved stroke adds nothing to those bounds.
+ use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
+ let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
+ let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
+ let geom = GradientGeom { start: (10.0, 45.0).into(), end: (30.0, 45.0).into(), aspect: 1.0, focal: None };
+ let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }));
+ fn placed_geom(n: &Node) -> Option {
+ if let Paint::Gradient(g) = n.appearance.fill_paint()
+ && g.geom.is_some()
+ {
+ return g.geom;
+ }
+ n.children().into_iter().flatten().find_map(|c| placed_geom(c))
+ }
+ let ends = |stroke: bool| {
+ let mut ty = painted_type(3, false, false);
+ if stroke {
+ ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into();
+ for item in &mut ty.appearance.items {
+ if let vectorcraft_doc::AppearanceItem::Stroke(s) = item {
+ s.effects.push(fx("distort.transform", json!({"moveH": 60})));
+ }
+ }
+ }
+ let mut group = clip_group(2, ty);
+ group.appearance = Appearance::basic(placed.clone(), Paint::None, 0.0).into();
+ let mut outer = Node::group(NodeId(1), vec![Arc::new(group)]);
+ let corners = json!({"corners": [[1.0 / 3.0, 0.0], [4.0 / 3.0, 0.0], [1.0, 1.0], [0.0, 1.0]]});
+ outer.appearance.effects.push(fx("distort.freeDistort", corners));
+ let canvas = crate::evaluate_container(None, &outer).unwrap();
+ if stroke {
+ assert!(stroke_wrapper(&canvas).is_some(), "the type's stroke paints around the clip: {canvas:?}");
+ }
+ placed_geom(&canvas).unwrap_or_else(|| panic!("no placed gradient: {canvas:?}"))
+ };
+ let (plain, stroked) = (ends(false), ends(true));
+ assert!(
+ plain.start.distance(stroked.start) < 0.5 && plain.end.distance(stroked.end) < 0.5,
+ "the gradient {stroked:?} follows the clip as {plain:?} does"
+ );
+}
diff --git a/crates/effects/src/util.rs b/crates/effects/src/util.rs
index de203b4955..6b79d19999 100644
--- a/crates/effects/src/util.rs
+++ b/crates/effects/src/util.rs
@@ -71,7 +71,7 @@ pub fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez {
/// Non-linear path mapping (shared with live envelopes in `vectorcraft-doc`), and the split of
/// segments into pieces within an anchor budget.
-pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, map_smooth_within, pieces};
+pub use vectorcraft_doc::live::{fit_piece, map_handles_within, map_nonlinear_within, pieces};
/// About how many lines the renderer flattens `path` into at 1 px/pt: one for a straight
/// segment, and for a curve the count Wang's formula gives at vello's tolerance of 0.25 px,
diff --git a/crates/engine/examples/layer_select_bench.rs b/crates/engine/examples/layer_select_bench.rs
new file mode 100644
index 0000000000..256cada3af
--- /dev/null
+++ b/crates/engine/examples/layer_select_bench.rs
@@ -0,0 +1,154 @@
+//! `cargo run --release -p vectorcraft-engine --example layer_select_bench` prints the time of a
+//! Shift-click in the Layers panel's selection column (`layer.selectAll {id, add: true}`) on a layer of
+//! 2,000, 20,000 and 50,000 rectangles, with all of its art selected (the click removes it) and with
+//! every other object selected (the click adds the rest). Each case is timed one id at a time (`old`,
+//! the loop the command used before, copied here) and in one pass (`new`), side by side in one
+//! process: first the whole command, then the selection step alone. Each case checks that both give
+//! the same selection and reply before it is timed.
+//! `ITERS` sets the runs per case (default 7); each row is the median wall time in ms, followed by
+//! every run of `old` and of `new`.
+// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
+#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
+
+use std::collections::HashSet;
+use std::hint::black_box;
+use std::time::Instant;
+
+use serde_json::{Value, json};
+use vectorcraft_color::{Color, Paint};
+use vectorcraft_doc::{Appearance, Document, Node, NodeId, Selection};
+use vectorcraft_engine::Session;
+use vectorcraft_geom::{Anchor, PathData, Point, SubPath};
+
+fn iters() -> usize {
+ std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
+}
+
+fn median(ms: &[f64]) -> f64 {
+ let mut ms = ms.to_vec();
+ ms.sort_by(f64::total_cmp);
+ ms[ms.len() / 2]
+}
+
+/// A document whose first layer holds `n` 10 pt squares in a row → (document, layer, squares).
+fn squares(n: usize) -> (Document, NodeId, Vec) {
+ let mut doc = Document::new(1600.0, 1200.0);
+ let layer = doc.layers[0].id;
+ let ids = (0..n)
+ .map(|i| {
+ let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0);
+ let corners = [(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)];
+ let path = PathData::single(SubPath::new(corners.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true));
+ let id = doc.alloc_id();
+ doc.insert(Some(layer), usize::MAX, Node::path(id, path, Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0))).unwrap();
+ id
+ })
+ .collect();
+ (doc, layer, ids)
+}
+
+/// `layer.selectAll {id: layer, add: true}` before the change: the layer's art checked, removed or
+/// added one id at a time with [`Selection::contains`], [`Selection::remove`] and [`Selection::add`].
+fn old_command(s: &mut Session, layer: NodeId) -> Value {
+ let st = s.doc().unwrap();
+ let ids = st.doc.node(layer).unwrap().layer_art(true);
+ let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i));
+ let rows = st.layer_rows.clone();
+ s.select(|_, sel| old_step(sel, &ids, all_selected)).unwrap();
+ let st = s.doc_mut().unwrap();
+ st.layer_rows = rows;
+ json!({ "selected": st.selection.objects.iter().map(|i| i.0).collect::>() })
+}
+
+fn old_step(sel: &mut Selection, ids: &[NodeId], all_selected: bool) {
+ for i in ids {
+ if all_selected { sel.remove(*i) } else { sel.add(*i) }
+ }
+}
+
+fn new_command(s: &mut Session, layer: NodeId) -> Value {
+ s.execute("layer.selectAll", &json!({"id": layer.0, "add": true})).unwrap()
+}
+
+/// Every run of `old` and of `new`, run in turn, each from `prepare`'s state.
+fn time(mut prepare: impl FnMut() -> S, old: impl Fn(&mut S), new: impl Fn(&mut S)) -> (Vec, Vec) {
+ let run = |s: &mut S, f: &dyn Fn(&mut S)| {
+ let t = Instant::now();
+ f(s);
+ t.elapsed().as_secs_f64() * 1000.0
+ };
+ let (mut olds, mut news) = (Vec::new(), Vec::new());
+ for _ in 0..iters() {
+ let mut s = prepare();
+ olds.push(run(&mut s, &old));
+ black_box(&s);
+ let mut s = prepare();
+ news.push(run(&mut s, &new));
+ black_box(&s);
+ }
+ (olds, news)
+}
+
+fn row(name: &str, (old, new): (Vec, Vec)) {
+ let (o, n) = (median(&old), median(&new));
+ let list = |ms: &[f64]| ms.iter().map(|m| format!("{m:.2}")).collect::>().join(" ");
+ println!(" {name:<40} {o:>12.3} ms {n:>12.3} ms {:>9.1}x", o / n.max(1e-9));
+ println!(" old runs: {}", list(&old));
+ println!(" new runs: {}", list(&new));
+}
+
+fn main() {
+ println!(" {:<40} {:>15} {:>15} {:>10}", "case", "old", "new", "speedup");
+ for n in [2_000usize, 20_000, 50_000] {
+ println!("{n} objects");
+ let (doc, layer, ids) = squares(n);
+ let mut s = Session::new();
+ s.add_document(doc, None);
+ let mut all = Selection::default();
+ all.set(ids.iter().copied());
+ let mut half = Selection::default();
+ half.set(ids.iter().copied().step_by(2));
+ for (name, start) in [("all selected (removes)", &all), ("half selected (adds)", &half)] {
+ let reset = |s: &mut Session| {
+ let st = s.doc_mut().unwrap();
+ st.selection = start.clone();
+ st.layer_rows.clear();
+ };
+ // Both ways give the same selection and reply.
+ reset(&mut s);
+ let old_reply = old_command(&mut s, layer);
+ let old_sel = s.doc().unwrap().selection.clone();
+ reset(&mut s);
+ let new_reply = new_command(&mut s, layer);
+ assert_eq!(s.doc().unwrap().selection, old_sel, "{name}: the same selection");
+ assert_eq!(new_reply, old_reply, "{name}: the same reply");
+
+ let (mut olds, mut news) = (Vec::new(), Vec::new());
+ for _ in 0..iters() {
+ for (f, ms) in [(old_command as fn(&mut Session, NodeId) -> Value, &mut olds), (new_command, &mut news)] {
+ reset(&mut s);
+ let t = Instant::now();
+ black_box(f(&mut s, layer));
+ ms.push(t.elapsed().as_secs_f64() * 1000.0);
+ }
+ }
+ row(&format!("command, {name}"), (olds, news));
+ // The selection step alone, on a copy of the starting selection.
+ let art = s.doc().unwrap().doc.node(layer).unwrap().layer_art(true);
+ let selected: HashSet = start.objects.iter().copied().collect();
+ let all_selected = art.iter().all(|i| selected.contains(i));
+ let new_step = |sel: &mut Selection| {
+ if all_selected {
+ sel.remove_all(art.iter().copied());
+ } else {
+ sel.add_all(art.iter().copied());
+ }
+ };
+ let (mut a, mut b) = (start.clone(), start.clone());
+ old_step(&mut a, &art, all_selected);
+ new_step(&mut b);
+ assert_eq!(a, b, "{name}: the same selection step");
+ row(&format!("selection step, {name}"), time(|| start.clone(), |sel| old_step(sel, &art, all_selected), new_step));
+ }
+ }
+}
diff --git a/crates/engine/examples/link_colors_bench.rs b/crates/engine/examples/link_colors_bench.rs
new file mode 100644
index 0000000000..d403339706
--- /dev/null
+++ b/crates/engine/examples/link_colors_bench.rs
@@ -0,0 +1,217 @@
+//! `cargo run --release -p vectorcraft-engine --example link_colors_bench` prints the time
+//! `Document::map_solid_paints_in` takes to link the paints of selected objects to swatches, as Add Used
+//! Colors and New Color Group do for the selection with global swatches, on synthetic documents: 2,000 and
+//! 20,000 rectangles in one layer, and 5,000 rectangles in 1,000 groups of groups, selected with and
+//! without the groups that hold them. The fills and strokes use 50 colors, each with a swatch to link to.
+//! For each it times two ways of finding the selected objects that no other selected object holds: a
+//! search of the id list for each ancestor of each id, and a lookup of each ancestor in a set of the ids
+//! (as `map_solid_paints_in` does). Both then link the same paints in the same loop. It checks that both
+//! give the same count, visit the same paints in the same order and leave the same document as
+//! `map_solid_paints_in` before it times them.
+//! `ITERS` sets the runs per row (default 7); the two ways run in alternating order, each run links 10
+//! fresh copies of the document, and each row is the median time of one call. On Linux the times are the CPU time of the main thread, which runs
+//! everything, in ms; elsewhere they are wall times.
+// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
+#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
+
+use std::collections::{HashMap, HashSet};
+use std::hint::black_box;
+use std::sync::Arc;
+use std::time::Instant;
+
+use vectorcraft_color::{Color, Paint};
+use vectorcraft_doc::swatches::{LinkFn, map_node_solid_paints};
+use vectorcraft_doc::{Appearance, Document, Node, NodeId};
+use vectorcraft_geom::{Rect, shapes};
+
+/// The colors the rectangles use, each with a swatch to link to.
+const COLORS: usize = 50;
+
+/// The calls in each timed run; a row gives the time of one call.
+const REPS: usize = 10;
+
+/// A way of finding the ids that no other listed id holds.
+type Roots = fn(&Document, &[NodeId]) -> Vec;
+
+/// A way of applying a link function to the paints of the listed ids, returning the count changed.
+type Map<'a> = dyn FnMut(&mut Document, &[NodeId], &mut LinkFn) -> usize + 'a;
+
+fn iters() -> usize {
+ std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
+}
+
+fn median(mut ms: Vec) -> f64 {
+ ms.sort_by(f64::total_cmp);
+ ms[ms.len() / 2]
+}
+
+/// The CPU time of the calling thread in ns, from `/proc/thread-self/schedstat` (Linux only).
+fn thread_cpu_ns() -> Option {
+ std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
+}
+
+/// The time `f` takes, in ms: CPU time where the system reports it, wall time otherwise.
+fn measure(f: impl FnOnce()) -> f64 {
+ match thread_cpu_ns() {
+ Some(start) => {
+ f();
+ thread_cpu_ns().map_or(f64::NAN, |end| end.saturating_sub(start) as f64 / 1e6)
+ }
+ None => {
+ let t = Instant::now();
+ f();
+ t.elapsed().as_secs_f64() * 1000.0
+ }
+ }
+}
+
+/// Color `i` of [`COLORS`]: each has its own red value.
+fn color(i: usize) -> Color {
+ Color::rgb(i as f32 / COLORS as f32, 0.5, 0.25)
+}
+
+/// The bits of a color's red value, which tell the colors of [`color`] apart; `u32::MAX` for other color models.
+fn red_bits(c: &Color) -> u32 {
+ match c {
+ Color::Rgb { r, .. } => r.to_bits(),
+ _ => u32::MAX,
+ }
+}
+
+/// The ids in the order given, less those with an ancestor in the list: a search of the list for each ancestor.
+fn roots_by_search(d: &Document, ids: &[NodeId]) -> Vec {
+ ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect()
+}
+
+/// [`roots_by_search`] with each ancestor looked up in a set of the ids.
+fn roots_by_set(d: &Document, ids: &[NodeId]) -> Vec {
+ let listed: HashSet = ids.iter().copied().collect();
+ ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect()
+}
+
+/// `f` applied to the paints of the subtrees of the ids `roots` finds, each node holding a changed
+/// paint put in place: the work of `map_solid_paints_in`.
+fn map_in(d: &mut Document, ids: &[NodeId], roots: Roots, f: &mut LinkFn) -> usize {
+ let mut n = 0;
+ for id in roots(d, ids) {
+ let Some(mut node) = d.node(id).cloned() else { continue };
+ let count = map_node_solid_paints(&mut node, f);
+ if count > 0
+ && let Some(slot) = d.node_mut(id)
+ {
+ *slot = node;
+ n += count;
+ }
+ }
+ n
+}
+
+/// Link every paint whose color has a swatch to that swatch, as Add Used Colors does for global
+/// swatches, recording each paint visited. Returns the count and the visits.
+fn link(d: &mut Document, ids: &[NodeId], map: &mut Map) -> (usize, Vec<(Color, Option)>) {
+ let names: HashMap = (0..COLORS).map(|i| (red_bits(&color(i)), format!("Swatch {i}"))).collect();
+ let mut visits = vec![];
+ let n = map(d, ids, &mut |c, s, _| {
+ visits.push((*c, s.clone()));
+ match names.get(&red_bits(c)) {
+ Some(name) if s.is_none() => {
+ *s = Some(name.clone());
+ true
+ }
+ _ => false,
+ }
+ });
+ (n, visits)
+}
+
+fn rect(d: &mut Document, i: usize) -> Arc {
+ let id = d.alloc_id();
+ let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0);
+ let r = shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0));
+ let a = Appearance::basic(Paint::solid(color(i % COLORS)), Paint::solid(color((i + 7) % COLORS)), 1.0);
+ Arc::new(Node::path(id, r, a))
+}
+
+/// `n` rectangles in the first layer, all selected.
+fn flat(n: usize) -> (Document, Vec) {
+ let mut d = Document::new(1600.0, 1200.0);
+ let l = d.layers[0].id;
+ let mut ids = vec![];
+ for i in 0..n {
+ let node = rect(&mut d, i);
+ ids.push(node.id);
+ d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(node)).unwrap();
+ }
+ (d, ids)
+}
+
+/// 1,000 groups in the first layer, each holding a group of 5 rectangles: the rectangles, and with
+/// `groups` the two groups above each of them too, listed first.
+fn nested(groups: bool) -> (Document, Vec) {
+ let mut d = Document::new(1600.0, 1200.0);
+ let l = d.layers[0].id;
+ let (mut outer_ids, mut leaves) = (vec![], vec![]);
+ for g in 0..1_000 {
+ let rects: Vec> = (0..5).map(|i| rect(&mut d, g * 5 + i)).collect();
+ leaves.extend(rects.iter().map(|r| r.id));
+ let inner = Node::group(d.alloc_id(), rects);
+ let outer = Node::group(d.alloc_id(), vec![Arc::new(inner.clone())]);
+ if groups {
+ outer_ids.extend([outer.id, inner.id]);
+ }
+ d.insert(Some(l), usize::MAX, outer).unwrap();
+ }
+ outer_ids.extend(leaves);
+ (d, outer_ids)
+}
+
+fn bench(name: &str, (doc, ids): (Document, Vec)) {
+ let mut shipped = doc.clone();
+ let want = link(&mut shipped, &ids, &mut |d, ids, f| d.map_solid_paints_in(ids, f));
+ for roots in [roots_by_search as Roots, roots_by_set] {
+ let mut d = doc.clone();
+ let got = link(&mut d, &ids, &mut |d, ids, f| map_in(d, ids, roots, f));
+ assert_eq!(got, want, "{name}: the same count and visits");
+ assert_eq!(d.layers, shipped.layers, "{name}: the same document");
+ }
+ let (mut old, mut new, mut real) = (vec![], vec![], vec![]);
+ let timed = |map: &mut Map| {
+ let mut docs = vec![doc.clone(); REPS];
+ measure(|| {
+ for d in &mut docs {
+ black_box(link(d, black_box(&ids), &mut *map));
+ }
+ }) / REPS as f64
+ };
+ for i in 0..iters() {
+ let run = |roots: Roots, out: &mut Vec| out.push(timed(&mut |d, ids, f| map_in(d, ids, roots, f)));
+ if i % 2 == 0 {
+ run(roots_by_search, &mut old);
+ run(roots_by_set, &mut new);
+ } else {
+ run(roots_by_set, &mut new);
+ run(roots_by_search, &mut old);
+ }
+ real.push(timed(&mut |d, ids, f| d.map_solid_paints_in(ids, f)));
+ }
+ let (old, new, real) = (median(old), median(new), median(real));
+ println!(" {name:<46} {:>7} {:>7} {old:>12.3} {new:>12.3} {real:>12.3} {:>8.1}x", ids.len(), want.0, old / new);
+}
+
+fn main() {
+ let unit = if thread_cpu_ns().is_some() { "CPU ms" } else { "wall ms" };
+ println!(
+ " {:<46} {:>7} {:>7} {:>12} {:>12} {:>12} {:>9}",
+ "document",
+ "ids",
+ "linked",
+ format!("search, {unit}"),
+ format!("set, {unit}"),
+ format!("shipped, {unit}"),
+ "speedup"
+ );
+ bench("2,000 rectangles in one layer", flat(2_000));
+ bench("20,000 rectangles in one layer", flat(20_000));
+ bench("5,000 rectangles in 1,000 groups of groups", nested(false));
+ bench("the same with the 2,000 groups listed first", nested(true));
+}
diff --git a/crates/engine/examples/stroke_targets_bench.rs b/crates/engine/examples/stroke_targets_bench.rs
new file mode 100644
index 0000000000..b576968e49
--- /dev/null
+++ b/crates/engine/examples/stroke_targets_bench.rs
@@ -0,0 +1,146 @@
+//! `cargo run --release -p vectorcraft-engine --example stroke_targets_bench` prints the time `stroke.set`
+//! takes to list its targets on documents of 2,000, 10,000 and 20,000 rectangles, all in one group. For
+//! each size it times, on the same leaves, the merge that checks each leaf against the growing list and
+//! the merge that checks it against a set, checks that the two lists are equal, and then times the whole
+//! `stroke.set {weight: 3}` command twice: once with the group named and once with every rectangle named.
+//! The whole-command rows include the document copy the command makes for undo; each run is undone
+//! before the next, outside the timed part.
+//! On Linux each row is the thread's CPU time, read from `/proc/thread-self/schedstat`; elsewhere
+//! it is wall time, and the first line says which. `ITERS` sets the runs per row (default 7); each
+//! row is the median in ms. A run of the two merge rows repeats the merge 1,000,000 / paths times
+//! and gives the time of one.
+// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
+#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
+
+use std::collections::HashSet;
+use std::hint::black_box;
+use std::time::Instant;
+
+use serde_json::{Value, json};
+use vectorcraft_color::Color;
+use vectorcraft_doc::{Document, NodeId};
+use vectorcraft_engine::Session;
+use vectorcraft_geom::Rect;
+use vectorcraft_testkit::fixtures::DocBuilder;
+
+fn iters() -> usize {
+ std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
+}
+
+/// The thread's CPU time in ns, or `None` where `/proc/thread-self/schedstat` cannot be read.
+fn cpu_ns() -> Option {
+ std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
+}
+
+/// The time `f` takes in ms: CPU time when [`cpu_ns`] reads, wall time otherwise.
+fn ms(f: impl FnOnce()) -> f64 {
+ let (cpu, wall) = (cpu_ns(), Instant::now());
+ f();
+ match (cpu, cpu_ns()) {
+ (Some(a), Some(b)) => (b - a) as f64 / 1e6,
+ _ => wall.elapsed().as_secs_f64() * 1000.0,
+ }
+}
+
+fn median(mut v: Vec) -> f64 {
+ v.sort_by(f64::total_cmp);
+ v[v.len() / 2]
+}
+
+/// `n` 10 pt squares in one group, and the squares' ids in stacking order.
+fn document(n: usize) -> (Document, NodeId, Vec) {
+ let mut b = DocBuilder::new(4000.0, 4000.0);
+ let kids: Vec<_> = (0..n)
+ .map(|i| {
+ let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) as f64 * 12.0);
+ b.rect_node(Rect::new(x, y, x + 10.0, y + 10.0), Color::rgb(0.2, 0.4, 0.6))
+ })
+ .collect();
+ let leaves = kids.iter().map(|k| k.id).collect();
+ let group = b.group(kids, false);
+ (b.build(), group, leaves)
+}
+
+/// The merge that checks each leaf against the growing list.
+fn listed(mut out: Vec, leaves: Vec) -> Vec {
+ for id in leaves {
+ if !out.contains(&id) {
+ out.push(id);
+ }
+ }
+ out
+}
+
+/// The merge that checks each leaf against a set seeded with `out`.
+fn with_set(mut out: Vec, leaves: Vec) -> Vec {
+ let mut seen: HashSet = out.iter().copied().collect();
+ for id in leaves {
+ if seen.insert(id) {
+ out.push(id);
+ }
+ }
+ out
+}
+
+fn row(name: &str, ms: f64) {
+ println!(" {name:<52} {ms:>10.3} ms");
+}
+
+/// The median time of `stroke.set {weight: 3}` on `ids`, each run undone outside the timed part.
+fn whole_command(s: &mut Session, ids: &[NodeId], n: usize) -> f64 {
+ let p: Value = json!({"ids": ids.iter().map(|id| id.0).collect::>(), "weight": 3});
+ let runs = (0..iters())
+ .map(|_| {
+ let mut r = Value::Null;
+ let t = ms(|| r = black_box(s.execute("stroke.set", &p).unwrap()));
+ assert_eq!(r["objects"], n, "{r}");
+ s.execute("edit.undo", &json!({})).unwrap();
+ t
+ })
+ .collect();
+ median(runs)
+}
+
+fn bench(n: usize) {
+ println!("{n} paths in one group");
+ let (doc, group, leaves) = document(n);
+
+ // Each run merges `reps` times, on copies made before the clock starts, and gives the time of one.
+ let reps = (1_000_000 / n).max(1);
+ let time = |f: fn(Vec, Vec) -> Vec| -> (f64, Vec) {
+ let mut last = Vec::new();
+ let runs = (0..iters())
+ .map(|_| {
+ let mut work: Vec> = (0..reps).map(|_| leaves.clone()).collect();
+ let mut done = Vec::with_capacity(reps);
+ let t = ms(|| {
+ for input in &mut work {
+ done.push(f(Vec::new(), black_box(std::mem::take(input))));
+ }
+ });
+ last = done.pop().unwrap();
+ t / reps as f64
+ })
+ .collect();
+ (median(runs), last)
+ };
+ let (old, a) = time(listed);
+ let (new, b) = time(with_set);
+ assert_eq!(a, b, "both merges give the same list");
+ assert_eq!(a, leaves);
+ row("target merge, list search", old);
+ row("target merge, set", new);
+ println!(" {:<52} {:>10.1}x", "ratio", old / new);
+
+ let mut s = Session::new();
+ s.add_document(doc, None);
+ row("stroke.set, whole command, the group named", whole_command(&mut s, &[group], n));
+ row("stroke.set, whole command, every path named", whole_command(&mut s, &leaves, n));
+}
+
+fn main() {
+ println!("{}", if cpu_ns().is_some() { "thread CPU time, median of runs" } else { "wall time, median of runs" });
+ for n in [2_000, 10_000, 20_000] {
+ bench(n);
+ }
+}
diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs
index d2e551e867..5a07a1d52b 100644
--- a/crates/engine/src/cmd.rs
+++ b/crates/engine/src/cmd.rs
@@ -826,7 +826,7 @@ pub use addons::{fold_source, print_hidden};
/// Document Info's category titles and the Objects category's count labels.
pub use docinfo::{CATEGORIES, OBJECT_LABELS};
pub use docmenu::guide_indexes;
-pub(crate) use edit::{settle_interaction, typing_in_progress};
+pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs
index 5d5db9cae4..a675aa2b88 100644
--- a/crates/engine/src/cmd/colormgmt.rs
+++ b/crates/engine/src/cmd/colormgmt.rs
@@ -121,7 +121,7 @@ pub fn specs() -> Vec {
"Separations Preview",
[],
None,
- "{on?: bool, plates?: [names], toggle?: plate, only?: plate} Separations Preview: show the chosen plates (one plate = greyscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}",
+ "{on?: bool, plates?: [names], toggle?: plate, only?: plate, soloToggle?: plate (only that plate, or every plate when it is the only one shown)} Separations Preview: show the chosen plates (one plate = grayscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}",
always,
separations
),
@@ -1064,6 +1064,13 @@ fn separations(s: &mut Session, p: &Value) -> Result {
if let Some(n) = text_param(p, "only", C)? {
v.separations = Some(vec![check(n)?]);
}
+ // The panel's Alt-click on a plate's eye: that plate alone, or every plate when it already
+ // shows alone among the active document's plates.
+ if let Some(n) = text_param(p, "soloToggle", C)? {
+ let n = check(n)?;
+ let alone = v.separations.as_ref().is_some_and(|vis| all.iter().filter(|a| vis.contains(a)).eq([&n]));
+ v.separations = Some(if alone { all.clone() } else { vec![n] });
+ }
if let Some(n) = text_param(p, "toggle", C)? {
let n = check(n)?;
let vis = v.separations.get_or_insert_with(|| all.clone());
diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs
index 013b373d19..e9fcad8883 100644
--- a/crates/engine/src/cmd/create.rs
+++ b/crates/engine/src/cmd/create.rs
@@ -62,7 +62,7 @@ pub fn specs() -> Vec {
"Circle Through Points",
[],
None,
- "{points?: [[x, y], [x, y], [x, y]] (left out: the three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the three points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same or three on one line are an error, and nothing is drawn",
+ "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn",
has_doc,
circle_through_points
),
@@ -413,16 +413,16 @@ fn ellipse(s: &mut Session, p: &Value) -> Result {
add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation)
}
-/// A live ellipse whose edge passes through three points: `points`, or the three selected anchor
-/// points ([`selected_anchor_points`]). One undo step, named as an Ellipse tool drag is.
+/// A live ellipse whose edge passes through two or three points: `points`, or the two or three
+/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One
+/// undo step, named as an Ellipse tool drag is.
fn circle_through_points(s: &mut Session, p: &Value) -> Result {
const C: &str = "shape.circleThroughPoints";
let points = match p.get("points").filter(|v| !v.is_null()) {
- Some(v) => three_points(v).ok_or_else(|| bad(C, "`points` must be three [x, y] pairs of numbers"))?,
- None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select three anchor points, or give `points`"))?,
+ Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?,
+ None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?,
};
- let [a, b, c] = points;
- let (center, radius) = shapes::circle_through(a, b, c)
+ let (center, radius) = shapes::circle_through_points(&points)
.ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?;
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
@@ -434,24 +434,25 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result {
Ok(out)
}
-/// The three points `[[x, y], [x, y], [x, y]]` holds, each pair two finite numbers.
-fn three_points(v: &Value) -> Option<[Point; 3]> {
+/// The two or three points `[[x, y], [x, y]]` or `[[x, y], [x, y], [x, y]]` holds, each pair two
+/// finite numbers.
+fn two_or_three_points(v: &Value) -> Option> {
let pair = |v: &Value| match v.as_array().map(Vec::as_slice) {
Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)),
_ => None,
};
- match v.as_array().map(Vec::as_slice) {
- Some([a, b, c]) => Some([pair(a)?, pair(b)?, pair(c)?]),
+ match v.as_array() {
+ Some(pairs) if matches!(pairs.len(), 2 | 3) => pairs.iter().map(pair).collect(),
_ => None,
}
}
-/// The positions of the selected anchor points, when there are exactly three. They are counted as
+/// The positions of the selected anchor points, when there are two or three. They are counted as
/// the other anchor commands count them ([`super::path::anchor_targets`]): a selected path with
/// anchors picked by Direct Selection gives those, and a path selected whole gives all of its own.
/// A selected segment's ends are not selected anchor points, so a selection with segments gives
/// none; so does a selection holding an object that is not a path, or an anchor that is gone.
-fn selected_anchor_points(s: &Session) -> Result