PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Vector: bound flattening memory, keep over-budget dashes, cheaper edge build (#5195) (#5204)
Valentin Kleinbcaadccbfab3
diff --git a/crates/vector/src/edit.rs b/crates/vector/src/edit.rsindex d08d76212..7f1f4d582 100644--- a/crates/vector/src/edit.rs+++ b/crates/vector/src/edit.rs@@ -80,6 +80,12 @@ fn handle(k: &Knot, h: Handle) -> Point {}}+/// Whether the segment from knot `a` to knot `b` is straight: both of its handles retracted.+fn straight(a: &Knot, b: &Knot) -> bool {+ let retracted = |k: &Knot, h: Handle| dist(handle(k, h), k.anchor) < 1e-9;+ retracted(a, Handle::Out) && retracted(b, Handle::In)+}+fn other(h: Handle) -> Handle {match h {Handle::In => Handle::Out,@@ -178,10 +184,9 @@ pub fn convert_point(path: &mut Path, knot: [usize; 2], out: Option<Point>) -> R/// the pointer exactly, with the nearer handle moving more. Smooth end knots stay smooth.pub fn bend_segment(path: &mut Path, knot: [usize; 2], t: f64, d: [f64; 2]) -> Result<(), String> {let end = segment_end(path, knot)?;- let retracted = |k: &Knot, h: Handle| dist(handle(k, h), k.anchor) < 1e-9;let a = *knot_mut(path, knot)?;let b = *knot_mut(path, end)?;- if retracted(&a, Handle::Out) && retracted(&b, Handle::In) {+ if straight(&a, &b) {return move_anchors(path, &[knot, end], d);}// B(t) moves by 3(1−t)²t·Δc1 + 3(1−t)t²·Δc2. With Δc1 = (1−t)·s·d and Δc2 = t·s·d that is@@ -213,10 +218,9 @@ pub fn add_anchor(path: &mut Path, knot: [usize; 2], t: f64) -> Result<[usize; 2return Err("`t` must be strictly between 0 and 1".into());}let end = segment_end(path, knot)?;- let retracted = |k: &Knot, h: Handle| dist(handle(k, h), k.anchor) < 1e-9;let a = *knot_mut(path, knot)?;let b = *knot_mut(path, end)?;- let new = if retracted(&a, Handle::Out) && retracted(&b, Handle::In) {+ let new = if straight(&a, &b) {// Hit testing and hover feedback use the cubic parameter, which is not linear even// when both handles are retracted. Keep the inserted corner at that same point.let p = eval(&[a.anchor, a.out_ctrl, b.in_ctrl, b.anchor], t);diff --git a/crates/vector/src/flatten.rs b/crates/vector/src/flatten.rsindex b3fd0a90f..a586dfa1b 100644--- a/crates/vector/src/flatten.rs+++ b/crates/vector/src/flatten.rs@@ -109,8 +109,38 @@ pub fn validate_shape(path: &Path, stroke: Option<&photocraft_doc::ShapeStroke>)Ok(())}-/// Flattens one subpath. Closed subpaths do not repeat the first point at the end.+/// Points one flattened path may hold. Paths that never pass [`validate_shape`] (vector masks+/// from files, imported SVG, effect outlines) are flattened more coarsely past it, so hostile+/// curves cannot exhaust memory.+pub(crate) const MAX_PATH_POINTS: usize = 1 << 20;++/// How much to coarsen the curves of `subpaths` at `tol` so the whole path stays within+/// [`MAX_PATH_POINTS`]: the share of each curve's pieces to keep (1 = all of them).+fn piece_scale<'a>(subpaths: impl IntoIterator<Item = &'a Subpath>, tol: f64) -> f64 {+ // Subpath starts and straight segments take one point each and cannot be coarsened.+ let (mut fixed, mut curves) = (0usize, 0usize);+ for s in subpaths {+ fixed = fixed.saturating_add(1);+ for seg in s.segments() {+ if is_line(&seg) {+ fixed = fixed.saturating_add(1);+ } else {+ curves = curves.saturating_add(pieces(&seg, tol));+ }+ }+ }+ let total = fixed.saturating_add(curves);+ if total <= MAX_PATH_POINTS { 1.0 } else { MAX_PATH_POINTS as f64 / total as f64 }+}++/// Flattens one subpath. Closed subpaths do not repeat the first point at the end. A hostile+/// subpath is flattened more coarsely so it stays within a bounded number of points.pub fn flatten_subpath(s: &Subpath, tol: f64) -> Polyline {+ flatten_scaled(s, tol, piece_scale([s], tol))+}++/// [`flatten_subpath`] keeping the share `scale` of each curve's pieces (at least one).+fn flatten_scaled(s: &Subpath, tol: f64, scale: f64) -> Polyline {let mut out = Polyline { closed: s.closed, ..Default::default() };if let Some(k) = s.knots.first() {out.push((k.anchor.x, k.anchor.y), true);@@ -121,6 +151,7 @@ pub fn flatten_subpath(s: &Subpath, tol: f64) -> Polyline {continue;}let n = pieces(seg, tol);+ let n = if scale < 1.0 { ((n as f64 * scale) as usize).max(1) } else { n };for j in 1..=n {out.push(eval(seg, j as f64 / n as f64), j == n);}@@ -136,15 +167,18 @@ pub fn flatten_subpath(s: &Subpath, tol: f64) -> Polyline {out}-/// Flattens every subpath (see [`flatten_subpath`]).+/// Flattens every subpath (see [`flatten_subpath`]); a hostile path is flattened more coarsely+/// so the whole path stays within a bounded number of points.pub fn flatten_path(p: &Path, tol: f64) -> Vec<Polyline> {- p.subpaths.iter().map(|s| flatten_subpath(s, tol)).collect()+ let scale = piece_scale(&p.subpaths, tol);+ p.subpaths.iter().map(|s| flatten_scaled(s, tol, scale)).collect()}#[cfg(test)]mod tests {use super::*;use crate::shapes;+ use photocraft_doc::Knot;#[test]fn lines_are_not_subdivided() {@@ -168,4 +202,26 @@ mod tests {assert!(p.pts.len() < 4 * (1 + (0.75 * 100.0 / tol.min(0.15)).sqrt() as usize + 1));}}++ #[test]+ fn hostile_curves_flatten_within_the_point_budget() {+ // Unvalidated paths (a vector mask from a file, an imported SVG) can carry handles far+ // outside the canvas: each of these segments alone asks for the 65536-piece cap, so the+ // path would flatten to ~1.3M points (#5195).+ let segments = 20;+ let knots = (0..=segments)+ .map(|i| {+ let a = Point::new(f64::from(i) * 50.0, f64::from(i % 2) * 1000.0);+ Knot::smooth(a, Point::new(a.x - 3e7, a.y + 3e7), Point::new(a.x + 3e7, a.y - 3e7))+ })+ .collect();+ let path = Path::new(vec![Subpath { closed: false, knots, op: Default::default() }]);+ let lines = flatten_path(&path, 0.01);+ let points: usize = lines.iter().map(|l| l.pts.len()).sum();+ assert!(points > 1000 && points <= MAX_PATH_POINTS + segments as usize + 1, "{points} points");+ assert_eq!(flatten_subpath(&path.subpaths[0], 0.01).pts.len(), points);+ // Ordinary paths are flattened exactly as before.+ let circle = shapes::ellipse(0.0, 0.0, 200.0, 200.0);+ assert_eq!(flatten_path(&circle, 0.01)[0], flatten_scaled(&circle.subpaths[0], 0.01, 1.0));+ }}diff --git a/crates/vector/src/lib.rs b/crates/vector/src/lib.rsindex 44e70ce76..d33643549 100644--- a/crates/vector/src/lib.rs+++ b/crates/vector/src/lib.rs@@ -43,10 +43,12 @@ pub const DEFAULT_TOLERANCE: f64 = 0.01;/// folded with the subpath operations; open subpaths are closed implicitly.pub fn fill_rasterizer(path: &Path, tol: f64) -> Rasterizer {let mut r = Rasterizer::new(path.inverted);+ // One point budget for the whole path, then one edge sort for all components.+ let polys: Vec<Vec<(f64, f64)>> = flatten_path(path, tol).into_iter().map(|l| l.pts).collect();for c in path.components() {- let polys: Vec<Vec<(f64, f64)>> = path.subpaths[c.clone()].iter().map(|s| flatten_subpath(s, tol).pts).collect();- r.add_component(&polys, path.effective_op(c.start), path.fill_rule);+ r.push_component(polys.get(c.clone()).unwrap_or_default(), path.effective_op(c.start), path.fill_rule);}+ r.sort_edges();r}@@ -105,26 +107,26 @@ impl CompiledVectorMask {/// Effective mask values over `rect`, with invocation-local rasterization state.pub fn render(&self, rect: Rect) -> Vec<f32> {- let mut v = match &self.geometry {- MaskGeometry::Constant(value) => vec![*value; rect.width() as usize * rect.height() as usize],- MaskGeometry::Path(rasterizer) => rasterizer.render(rect),- };- self.apply_density(&mut v);- v+ self.render_with(rect, Rasterizer::render)}/// Effective mask values without entering a thread pool. Use this while/// initializing a shared result that other Rayon workers may wait for.pub fn render_sequential(&self, rect: Rect) -> Vec<f32> {+ self.render_with(rect, |rasterizer, rect| {+ let mut v = vec![0.0; rect.width() as usize * rect.height() as usize];+ if !v.is_empty() {+ rasterizer.render_into(rect, &mut v);+ }+ v+ })+ }++ /// Mask values over `rect`, with a path's coverage from `coverage`.+ fn render_with(&self, rect: Rect, coverage: impl FnOnce(&Rasterizer, Rect) -> Vec<f32>) -> Vec<f32> {let mut v = match &self.geometry {MaskGeometry::Constant(value) => vec![*value; rect.width() as usize * rect.height() as usize],- MaskGeometry::Path(rasterizer) => {- let mut v = vec![0.0; rect.width() as usize * rect.height() as usize];- if !v.is_empty() {- rasterizer.render_into(rect, &mut v);- }- v- }+ MaskGeometry::Path(rasterizer) => coverage(rasterizer, rect),};self.apply_density(&mut v);vdiff --git a/crates/vector/src/map.rs b/crates/vector/src/map.rsindex ab2e62e1e..6078e604f 100644--- a/crates/vector/src/map.rs+++ b/crates/vector/src/map.rs@@ -15,13 +15,18 @@ use photocraft_geom::Point;pub fn map_points(path: &Path, f: impl Fn(Point) -> Point) -> Path {let mut out = path.clone();for s in &mut out.subpaths {- for k in &mut s.knots {- *k = Knot { anchor: f(k.anchor), in_ctrl: f(k.in_ctrl), out_ctrl: f(k.out_ctrl), smooth: k.smooth };- }+ map_knots(s, &f);}out}+/// Sends every anchor and control point of `s` through `f`, in place.+fn map_knots(s: &mut Subpath, f: &impl Fn(Point) -> Point) {+ for k in &mut s.knots {+ *k = Knot { anchor: f(k.anchor), in_ctrl: f(k.in_ctrl), out_ctrl: f(k.out_ctrl), smooth: k.smooth };+ }+}+/// Pieces a path may be split into, in total: bounds the work and memory on hostile input.const MAX_PIECES: usize = 1 << 20;/// Deepest split of one segment (2^6 = 64 pieces).@@ -47,7 +52,9 @@ fn map_subpath(s: &Subpath, f: &impl Fn(Point) -> Point, tol: f64, depth: u32) -let n = s.knots.len();let segs = s.segments();if segs.is_empty() {- return map_points(&Path::new(vec![s.clone()]), f).subpaths.pop().unwrap_or_default();+ let mut out = s.clone();+ map_knots(&mut out, f);+ return out;}// The mapped pieces of each segment (segment i runs from knot i to knot i + 1).let pieces: Vec<Vec<[Point; 4]>> = segs.iter().map(|seg| map_segment(seg, f, tol, depth)).collect();diff --git a/crates/vector/src/raster.rs b/crates/vector/src/raster.rsindex ba2cdd21f..eb6c4a943 100644--- a/crates/vector/src/raster.rs+++ b/crates/vector/src/raster.rs@@ -37,6 +37,10 @@ impl Edge {}}+/// Polygon coordinates are clamped to `±COORD_LIMIT`: far outside any `i32` pixel rectangle,+/// and small enough that edge slopes and positions never overflow to infinity or NaN.+const COORD_LIMIT: f64 = 1e15;+/// A combination step: a component (set of polygons filled with `rule`) and how it folds into/// the result so far.#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -66,6 +70,19 @@ impl Rasterizer {/// Adds a component made of closed polygons (open input is closed implicitly).pub fn add_component(&mut self, polys: &[Vec<(f64, f64)>], op: PathOp, rule: FillRule) {+ self.push_component(polys, op, rule);+ self.sort_edges();+ }++ /// Restores the `y0` order of the edges after [`Self::push_component`]. The sort is stable,+ /// so sorting once after many components orders the edges exactly like sorting after each.+ pub(crate) fn sort_edges(&mut self) {+ self.edges.sort_by(|a, b| a.y0.total_cmp(&b.y0));+ }++ /// [`Self::add_component`] without restoring the edge order: callers adding many components+ /// sort once at the end with [`Self::sort_edges`].+ pub(crate) fn push_component(&mut self, polys: &[Vec<(f64, f64)>], op: PathOp, rule: FillRule) {let comp = self.comps.len() as u32;self.comps.push(Component { op, rule });if op != PathOp::Combine && comp != 0 {@@ -77,11 +94,13 @@ impl Rasterizer {continue;}for i in 0..n {- let a = poly[i];- let b = poly[(i + 1) % n];+ let (a, b) = (poly[i], poly[(i + 1) % n]);if !(a.0.is_finite() && a.1.is_finite() && b.0.is_finite() && b.1.is_finite()) {continue;}+ // Far beyond any pixel rectangle; keeps edge arithmetic from overflowing.+ let clamp = |p: (f64, f64)| (p.0.clamp(-COORD_LIMIT, COORD_LIMIT), p.1.clamp(-COORD_LIMIT, COORD_LIMIT));+ let (a, b) = (clamp(a), clamp(b));self.bounds = Some(match self.bounds {None => (a.0.min(b.0), a.1.min(b.1), a.0.max(b.0), a.1.max(b.1)),Some(bb) => (bb.0.min(a.0.min(b.0)), bb.1.min(a.1.min(b.1)), bb.2.max(a.0.max(b.0)), bb.3.max(a.1.max(b.1))),@@ -90,10 +109,15 @@ impl Rasterizer {continue;}let (p, q, dir) = if a.1 < b.1 { (a, b, 1) } else { (b, a, -1) };- self.edges.push(Edge { x0: p.0, y0: p.1, y1: q.1, dir, comp, dxdy: (q.0 - p.0) / (q.1 - p.1) });+ let dxdy = (q.0 - p.0) / (q.1 - p.1);+ // Only a vanishingly short edge has an infinite slope once clamped: like a+ // horizontal edge it covers no area, and it would turn coverage into NaN.+ if !dxdy.is_finite() {+ continue;+ }+ self.edges.push(Edge { x0: p.0, y0: p.1, y1: q.1, dir, comp, dxdy });}}- self.edges.sort_by(|a, b| a.y0.total_cmp(&b.y0));}/// Pixel bounds of everything that may be covered (`None` = nothing; the whole plane@@ -428,6 +452,43 @@ mod tests {assert!(r.render(Rect::new(0, 0, 4, 4)).iter().all(|v| *v == 1.0));}+ #[test]+ fn huge_finite_coordinates_keep_edges_finite() {+ // The diagonal runs from far left of row 3 to far right of row 4, crossing x = 0 at+ // y = 4: row 3 is outside the triangle on the canvas, row 4 inside. Its slope used to+ // overflow to infinity, and the NaN it gave at the edge's top dropped that boundary,+ // filling row 3 (#5195).+ let mut r = Rasterizer::new(false);+ r.add_component(&[vec![(-1e308, 3.0), (1e308, 5.0), (-1e308, 5.0)]], PathOp::Combine, FillRule::NonZero);+ let c = r.render(Rect::new(0, 0, 10, 8));+ assert!(c.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)));+ for (y, row) in c.chunks(10).enumerate() {+ let expect = if y == 4 { 1.0 } else { 0.0 };+ assert!(row.iter().all(|v| (v - expect).abs() < 1e-3), "row {y}: {row:?}");+ }+ }++ #[test]+ fn sorting_edges_once_matches_sorting_per_component() {+ // Components sharing top rows (tied `y0`s) and a subtraction: one stable sort at the end+ // gives the exact edge order (and so the exact bits) of a sort after every component.+ let comps = [+ (vec![square(1.0, 1.0, 6.0), vec![(2.5, 1.0), (9.0, 4.0), (3.0, 8.5)]], PathOp::Combine, FillRule::NonZero),+ (vec![square(3.0, 1.0, 2.5)], PathOp::Subtract, FillRule::EvenOdd),+ (vec![vec![(0.5, 1.0), (8.0, 1.0), (4.2, 7.7)]], PathOp::Exclude, FillRule::NonZero),+ ];+ let (mut each, mut once) = (Rasterizer::new(false), Rasterizer::new(false));+ for (polys, op, rule) in &comps {+ each.add_component(polys, *op, *rule);+ once.push_component(polys, *op, *rule);+ }+ once.sort_edges();+ let rect = Rect::new(0, 0, 10, 10);+ let (a, b) = (each.render(rect), once.render(rect));+ assert!(a.iter().zip(&b).all(|(p, q)| p.to_bits() == q.to_bits()));+ assert!(sum(&a) > 1.0);+ }+#[test]fn pixel_bounds_clip_upper_edge_at_i32_max() {let mut r = Rasterizer::new(false);diff --git a/crates/vector/src/stroke.rs b/crates/vector/src/stroke.rsindex dba9473e8..2e08ab68b 100644--- a/crates/vector/src/stroke.rs+++ b/crates/vector/src/stroke.rs@@ -3,6 +3,8 @@//! together with the non-zero rule yields their exact union without computing offset curves.//! Dashing splits the flattened polylines by arc length first.+use std::borrow::Cow;+use photocraft_doc::{LineCap, LineJoin};use crate::flatten::Polyline;@@ -86,8 +88,14 @@ fn area_radius(r: f64, step: f64) -> f64 {if step < 1e-9 { r } else { r * (step / step.sin()).sqrt() }}-fn circle(c: P, r: f64, tol: f64) -> Vec<P> {- let n = ((std::f64::consts::TAU / arc_step(r, tol)).ceil() as usize).max(8);+/// Points a full circle needs at `tol` (at least 8).+fn circle_points(r: f64, tol: f64) -> usize {+ ((std::f64::consts::TAU / arc_step(r, tol)).ceil() as usize).max(8)+}++/// A circle of at most `arc_cap` points (`usize::MAX` = no limit, at least 4).+fn circle(c: P, r: f64, tol: f64, arc_cap: usize) -> Vec<P> {+ let n = circle_points(r, tol).min(arc_cap).max(4);let rr = area_radius(r, std::f64::consts::TAU / n as f64);(0..n).map(|i| {@@ -97,28 +105,78 @@ fn circle(c: P, r: f64, tol: f64) -> Vec<P> {.collect()}+/// Dash steps one stroke may spend, shared by all of its lines: it bounds the number of dashes+/// (and so of caps) for file-provided patterns. Past it, the rest is drawn solid.+const DASH_STEP_BUDGET: usize = 100_000;++/// Outline points a stroke may spend before its round caps and joins get coarser (#5211).+const OUTLINE_POINT_BUDGET: usize = 1 << 20;+/// Stroke outline pieces for `lines`. Fill them with the non-zero rule.+///+/// The outline is bounded: when full-resolution round caps and joins would exceed+/// [`OUTLINE_POINT_BUDGET`] points, every round cap and join gets the same, smaller number of+/// segments (down to 4 per circle and 1 per join; areas stay exact). Strokes under the budget+/// are unchanged and no piece is dropped, so the total is at most the larger of the budget and+/// that minimal tessellation, which is linear in the (budgeted) flattened points and dashes.pub fn stroke_polygons(lines: &[Polyline], style: &StrokeStyle, tol: f64) -> Vec<Vec<P>> {let mut out = Vec::new();if style.width <= 0.0 || !style.width.is_finite() || !style.miter_limit.is_finite() || style.miter_limit < 1.0 {return out;}+ let mut steps_left = DASH_STEP_BUDGET;+ let mut pieces: Vec<Cow<Polyline>> = Vec::new();for pl in lines {if pl.pts.iter().any(|p| !p.0.is_finite() || !p.1.is_finite()) {continue;}if !style.dashes.is_empty() {- for dash in dash_polyline(pl, &style.dashes, style.dash_offset) {- stroke_one(&dash, style, tol, &mut out);- }+ pieces.extend(dash_polyline_budgeted(pl, &style.dashes, style.dash_offset, &mut steps_left).into_iter().map(Cow::Owned));} else {- stroke_one(pl, style, tol, &mut out);+ pieces.push(Cow::Borrowed(pl));}}+ let arc_cap = round_arc_cap(&pieces, style, tol);+ for pl in &pieces {+ stroke_one(pl, style, tol, arc_cap, &mut out);+ }out}-fn stroke_one(pl: &Polyline, style: &StrokeStyle, tol: f64, out: &mut Vec<Vec<P>>) {+/// Points per full circle allowed for round caps and joins so the outline of `pieces` stays+/// within [`OUTLINE_POINT_BUDGET`]; `usize::MAX` when full resolution fits.+fn round_arc_cap(pieces: &[Cow<Polyline>], style: &StrokeStyle, tol: f64) -> usize {+ let (round_cap, round_join) = (style.cap == LineCap::Round, style.join == LineJoin::Round);+ if !round_cap && !round_join {+ return usize::MAX;+ }+ // Upper bounds: ribbons and miter/bevel pieces, full circles (caps and dots), round joins.+ let (mut base, mut circles, mut joins) = (0usize, 0usize, 0usize);+ for pl in pieces {+ let m = pl.pts.len();+ if m == 0 {+ continue;+ }+ base = base.saturating_add(m.saturating_mul(6)).saturating_add(8);+ if round_cap && !(pl.closed && m > 2) {+ circles = circles.saturating_add(if m == 1 { 1 } else { 2 });+ }+ if round_join {+ joins = joins.saturating_add(m);+ }+ }+ // A join sweeps at most half a circle, plus its centre and two end points.+ let cost = |n: usize| base.saturating_add(circles.saturating_mul(n)).saturating_add(joins.saturating_mul(n / 2 + 3));+ let full = circle_points(style.width * 0.5, tol);+ if cost(full) <= OUTLINE_POINT_BUDGET {+ return usize::MAX;+ }+ let left = OUTLINE_POINT_BUDGET.saturating_sub(base).saturating_sub(joins.saturating_mul(3)) as f64;+ let per_circle = circles as f64 + joins as f64 * 0.5;+ ((left / per_circle.max(1.0)) as usize).clamp(4, full)+}++fn stroke_one(pl: &Polyline, style: &StrokeStyle, tol: f64, arc_cap: usize, out: &mut Vec<Vec<P>>) {let hw = style.width * 0.5;// Drop repeated points.let mut pts: Vec<P> = Vec::with_capacity(pl.pts.len());@@ -145,7 +203,7 @@ fn stroke_one(pl: &Polyline, style: &StrokeStyle, tol: f64, out: &mut Vec<Vec<P>// A dot: only round and square caps draw something.let c = pts[0];match style.cap {- LineCap::Round => emit(out, circle(c, hw, tol)),+ LineCap::Round => emit(out, circle(c, hw, tol, arc_cap)),LineCap::Square => emit(out, vec![(c.0 - hw, c.1 - hw), (c.0 + hw, c.1 - hw), (c.0 + hw, c.1 + hw), (c.0 - hw, c.1 + hw)]),LineCap::Butt => {}}@@ -213,19 +271,19 @@ fn stroke_one(pl: &Polyline, style: &StrokeStyle, tol: f64, out: &mut Vec<Vec<P>(jn, true) => jn,(_, false) => LineJoin::Miter,};- join_piece(v, d1, d2, hw, join, if knot[j] { style.miter_limit.min(500.0) } else { f64::INFINITY }, tol, out);+ join_piece(v, d1, d2, hw, join, if knot[j] { style.miter_limit.min(500.0) } else { f64::INFINITY }, tol, arc_cap, out);}}if !closed {let d0 = norm(sub(pts[1], pts[0]));let d1 = norm(sub(pts[n - 1], pts[n - 2]));- cap_piece(pts[0], mul(d0, -1.0), hw, style.cap, tol, out);- cap_piece(pts[n - 1], d1, hw, style.cap, tol, out);+ cap_piece(pts[0], mul(d0, -1.0), hw, style.cap, tol, arc_cap, out);+ cap_piece(pts[n - 1], d1, hw, style.cap, tol, arc_cap, out);}}#[allow(clippy::too_many_arguments)]-fn join_piece(v: P, d1: P, d2: P, hw: f64, join: LineJoin, miter_limit: f64, tol: f64, out: &mut Vec<Vec<P>>) {+fn join_piece(v: P, d1: P, d2: P, hw: f64, join: LineJoin, miter_limit: f64, tol: f64, arc_cap: usize, out: &mut Vec<Vec<P>>) {let c = cross(d1, d2);let d = dot(d1, d2);if c.abs() < 1e-12 && d > 0.0 {@@ -239,15 +297,14 @@ fn join_piece(v: P, d1: P, d2: P, hw: f64, join: LineJoin, miter_limit: f64, tolmatch join {LineJoin::Bevel => emit(out, vec![v, a, b]),LineJoin::Miter => {- // Miter length / width = 1 / sin(θ/2) where θ is the angle between the segments.- let half = ((1.0 - d) * 0.5).max(0.0).sqrt(); // sin of half the turning angle+ // Miter length / width = 1 / sin(θ/2) where θ is the angle between the segments,+ // i.e. 1 / cos of half the turning angle.let cos_half = ((1.0 + d) * 0.5).max(0.0).sqrt();if cos_half < 1e-9 || 1.0 / cos_half > miter_limit {emit(out, vec![v, a, b]);} else {let bis = norm(add(n1, n2));let m = add(v, mul(bis, hw / cos_half));- let _ = half;emit(out, vec![v, a, m, b]);}}@@ -267,7 +324,12 @@ fn join_piece(v: P, d1: P, d2: P, hw: f64, join: LineJoin, miter_limit: f64, toldelta = std::f64::consts::PI * if cross(n1, d1) > 0.0 { 1.0 } else { -1.0 };}a1 = a0 + delta;- let steps = ((delta.abs() / arc_step(hw, tol)).ceil() as usize).max(1);+ let mut steps = (delta.abs() / arc_step(hw, tol)).ceil() as usize;+ if arc_cap != usize::MAX {+ // Over the outline budget: the join's share of an `arc_cap`-point circle.+ steps = steps.min((arc_cap as f64 * delta.abs() / std::f64::consts::TAU).ceil() as usize);+ }+ let steps = steps.max(1);let rr = area_radius(hw, delta.abs() / steps as f64);let mut poly = vec![v, a];for k in 1..steps {@@ -280,10 +342,10 @@ fn join_piece(v: P, d1: P, d2: P, hw: f64, join: LineJoin, miter_limit: f64, tol}}-fn cap_piece(p: P, dir: P, hw: f64, cap: LineCap, tol: f64, out: &mut Vec<Vec<P>>) {+fn cap_piece(p: P, dir: P, hw: f64, cap: LineCap, tol: f64, arc_cap: usize, out: &mut Vec<Vec<P>>) {match cap {LineCap::Butt => {}- LineCap::Round => emit(out, circle(p, hw, tol)),+ LineCap::Round => emit(out, circle(p, hw, tol, arc_cap)),LineCap::Square => {let n = mul(perp(dir), hw);let e = mul(dir, hw);@@ -294,6 +356,12 @@ fn cap_piece(p: P, dir: P, hw: f64, cap: LineCap, tol: f64, out: &mut Vec<Vec<P>/// Splits a polyline into dashes (open polylines). `pattern` alternates on/off lengths in px.pub fn dash_polyline(pl: &Polyline, pattern: &[f64], offset: f64) -> Vec<Polyline> {+ dash_polyline_budgeted(pl, pattern, offset, &mut DASH_STEP_BUDGET.clone())+}++/// [`dash_polyline`] spending at most `steps_left` dash steps (decremented); once they are+/// spent, the rest of the line is drawn solid.+fn dash_polyline_budgeted(pl: &Polyline, pattern: &[f64], offset: f64, steps_left: &mut usize) -> Vec<Polyline> {if pattern.is_empty() {return vec![pl.clone()];}@@ -313,13 +381,16 @@ pub fn dash_polyline(pl: &Polyline, pattern: &[f64], offset: f64) -> Vec<Polylinif !total.is_finite() || total <= 1e-9 || pl.pts.len() < 2 {return Vec::new();}- let mut pts = pl.pts.clone();- let mut knots = pl.knot.clone();- knots.resize(pts.len(), true);- if pl.closed {+ // Only a closed polyline needs a copy (with its first point repeated at the end).+ let pts: Cow<[P]> = if pl.closed {+ let mut pts = pl.pts.clone();pts.push(pl.pts[0]);- knots.push(true);- }+ pts.into()+ } else {+ pl.pts.as_slice().into()+ };+ // Knot flags past the source's (and the repeated closing point) count as knots.+ let knot_at = |i: usize| i >= pl.pts.len() || pl.knot.get(i).copied().unwrap_or(true);// Position in the pattern.let mut idx = 0usize;let mut left = pat[0];@@ -336,23 +407,27 @@ pub fn dash_polyline(pl: &Polyline, pattern: &[f64], offset: f64) -> Vec<Polylin}let mut out = Vec::new();let mut cur: Option<Polyline> = if idx.is_multiple_of(2) { Some(Polyline { pts: vec![pts[0]], knot: vec![true], closed: false }) } else { None };- let mut guard = 0usize;- for (wi, w) in pts.windows(2).enumerate() {+ 'walk: for (wi, w) in pts.windows(2).enumerate() {let (a, b) = (w[0], w[1]);- let b_knot = knots[wi + 1];+ let b_knot = knot_at(wi + 1);let seg = len(sub(b, a));let mut pos = 0.0;while seg - pos > 1e-12 {- guard += 1;- if guard > 100_000 {- // Bound allocations and time, including file-provided patterns. Commands- // reject patterns that exceed this budget before document mutation.- return Vec::new();- }let step = left.min(seg - pos);- if step > 0.0 && pos + step == pos {- return Vec::new();+ if *steps_left == 0 || (step > 0.0 && pos + step == pos) {+ // Past the step budget (which bounds allocations and time for file-provided+ // patterns; commands reject such patterns before mutating the document) or+ // dashes below the coordinates' precision: keep the dashes made so far and draw+ // the rest of the line solid rather than dropping the whole stroke (#5195).+ let here = if pos > 0.0 { add(a, mul(sub(b, a), pos / seg)) } else { a };+ let rest = cur.get_or_insert_with(|| Polyline { pts: vec![here], knot: vec![true], closed: false });+ for (j, p) in pts.iter().enumerate().skip(wi + 1) {+ rest.pts.push(*p);+ rest.knot.push(knot_at(j));+ }+ break 'walk;}+ *steps_left -= 1;pos += step;left -= step;let at_end = seg - pos <= 1e-12;@@ -451,11 +526,57 @@ mod tests {#[test]fn invalid_and_too_dense_dashes_finish_with_bounded_work() {let pl = line(&[(0.0, 0.0), (100.0, 0.0)], false);- for pattern in [vec![0.0, 0.0], vec![f64::INFINITY, 1.0], vec![f64::NAN, 1.0], vec![-1.0, 2.0], vec![1.0; 33], vec![1e-8, 1e-8]] {+ for pattern in [vec![0.0, 0.0], vec![f64::INFINITY, 1.0], vec![f64::NAN, 1.0], vec![-1.0, 2.0], vec![1.0; 33]] {assert!(dash_polyline(&pl, &pattern, 0.0).is_empty());}assert!(dash_polyline(&pl, &[2.0, 1.0], f64::INFINITY).is_empty());assert!(dash_polyline(&line(&[(f64::NAN, 0.0), (1.0, 0.0)], false), &[2.0, 1.0], 0.0).is_empty());+ // Too dense for the step budget: bounded work, and the line is still drawn.+ let d = dash_polyline(&pl, &[1e-8, 1e-8], 0.0);+ assert!(!d.is_empty() && d.len() <= 50_001);+ assert_eq!(d.last().and_then(|p| p.pts.last()), Some(&(100.0, 0.0)));+ }++ #[test]+ fn dashes_past_the_step_budget_keep_the_rest_of_the_line_solid() {+ // An SVG `stroke-dasharray="0.5 0.5"` along 60000 px needs more steps than the budget:+ // the stroke used to vanish entirely (#5195). The dashes made so far stay, the rest of+ // the line (through its later vertices) is drawn solid.+ let pl = line(&[(0.0, 0.0), (60_000.0, 0.0), (60_000.0, 1000.0)], false);+ let d = dash_polyline(&pl, &[0.5, 0.5], 0.0);+ assert!(d.len() > 40_000, "{} dashes", d.len());+ assert_eq!(d[0].pts, [(0.0, 0.0), (0.5, 0.0)]);+ let tail = d.last().unwrap();+ assert_eq!(tail.pts.last(), Some(&(60_000.0, 1000.0)));+ assert!(tail.pts.contains(&(60_000.0, 0.0)) && tail.pts.len() == tail.knot.len());+ // The solid tail starts where the dashes stopped (100000 steps of 0.5 px).+ assert!((tail.pts[0].0 - 50_000.0).abs() < 1.0 && tail.pts[0].1 == 0.0, "{:?}", tail.pts[0]);+ // Closed outlines finish the same way, back to their first point, where the solid tail+ // joins the first dash (one piece with a join at the seam, no caps).+ let outline = line(&[(0.0, 0.0), (60_000.0, 0.0), (60_000.0, 1000.0), (0.0, 1000.0)], true);+ let d = dash_polyline(&outline, &[0.5, 0.5], 0.0);+ let joined = &d[0];+ assert!(joined.pts.contains(&(60_000.0, 1000.0)) && joined.pts.contains(&(0.0, 1000.0)) && joined.pts.contains(&(0.0, 0.0)));+ assert_eq!(joined.pts.last(), Some(&(0.5, 0.0)));+ }++ #[test]+ fn wide_round_capped_dashes_keep_the_outline_within_its_point_budget() {+ let points = |polys: &[Vec<P>]| polys.iter().map(Vec::len).sum::<usize>();+ // 5000 dashes, each with two round caps of ~629 points at full resolution (#5211).+ let st = StrokeStyle { width: 4000.0, cap: LineCap::Round, join: LineJoin::Round, dashes: vec![1.0, 9.0], ..Default::default() };+ let pl = line(&[(0.0, 0.0), (25_000.0, 0.0), (25_000.0, 25_000.0)], false);+ let polys = stroke_polygons(std::slice::from_ref(&pl), &st, 0.01);+ assert!(points(&polys) <= OUTLINE_POINT_BUDGET, "{} points", points(&polys));+ // No dash is dropped: a ribbon and two caps each.+ assert!(polys.len() >= 3 * 5000, "{} pieces", polys.len());+ // Many tiny undashed subpaths: bounded too, every one still drawn.+ let dots: Vec<Polyline> = (0..3000).map(|i| line(&[(f64::from(i), 0.0), (f64::from(i) + 0.5, 0.0)], false)).collect();+ let polys = stroke_polygons(&dots, &StrokeStyle { dashes: Vec::new(), ..st.clone() }, 0.01);+ assert!(points(&polys) <= OUTLINE_POINT_BUDGET && polys.len() >= 3 * 3000, "{} points", points(&polys));+ // Under the budget, round caps keep their full resolution.+ let one = stroke_polygons(&dots[..1], &StrokeStyle { dashes: Vec::new(), ..st }, 0.01);+ assert!(one.iter().any(|p| p.len() == circle_points(2000.0, 0.01)) && circle_points(2000.0, 0.01) > 600);}#[test]diff --git a/crates/vector/src/trace.rs b/crates/vector/src/trace.rsindex 5aa5c0372..1a547bfb0 100644--- a/crates/vector/src/trace.rs+++ b/crates/vector/src/trace.rs@@ -25,10 +25,8 @@ type P = (f64, f64);pub fn trace_mask(values: &[f32], rect: Rect, outside: f32, tolerance: f64) -> Path {let loops = contours(values, rect, outside);let mut subpaths = Vec::new();+ // `contours` only returns loops of three or more points.for (i, lp) in loops.iter().enumerate() {- if lp.len() < 3 {- continue;- }// Fit to half the tolerance: the worst point may deviate by the full amount only rarely.let mut s = fit_closed(lp, (tolerance * 0.5).max(0.05), 1.5);s.op = if i == 0 { PathOp::Combine } else { PathOp::Exclude };