diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index c8dcedee90..b1e6683061 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -7,7 +7,7 @@ use std::collections::{HashMap, HashSet}; use std::rc::Rc; use std::sync::Arc; -use kurbo::BezPath; +use kurbo::{BezPath, PathEl}; use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Dash, Document, LAYER_COLORS, LayerColor, LineCap, Node, NodeKind, Symbol, TextObject}; use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect}; @@ -345,8 +345,13 @@ impl<'d, 'a> Build<'d, 'a> { for it in items.iter() { let p = &it.props; let on_zero = p.layer == "0"; - s |= p.color == Col::ByBlock || p.lineweight == Lw::ByBlock || p.linetype == "BYBLOCK" || p.alpha == Alpha::ByBlock; - s |= on_zero && (p.color == Col::ByLayer || p.lineweight == Lw::ByLayer || p.linetype == "BYLAYER"); + // Fills draw no stroke, and pattern lines carry their own dashes. + let filled = matches!(&it.geom, Geom::Path { fill: true, .. } | Geom::Shaded { shade: Shade::Gradient(_), .. }); + let stroked = !filled; + let in_linetype = !filled && !matches!(&it.geom, Geom::Shaded { shade: Shade::Pattern { .. }, .. }); + s |= p.color == Col::ByBlock || p.alpha == Alpha::ByBlock; + s |= (stroked && p.lineweight == Lw::ByBlock) || (in_linetype && p.linetype == "BYBLOCK"); + s |= on_zero && (p.color == Col::ByLayer || (stroked && p.lineweight == Lw::ByLayer) || (in_linetype && p.linetype == "BYLAYER")); if let Geom::Shaded { shade: Shade::Gradient(g), .. } = &it.geom { let inherited = |c| c == Col::ByBlock || (on_zero && c == Col::ByLayer); s |= inherited(g.first) || matches!(g.second, Second::Col(c) if inherited(c)); @@ -516,7 +521,7 @@ impl<'d, 'a> Build<'d, 'a> { let mut node = match &it.geom { Geom::Path { bp, fill, width } => self.path(bp, if *fill { Look::Fill } else { Look::Line }, *width, &it.props, map, inh)?, Geom::Shaded { bp, shade: Shade::Gradient(g) } => self.path(bp, Look::Gradient(g), 0.0, &it.props, map, inh)?, - Geom::Shaded { bp, shade: Shade::Pattern { dots } } => self.path(bp, Look::Pattern { dots: *dots }, 0.0, &it.props, map, inh)?, + Geom::Shaded { bp, shade: Shade::Pattern { dots } } => self.pattern(bp, *dots, &it.props, map, inh)?, Geom::Text(t) => self.text(t, &it.props, map, inh)?, Geom::Insert(ins) => return self.insert(ins, &it.props, map, inh, depth), }; @@ -525,6 +530,45 @@ impl<'d, 'a> Build<'d, 'a> { Some(node) } + /// Pattern hatch lines (`bp`, a move and a line per piece). With `dots`, the pieces of no + /// length go on a path of their own with round caps, grouped with the dashes, which keep + /// butt caps and their lengths. + fn pattern(&mut self, bp: &BezPath, dots: bool, p: &Props, map: Affine, inh: &Inherit) -> Option { + if !dots { + return self.path(bp, Look::Pattern { dots: false }, 0.0, p, map, inh); + } + let (mut dashes, mut points) = (BezPath::new(), BezPath::new()); + let mut from = None; + for el in bp.elements() { + match *el { + PathEl::MoveTo(a) => from = Some(a), + PathEl::LineTo(b) => { + if let Some(a) = from { + let out = if a == b { &mut points } else { &mut dashes }; + out.move_to(a); + out.line_to(b); + } + } + _ => {} + } + } + if dashes.elements().is_empty() { + return self.path(&points, Look::Pattern { dots: true }, 0.0, p, map, inh); + } + if points.elements().is_empty() { + return self.path(&dashes, Look::Pattern { dots: false }, 0.0, p, map, inh); + } + // The two paths are objects of their own inside the group that `item` counts. + if self.nodes.saturating_add(2) >= MAX_NODES { + self.warn(TOO_MANY); + return None; + } + let lines = self.path(&dashes, Look::Pattern { dots: false }, 0.0, p, map, inh)?; + let dots = self.path(&points, Look::Pattern { dots: true }, 0.0, p, map, inh)?; + self.nodes += 2; + Some(Node::group(self.doc.alloc_id(), vec![Arc::new(lines), Arc::new(dots)])) + } + /// A path painted as `look` says; `width`: a line's width in drawing units (0: the /// lineweight). fn path(&mut self, bp: &BezPath, look: Look<'_>, width: f64, p: &Props, map: Affine, inh: &Inherit) -> Option { diff --git a/crates/cad/src/import/hatch.rs b/crates/cad/src/import/hatch.rs index 506f595ba0..cc375424ba 100644 --- a/crates/cad/src/import/hatch.rs +++ b/crates/cad/src/import/hatch.rs @@ -22,10 +22,13 @@ const MAX_WORK: usize = 20_000_000; pub(crate) const MAX_TOTAL_PIECES: usize = if cfg!(test) { 1_000 } else { 2_000_000 }; /// The most clipping and dash steps all pattern hatches take together. pub(crate) const MAX_TOTAL_WORK: usize = if cfg!(test) { 200_000 } else { 200_000_000 }; -/// How far flattened boundary curves may stray, as a fraction of the boundary's larger side. +/// How far flattened boundary curves may stray, as a fraction of their loop's larger side. const FLATNESS: f64 = 1e-4; -/// Lengths below this fraction of the boundary's larger side count as none. +/// Line spacings and dash periods below this fraction of the boundary's larger side count as +/// none. const TINY: f64 = 1e-9; +/// Spans shorter than this many units of the last place of their coordinates count as none. +const LOCAL_TINY: f64 = 64.0 * f64::EPSILON; /// Why a pattern hatch is not drawn as its pattern. #[derive(Clone, Copy, Debug, PartialEq)] @@ -114,7 +117,7 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu if !(size > 0.0 && size.is_finite()) { return Ok((out, false)); } - let edges = edges(boundary, size * FLATNESS)?; + let edges = edges(boundary)?; if edges.is_empty() { return Ok((out, false)); } @@ -158,7 +161,8 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu let q = base + offset * k as f64; crossings(&edges, q, d, n, &mut t); for &[ta, tb] in t.as_chunks::<2>().0 { - if tb - ta <= tiny { + // Spans of no length at the precision of their own coordinates are dropped. + if tb - ta <= LOCAL_TINY * (q.to_vec2().hypot() + ta.abs().max(tb.abs())) { continue; } let mut emit = |s0: f64, s1: f64, budget: &mut Budget| -> Result<(), NoPattern> { @@ -202,10 +206,19 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu Ok((out, dots)) } -/// The boundary's edges as straight segments, each loop closed. -fn edges(boundary: &BezPath, tolerance: f64) -> Result, NoPattern> { +/// The boundary's edges as straight segments, each loop closed and its curves flattened to +/// within [`FLATNESS`] of the loop's own size. Loops of no size are left out. +fn edges(boundary: &BezPath) -> Result, NoPattern> { + let mut loops: Vec = Vec::new(); + for el in boundary.elements() { + if matches!(el, PathEl::MoveTo(_)) { + loops.push(BezPath::new()); + } + if let Some(l) = loops.last_mut() { + l.push(*el); + } + } let mut out = Vec::new(); - let (mut start, mut last) = (None::, None::); let mut over = false; let mut push = |a: Point, b: Point, out: &mut Vec<(Point, Point)>| { if out.len() >= MAX_EDGES { @@ -214,30 +227,35 @@ fn edges(boundary: &BezPath, tolerance: f64) -> Result, NoPa out.push((a, b)); } }; - kurbo::flatten(boundary.iter(), tolerance, |el| match el { - PathEl::MoveTo(p) => { - if let (Some(s), Some(l)) = (start, last) { - push(l, s, &mut out); - } - start = Some(p); - last = Some(p); + for lp in &loops { + let Some(b) = super::curve::bounds(lp) else { continue }; + let tolerance = b.width().max(b.height()) * FLATNESS; + if !(tolerance > 0.0 && tolerance.is_finite()) { + continue; } - PathEl::LineTo(p) => { - if let Some(l) = last { - push(l, p, &mut out); + let (mut start, mut last) = (None::, None::); + kurbo::flatten(lp.iter(), tolerance, |el| match el { + PathEl::MoveTo(p) => { + start = Some(p); + last = Some(p); } - last = Some(p); - } - PathEl::ClosePath => { - if let (Some(s), Some(l)) = (start, last) { - push(l, s, &mut out); + PathEl::LineTo(p) => { + if let Some(l) = last { + push(l, p, &mut out); + } + last = Some(p); } - last = start; + PathEl::ClosePath => { + if let (Some(s), Some(l)) = (start, last) { + push(l, s, &mut out); + } + last = start; + } + _ => {} + }); + if let (Some(s), Some(l)) = (start, last) { + push(l, s, &mut out); } - _ => {} - }); - if let (Some(s), Some(l)) = (start, last) { - push(l, s, &mut out); } if over { Err(NoPattern::TooDense) } else { Ok(out) } } @@ -317,8 +335,8 @@ pub(crate) fn gradient(g: &model::Gradient, boundary: &BezPath, ocs: Affine, own let (w, h) = (r.width(), r.height()); let shift = if g.shift.is_finite() { g.shift.clamp(0.0, 1.0) } else { 0.0 }; let c = r.center() + Vec2::new(-w, h) * (shift / 4.0); - // How far the shift moves the center along the gradient (left). - let dx = c.x - r.center().x; + // How far the shift moves the center left and up. + let (dx, dy) = (c.x - r.center().x, c.y - r.center().y); let name = g.name.trim().to_uppercase(); let (inverse, name) = match name.strip_prefix("INV") { Some(rest) => (true, rest), @@ -331,10 +349,10 @@ pub(crate) fn gradient(g: &model::Gradient, boundary: &BezPath, ocs: Affine, own } "SPHERICAL" => (GradientKind::Radial, c, c + Vec2::new(w.max(h) / 2.0, 0.0), swap(&[(0.0, true), (1.0, false)])), "HEMISPHERICAL" => { - let center = Point::new(c.x, r.y0 + (c.y - r.center().y)); + let center = Point::new(c.x, r.y0 + dy); (GradientKind::Radial, center, center + Vec2::new((w / 2.0).max(h), 0.0), swap(&[(0.0, true), (1.0, false)])) } - "CURVED" => (GradientKind::Linear, Point::new(c.x, r.y0), Point::new(c.x, r.y1), swap(&[(0.0, true), (1.0, false)])), + "CURVED" => (GradientKind::Linear, Point::new(c.x, r.y0 + dy), Point::new(c.x, r.y1 + dy), swap(&[(0.0, true), (1.0, false)])), _ => (GradientKind::Linear, Point::new(r.x0 + dx, c.y), Point::new(r.x1 + dx, c.y), swap(&[(0.0, false), (1.0, true)])), }; let mut geom = GradientGeom { start, end, aspect: 1.0, focal: None }; @@ -461,11 +479,41 @@ mod tests { #[test] fn a_dash_across_the_boundary_is_cut_there() { - let (bp, _) = pattern(&[line(0.0, [0.0, 7.0], &[30.0, -10.0])], &square(35.0)).unwrap(); + let (bp, _) = pattern(&[line(0.0, [0.0, 7.0], &[30.0, -10.0])], &square(50.0)).unwrap(); let p = pieces(&bp); assert!(p.iter().any(|(a, b)| (a.x - 0.0).abs() < 1e-9 && (b.x - 30.0).abs() < 1e-9)); - // The second dash, 40 to 70, starts past the boundary at 35. - assert!(p.iter().all(|(_, b)| b.x <= 35.0 + 1e-9), "{p:?}"); + // The second dash, 40 to 70, crosses the boundary at 50 and stops there. + assert!(p.iter().any(|(a, b)| (a.x - 40.0).abs() < 1e-9 && (b.x - 50.0).abs() < 1e-9), "{p:?}"); + assert!(p.iter().all(|(_, b)| b.x <= 50.0 + 1e-9), "{p:?}"); + } + + #[test] + fn short_spans_far_apart_keep_their_pieces_and_curves() { + // Two strips 1 wide and 100 tall, 10 billion units apart: each level line keeps its + // one-unit spans. + let strip = |x: f64| { + let mut s = square(1.0); + s.apply_affine(Affine::translate((x, 0.0)) * Affine::scale_non_uniform(1.0, 100.0)); + s + }; + let mut boundary = strip(0.0); + boundary.extend(strip(1e10)); + let l = PatternLine { angle: 0.0, base: [0.0, 25.0], offset: [0.0, 50.0], dashes: vec![] }; + let (bp, _) = pattern(&[l.clone()], &boundary).unwrap(); + let p = pieces(&bp); + assert_eq!(p.len(), 4, "{p:?}"); + assert!(p.iter().all(|(a, b)| ((b.x - a.x) - 1.0).abs() < 1e-3), "{p:?}"); + // Unit circles as far apart keep their round outlines: the line through y 0.5 spans + // 2 * sqrt(0.75) of each. + let circle = |x: f64| kurbo::Shape::to_path(&kurbo::Circle::new((x, 0.0), 1.0), 0.1); + let mut boundary = circle(0.0); + boundary.extend(circle(1e10)); + let l = PatternLine { angle: 0.0, base: [0.0, 0.5], offset: [0.0, 100.0], dashes: vec![] }; + let (bp, _) = pattern(&[l], &boundary).unwrap(); + let p = pieces(&bp); + assert_eq!(p.len(), 2, "{p:?}"); + let chord = 2.0 * 0.75f64.sqrt(); + assert!(p.iter().all(|(a, b)| ((b.x - a.x).abs() - chord).abs() < chord * 1e-2), "{p:?}"); } #[test] @@ -532,6 +580,11 @@ mod tests { assert_eq!(g.stops, [(0.0, true), (1.0, false)], "the second color in the center"); let g = gradient(&grad("CYLINDER", 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap(); assert_eq!(g.geom.start.midpoint(g.geom.end), Point::new(50.0, 75.0)); + // A curved gradient runs bottom to top, so the shift moves it up. + for name in ["CURVED", "INVCURVED"] { + let g = gradient(&grad(name, 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap(); + assert_eq!((g.geom.start, g.geom.end), (Point::new(50.0, 25.0), Point::new(50.0, 125.0)), "{name}"); + } // A plane stretched twice as wide stretches the circle into an ellipse with it. let g = gradient(&grad("SPHERICAL", 0.0, 0.0), &square(10.0), Affine::scale_non_uniform(2.0, 1.0), Col::ByLayer).unwrap(); assert!((g.geom.aspect - 0.5).abs() < 1e-9 && g.geom.end.distance(Point::new(20.0, 5.0)) < 1e-9, "{:?}", g.geom); @@ -545,6 +598,8 @@ mod tests { let a = gradient(&grad(name, 0.0, 0.0), &square(10.0), Affine::IDENTITY, Col::ByLayer).unwrap(); let b = gradient(&grad(inv, 0.0, 0.0), &square(10.0), Affine::IDENTITY, Col::ByLayer).unwrap(); assert_eq!((a.kind, a.geom), (b.kind, b.geom), "{name}"); + let count = if name == "CYLINDER" { 3 } else { 2 }; + assert_eq!((a.stops.len(), b.stops.len()), (count, count), "{name}"); assert!(a.stops.iter().zip(&b.stops).all(|(x, y)| x.0 == y.0 && x.1 != y.1), "{name}: {:?} {:?}", a.stops, b.stops); } } diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index 9b692caa63..081c40fa5a 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -852,6 +852,25 @@ fn pattern_hatches_draw_their_lines_inside_the_boundary() { let r = open(&entities(&pattern_hatch("CONTINUOUS", &[(79, "2"), (49, "0"), (49, "-5")])), &points()); let [dots] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; assert!(dots.appearance.stroke().is_some_and(|s| s.cap == LineCap::Round), "{:?}", r.warnings); + // Dashes and dots together: the dots take round caps on a path of their own, and the dashes + // keep butt caps, so they do not grow into their gaps. + let mixed = [(79, "4"), (49, "3"), (49, "-2"), (49, "0"), (49, "-5")]; + let r = open(&entities(&pattern_hatch("CONTINUOUS", &mixed)), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [hatch_art] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let [dashes, dots] = &hatch_art.children().unwrap()[..] else { panic!("dashes and dots: {:?}", hatch_art.kind) }; + assert!(dashes.appearance.stroke().is_some_and(|s| s.cap != LineCap::Round)); + assert!(dots.appearance.stroke().is_some_and(|s| s.cap == LineCap::Round)); + let length = |n: &Node| { + let pts = path_points(n); + pts[0].distance(*pts.last().unwrap()) + }; + let pieces = |n: &Node| match &n.kind { + NodeKind::Compound { children, .. } => children.iter().map(|c| (**c).clone()).collect(), + _ => vec![n.clone()], + }; + assert!(pieces(dashes).iter().all(|c| length(c) > 1e-9), "no dots among the dashes"); + assert!(pieces(dots).iter().all(|c| length(c) < 1e-9), "only dots"); // Without its pattern lines a pattern hatch still comes in as its boundary, with a note. let r = open(&entities(&hatch("0")), &points()); assert!(r.warnings.iter().any(|w| w.contains("without usable pattern lines")), "{:?}", r.warnings); @@ -981,6 +1000,22 @@ fn block_gradient_stops_keep_the_inserts_color() { } } +#[test] +fn block_pattern_hatches_ignore_the_inserts_linetype() { + let inserts = [(0, "INSERT"), (2, "Door"), (62, "1"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "Door"), (62, "3"), (10, "200"), (20, "0")]; + // Pattern lines draw without a linetype: inserts of other colors share one symbol. + let mut lines = pattern_hatch("BYBLOCK", &[]); + lines.splice(1..1, [(8, "Doors"), (370, "25")]); + let r = open(&with_door(&lines, &inserts), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert_eq!(r.document.symbols.len(), 1); + // A pattern hatch drawn as its boundary strokes it in the insert's linetype. + let mut boundary = hatch("0"); + boundary.splice(1..1, [(8, "Doors"), (370, "25"), (6, "BYBLOCK")]); + let r = open(&with_door(&boundary, &inserts), &points()); + assert_eq!(r.document.symbols.len(), 2, "{:?}", r.warnings); +} + #[test] fn hatch_declaring_many_absent_source_handles_parses_quickly() { let base = hatch("1");