From 02ea1d1c31eac64fbd0329ec278a0d3cb1035251 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:11:23 +0700 Subject: [PATCH 1/3] DXF/DWG: chain HATCH edge-path edges that are out of order or reversed An edge path was read in file order, so an edge listed elsewhere or stored end to start made the vertex list jump, and the even-odd fill filled the polygon of the jumps (a square listed AB, DC, BC, AD filled as an hourglass). Each edge is now read on its own and hatch/chain.rs joins them. A path whose edges already run on is joined in file order as before. Otherwise edges are chained into runs by their ends (within a millionth of the loop's extent, at least 1e-9), turned around when needed (points reversed, bulges negated and moved). Closed runs fill as loops of their own; open runs are joined in order, as a path read in file order is. Ends are looked up in a sorted grid, O(n log n). Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_read/hatch.rs | 22 +- crates/io/src/dxf_read/hatch/chain.rs | 256 ++++++++++++++++++++++ crates/io/tests/it/hatch_edge_chain.rs | 284 +++++++++++++++++++++++++ crates/io/tests/it/main.rs | 1 + 4 files changed, 557 insertions(+), 6 deletions(-) create mode 100644 crates/io/src/dxf_read/hatch/chain.rs create mode 100644 crates/io/tests/it/hatch_edge_chain.rs diff --git a/crates/io/src/dxf_read/hatch.rs b/crates/io/src/dxf_read/hatch.rs index a60d9ead0..c0651572c 100644 --- a/crates/io/src/dxf_read/hatch.rs +++ b/crates/io/src/dxf_read/hatch.rs @@ -1,6 +1,8 @@ use super::common::T; use super::{Color, EntityKind, Gradient, Handle, Hatch, HatchLoop, PolyVertex, Rgb, Spline, Tag, Vec2}; +mod chain; + /// Upper bound on the points the elliptic and spline edges of one HATCH's boundary are sampled /// into: the point budget the renderer gives one hatch's loops /// ([`cadcraft_geom::MAX_TESSELLATED_POINTS`]). @@ -129,25 +131,33 @@ fn polyline_boundary(tags: &[Tag], index: &mut usize) -> Option> Some(vertices) } +/// An edge path's vertices. Each edge is read on its own, then [`chain::chain`] joins them. fn edge_boundary(tags: &[Tag], index: &mut usize, budget: &mut EdgeBudget) -> Option> { let get = |i: usize| tags.get(i); seek_code(tags, index, 93); let count = get(*index)?.i64().clamp(0, 1_000_000) as usize; *index += 1; - let mut vertices = Vec::new(); + // Every edge's points back to back, and where each edge's are. + let (mut points, mut edges) = (Vec::new(), Vec::new()); + let mut edge = Vec::new(); for _ in 0..count { seek_code(tags, index, 72); let kind = get(*index)?.i64(); *index += 1; match kind { - 1 => line_edge(tags, index, &mut vertices), - 2 => circular_edge(tags, index, &mut vertices), - 3 => elliptic_edge(tags, index, &mut vertices, budget), - 4 => spline_edge(tags, index, &mut vertices, budget), + 1 => line_edge(tags, index, &mut edge), + 2 => circular_edge(tags, index, &mut edge), + 3 => elliptic_edge(tags, index, &mut edge, budget), + 4 => spline_edge(tags, index, &mut edge, budget), _ => {} } + if !edge.is_empty() { + let start = points.len(); + points.append(&mut edge); + edges.push(start..points.len()); + } } - Some(vertices) + Some(chain::chain(&points, &edges)) } fn edge_value(tags: &[Tag], index: usize) -> f64 { diff --git a/crates/io/src/dxf_read/hatch/chain.rs b/crates/io/src/dxf_read/hatch/chain.rs new file mode 100644 index 000000000..2727315b8 --- /dev/null +++ b/crates/io/src/dxf_read/hatch/chain.rs @@ -0,0 +1,256 @@ +//! Joining the edges of a HATCH edge path into loops. +//! +//! The DXF Reference lists a boundary path's edges one after another: group 72 gives each edge's +//! type, and the edge's own groups follow. Some files list the edges out of order, or store some +//! of them end to start. Read in file order, the vertex list of such a path jumps from edge to +//! edge, and the even-odd fill then fills the polygon those jumps make instead of the outline. + +use std::collections::VecDeque; +use std::ops::Range; + +use super::{PolyVertex, Vec2}; + +/// Points this close are one vertex where an edge meets the next. It is the tolerance the edge +/// readers used before edges were chained, so a path whose edges run on is read as before. +const SAME_POINT: f64 = 1e-9; + +/// The share of a loop's extent within which two edge ends meet. +/// +/// It only decides which edge follows which: no point is moved, and two ends that meet but +/// differ keep both points, so a real gap that small stays a segment of its own length. A +/// millionth is far above the rounding of the values a file stores (an arc's ends are computed +/// from its centre, radius and angles), and far below what a picture can show: a loop drawn +/// 10,000 pixels wide puts it at a hundredth of a pixel. +const MEET_SHARE: f64 = 1e-6; + +/// The vertices of an edge path, from its edges in file order. Each edge is a range of `points`, +/// read on its own: its first point, the points between (a bulge on the vertex before each arc) +/// and its last point. +/// +/// A path whose edges run on, each starting where the one before ends, is joined in file order, +/// as it always was. Otherwise the edges are chained into runs: +/// - A run starts with the first edge not yet used, as the file stores it. +/// - An edge with an end at the run's last point goes after it, turned around when that end is +/// its last point. Once none is left, an edge with an end at the run's first point goes before +/// it, turned around when that end is its first point. Of several, the one listed first. +/// - An edge that meets no run starts a new one. +/// +/// A closed run, one that ends where it starts, is a loop of its own. The runs left open make up +/// one loop together, in the order of their first edges, each joined straight to the next as a +/// path read in file order is (a path with missing edges then still closes as before). The vertex +/// list goes from the first loop's start to each later loop and back, and closes each later loop +/// straight from its last point to its first. An even-odd fill crosses each of those jumps +/// twice, so it fills each loop as a loop of its own. +pub(super) fn chain(points: &[PolyVertex], edges: &[Range]) -> Vec { + let mut out = Vec::with_capacity(points.len().saturating_add(edges.len())); + let Some(frame) = Frame::of(points).filter(|frame| !runs_on(points, edges, frame.tol)) else { + for edge in edges { + append(&mut out, edge_points(points, edge), false); + } + return out; + }; + let (order, run_ends) = runs(&frame, points, edges); + let span = |run: &[(usize, bool)]| { + let first = run.first().and_then(|&(edge, turned)| placed_ends(points, edges, edge, turned))?; + let last = run.last().and_then(|&(edge, turned)| placed_ends(points, edges, edge, turned))?; + Some((first.0, last.1)) + }; + // Each loop as the runs it is made of, ranges of `order`. + let mut loops: Vec>> = Vec::new(); + let (mut open, mut from): (Option, usize) = (None, 0); + for &to in &run_ends { + let run = from..to; + from = to; + let closed = span(order.get(run.clone()).unwrap_or_default()).is_some_and(|(start, end)| end.near(start, frame.tol)); + match open.and_then(|i| loops.get_mut(i)) { + Some(runs) if !closed => runs.push(run), + _ => { + open = open.or((!closed).then_some(loops.len())); + loops.push(vec![run]); + } + } + } + let mut anchor = None; + for runs in &loops { + let placed: Vec<(usize, bool)> = runs.iter().flat_map(|run| order.get(run.clone()).unwrap_or_default().iter().copied()).collect(); + let Some((start, end)) = span(&placed) else { continue }; + let later = anchor.is_some(); + if let Some(anchor) = anchor { + extend(&mut out, std::iter::once(PolyVertex::new(anchor))); + } else { + anchor = Some(start); + } + for (edge, turned) in placed { + append(&mut out, edges.get(edge).map_or(&[][..], |edge| edge_points(points, edge)), turned); + } + if later && !end.near(start, frame.tol) { + extend(&mut out, std::iter::once(PolyVertex::new(start))); + } + } + out +} + +/// Whether each edge starts where the one before it ends. +fn runs_on(points: &[PolyVertex], edges: &[Range], tol: f64) -> bool { + edges.windows(2).all(|pair| match pair { + [before, after] => ends(points, before).zip(ends(points, after)).is_some_and(|((_, end), (start, _))| end.near(start, tol)), + _ => true, + }) +} + +/// The edges in the order they are chained, each with whether it is turned around, and where +/// each run ends in that list. +fn runs(frame: &Frame, points: &[PolyVertex], edges: &[Range]) -> (Vec<(usize, bool)>, Vec) { + let mut index = EndIndex::new(frame, points, edges); + let mut used = vec![false; edges.len()]; + let (mut order, mut run_ends) = (Vec::with_capacity(edges.len()), Vec::new()); + let mut run = VecDeque::new(); + for first in 0..edges.len() { + let Some((mut head, mut tail)) = edges.get(first).and_then(|edge| ends(points, edge)) else { continue }; + if !take(&mut used, first) { + continue; + } + run.push_back((first, false)); + while let Some((edge, at_last)) = index.find(frame, tail, &used) { + let Some((start, end)) = edges.get(edge).and_then(|e| ends(points, e)) else { break }; + if !take(&mut used, edge) { + break; + } + run.push_back((edge, at_last)); + tail = if at_last { start } else { end }; + } + while let Some((edge, at_last)) = index.find(frame, head, &used) { + let Some((start, end)) = edges.get(edge).and_then(|e| ends(points, e)) else { break }; + if !take(&mut used, edge) { + break; + } + run.push_front((edge, !at_last)); + head = if at_last { start } else { end }; + } + order.extend(run.drain(..)); + run_ends.push(order.len()); + } + (order, run_ends) +} + +/// Marks an edge used; false when it already was. +fn take(used: &mut [bool], edge: usize) -> bool { + used.get_mut(edge).is_some_and(|used| !std::mem::replace(used, true)) +} + +/// Where a loop's edge ends are looked up: the lower corner of the box around its finite points, +/// and the distance within which two ends meet, which is also the side of a lookup cell. +struct Frame { + low: Vec2, + tol: f64, +} + +impl Frame { + /// None when no point is finite, or the points span more than a double holds. + fn of(points: &[PolyVertex]) -> Option { + let mut finite = points.iter().map(|v| v.p).filter(|p| p.is_finite()); + let first = finite.next()?; + let (low, high) = finite.fold((first, first), |(low, high), p| (low.min(p), high.max(p))); + let extent = (high.x - low.x).max(high.y - low.y); + extent.is_finite().then(|| Frame { low, tol: (extent * MEET_SHARE).max(SAME_POINT) }) + } + + /// The cell a point is in. The box is at most a million cells across (`extent / tol`), so + /// the conversions are exact. + fn cell(&self, p: Vec2) -> Option<(i64, i64)> { + p.is_finite().then(|| (((p.x - self.low.x) / self.tol).floor() as i64, ((p.y - self.low.y) / self.tol).floor() as i64)) + } +} + +/// The finite edge ends of a loop by cell. Ends in the same or the next cell meet: ends within +/// `tol` of each other always do, ends more than three times `tol` apart never. +struct EndIndex { + /// Each end's cell and id (twice its edge's index, plus one for the edge's last point), + /// sorted. + ends: Vec<((i64, i64), usize)>, + /// At a cell's first entry: the cell's first entry that may still be unused. + next: Vec, +} + +impl EndIndex { + fn new(frame: &Frame, points: &[PolyVertex], edges: &[Range]) -> EndIndex { + let mut ends: Vec<((i64, i64), usize)> = edges + .iter() + .enumerate() + .filter_map(|(i, edge)| ends(points, edge).map(|(start, end)| (i, start, end))) + .flat_map(|(i, start, end)| [(frame.cell(start), 2 * i), (frame.cell(end), 2 * i + 1)]) + .filter_map(|(cell, id)| cell.map(|cell| (cell, id))) + .collect(); + ends.sort_unstable(); + let next = (0..ends.len()).collect(); + EndIndex { ends, next } + } + + /// The unused edge listed first with an end in `p`'s cell or one next to it, and whether + /// that end is the edge's last point (its first point when both are there). + fn find(&mut self, frame: &Frame, p: Vec2, used: &[bool]) -> Option<(usize, bool)> { + let (x, y) = frame.cell(p)?; + let id = (-1..=1).flat_map(|dx| (-1..=1).map(move |dy| (x + dx, y + dy))).filter_map(|cell| self.first_unused(cell, used)).min()?; + Some((id / 2, id % 2 == 1)) + } + + /// The first end in `cell` whose edge is unused. Used ends are skipped once for good. + fn first_unused(&mut self, cell: (i64, i64), used: &[bool]) -> Option { + let first = self.ends.partition_point(|(c, _)| *c < cell); + let mut at = self.next.get(first).copied()?; + let found = loop { + match self.ends.get(at) { + Some(&(c, id)) if c == cell => { + if !used.get(id / 2).copied().unwrap_or(true) { + break Some(id); + } + at += 1; + } + _ => break None, + } + }; + if let Some(next) = self.next.get_mut(first) { + *next = at; + } + found + } +} + +fn edge_points<'a>(points: &'a [PolyVertex], edge: &Range) -> &'a [PolyVertex] { + points.get(edge.clone()).unwrap_or_default() +} + +/// An edge's first and last point. +fn ends(points: &[PolyVertex], edge: &Range) -> Option<(Vec2, Vec2)> { + let points = edge_points(points, edge); + Some((points.first()?.p, points.last()?.p)) +} + +/// An edge's first and last point as placed, turned around or not. +fn placed_ends(points: &[PolyVertex], edges: &[Range], edge: usize, turned: bool) -> Option<(Vec2, Vec2)> { + let (start, end) = ends(points, edges.get(edge)?)?; + Some(if turned { (end, start) } else { (start, end) }) +} + +/// Appends an edge's vertices. Turned around, its points come in reverse order, and each arc's +/// bulge is negated and moved to the vertex that now starts the arc. +fn append(out: &mut Vec, edge: &[PolyVertex], turned: bool) { + if turned { + let before = edge.iter().rev().skip(1).map(Some).chain([None]); + extend(out, edge.iter().rev().zip(before).map(|(v, before)| PolyVertex::with_bulge(v.p, before.map_or(0.0, |b| -b.bulge)))); + } else { + extend(out, edge.iter().copied()); + } +} + +/// Appends vertices, leaving out the first when the list already ends there; its bulge then goes +/// on the list's last vertex. +fn extend(out: &mut Vec, mut vertices: impl Iterator) { + if let Some(first) = vertices.next() { + match out.last_mut() { + Some(last) if last.p.near(first.p, SAME_POINT) => last.bulge = first.bulge, + _ => out.push(first), + } + } + out.extend(vertices); +} diff --git a/crates/io/tests/it/hatch_edge_chain.rs b/crates/io/tests/it/hatch_edge_chain.rs new file mode 100644 index 000000000..4ed3c0942 --- /dev/null +++ b/crates/io/tests/it/hatch_edge_chain.rs @@ -0,0 +1,284 @@ +//! A HATCH edge path whose edges are listed out of order, or stored end to start, is read as the +//! outline its edges make. Read in file order, its vertex list jumps between edges, and the +//! even-odd fill fills the polygon of those jumps instead. + +use cadcraft_doc::{EntityKind, HatchLoop}; +use cadcraft_geom::{PolyVertex, Vec2}; + +/// A boundary edge as a DXF HATCH stores it (DXF Reference, HATCH boundary path data). +#[derive(Clone)] +enum Edge { + Line([f64; 2], [f64; 2]), + /// Centre, radius, start and end angle in degrees, counter-clockwise. + Arc([f64; 2], f64, f64, f64, bool), + /// Centre, major axis end relative to the centre, minor-to-major ratio, start and end angle + /// in degrees, counter-clockwise. + Ellipse([f64; 2], [f64; 2], f64, f64, f64, bool), + /// Degree, knots, control points. + Spline(u32, Vec, Vec<[f64; 2]>), +} + +fn line(a: [f64; 2], b: [f64; 2]) -> Edge { + Edge::Line(a, b) +} + +fn groups(edge: &Edge) -> String { + match edge { + Edge::Line(a, b) => format!("72\n1\n10\n{}\n20\n{}\n11\n{}\n21\n{}\n", a[0], a[1], b[0], b[1]), + Edge::Arc(c, r, start, end, ccw) => format!("72\n2\n10\n{}\n20\n{}\n40\n{r}\n50\n{start}\n51\n{end}\n73\n{}\n", c[0], c[1], i32::from(*ccw)), + Edge::Ellipse(c, major, ratio, start, end, ccw) => format!( + "72\n3\n10\n{}\n20\n{}\n11\n{}\n21\n{}\n40\n{ratio}\n50\n{start}\n51\n{end}\n73\n{}\n", + c[0], + c[1], + major[0], + major[1], + i32::from(*ccw) + ), + Edge::Spline(degree, knots, control) => { + let mut s = format!("72\n4\n94\n{degree}\n73\n0\n74\n0\n95\n{}\n96\n{}\n", knots.len(), control.len()); + for k in knots { + s.push_str(&format!("40\n{k}\n")); + } + for p in control { + s.push_str(&format!("10\n{}\n20\n{}\n", p[0], p[1])); + } + s + } + } +} + +/// A DXF whose one solid HATCH has one edge path per entry of `paths`. +fn dxf(paths: &[Vec]) -> String { + let mut s = String::from( + "0\nSECTION\n2\nENTITIES\n0\nHATCH\n5\n100\n100\nAcDbEntity\n8\n0\n100\nAcDbHatch\n10\n0\n20\n0\n30\n0\n210\n0\n220\n0\n230\n1\n2\nSOLID\n70\n1\n71\n0\n", + ); + s.push_str(&format!("91\n{}\n", paths.len())); + for (i, edges) in paths.iter().enumerate() { + s.push_str(&format!("92\n{}\n93\n{}\n", i32::from(i == 0), edges.len())); + for edge in edges { + s.push_str(&groups(edge)); + } + s.push_str("97\n0\n"); + } + s.push_str("75\n0\n76\n1\n98\n0\n0\nENDSEC\n0\nEOF\n"); + s +} + +fn loops_of(d: &cadcraft_doc::Drawing) -> Vec { + let hatch = d.model.iter().find_map(|e| match &e.kind { + EntityKind::Hatch(h) => Some(h.loops.clone()), + _ => None, + }); + hatch.expect("a hatch") +} + +fn read_loops(paths: &[Vec]) -> Vec { + loops_of(&cadcraft_io::read(dxf(paths).as_bytes(), "edges.dxf").expect("read DXF")) +} + +/// The vertices of the one loop of a hatch with one edge path. +fn vertices(edges: &[Edge]) -> Vec { + let loops = read_loops(&[edges.to_vec()]); + assert_eq!(loops.len(), 1); + loops.into_iter().next().map(|l| l.vertices).unwrap_or_default() +} + +/// The same vertices, up to the rounding of points and bulges computed from other stored values. +fn assert_same(got: &[PolyVertex], expected: &[PolyVertex]) { + let same = got.len() == expected.len() && got.iter().zip(expected).all(|(a, b)| a.p.near(b.p, 1e-9) && (a.bulge - b.bulge).abs() < 1e-12); + assert!(same, "got {got:?}\nexpected {expected:?}"); +} + +/// Whether the even-odd fill of loops of straight segments covers `p`. +fn filled(loops: &[HatchLoop], p: Vec2) -> bool { + let mut inside = false; + for l in loops { + assert!(l.vertices.iter().all(|v| v.bulge == 0.0), "straight segments only"); + for (a, b) in l.vertices.iter().zip(l.vertices.iter().cycle().skip(1)) { + let (a, b) = (a.p, b.p); + if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) { + inside = !inside; + } + } + } + inside +} + +const A: [f64; 2] = [0.0, 0.0]; +const B: [f64; 2] = [10.0, 0.0]; +const C: [f64; 2] = [10.0, 10.0]; +const D: [f64; 2] = [0.0, 10.0]; + +#[test] +fn edges_listed_out_of_order_read_as_the_outline() { + let in_order = vertices(&[line(A, B), line(B, C), line(C, D), line(D, A)]); + // Read in file order, this is A, B, D, C, B, C, A, D: its even-odd fill is an hourglass. + let shuffled = vertices(&[line(A, B), line(D, C), line(B, C), line(A, D)]); + assert_same(&shuffled, &in_order); + let loops = read_loops(&[vec![line(A, B), line(D, C), line(B, C), line(A, D)]]); + for p in [[5.0, 1.0], [5.0, 9.0], [1.0, 5.0], [9.0, 5.0]] { + assert!(filled(&loops, Vec2::new(p[0], p[1])), "{p:?}"); + } +} + +#[test] +fn edges_stored_end_to_start_are_turned_around() { + let p = [[0.0, 0.0], [10.0, 0.0], [15.0, 8.0], [10.0, 16.0], [0.0, 16.0], [-5.0, 8.0]]; + let in_order = vertices(&[line(p[0], p[1]), line(p[1], p[2]), line(p[2], p[3]), line(p[3], p[4]), line(p[4], p[5]), line(p[5], p[0])]); + // The second and third edges are both stored end to start, and the last one too. + let edges = [line(p[0], p[1]), line(p[2], p[1]), line(p[3], p[2]), line(p[3], p[4]), line(p[4], p[5]), line(p[0], p[5])]; + assert_same(&vertices(&edges), &in_order); + // Around the two reversed edges in a row, a vertex list in file order (..., P1, P2, P1, P3, + // P2, P3, ...) leaves the triangle P1 P2 P3 unfilled. + let loops = read_loops(&[edges.to_vec()]); + assert!(filled(&loops, Vec2::new(11.0, 7.0))); +} + +#[test] +fn arcs_ellipse_arcs_and_splines_stored_end_to_start_are_turned_around() { + // A loop round counter-clockwise: the bottom, a half circle out to the right, the top, and + // half an ellipse out to the left. + let arc = Edge::Arc([10.0, 5.0], 5.0, -90.0, 90.0, true); + let ellipse = Edge::Ellipse([0.0, 5.0], [0.0, 5.0], 0.4, 0.0, 180.0, true); + let in_order = vertices(&[line(A, B), arc, line(C, D), ellipse]); + // The same half circle from (10, 10) to (10, 0) clockwise: a clockwise arc stores its angles + // negated. The same half ellipse from (0, 0) to (0, 10) clockwise. + let arc_back = Edge::Arc([10.0, 5.0], 5.0, 270.0, 90.0, false); + let ellipse_back = Edge::Ellipse([0.0, 5.0], [0.0, 5.0], 0.4, 180.0, 360.0, false); + let got = vertices(&[line(A, B), arc_back, line(D, C), ellipse_back]); + assert_same(&got, &in_order); + assert!(in_order.iter().any(|v| v.bulge > 0.5), "the half circle is a bulge: {in_order:?}"); + // The same half circle found before the run's first edge: an open path listed from its + // last edge. + let arc = Edge::Arc([10.0, 5.0], 5.0, -90.0, 90.0, true); + let in_order = vertices(&[arc, line(C, D)]); + assert_same(&vertices(&[line(C, D), Edge::Arc([10.0, 5.0], 5.0, 270.0, 90.0, false)]), &in_order); + + // A Bezier spline and the same curve with its control points reversed. + let control = vec![[10.0, 0.0], [10.0, 8.0], [0.0, 8.0], [0.0, 0.0]]; + let knots = vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]; + let spline = Edge::Spline(3, knots.clone(), control.clone()); + let spline_back = Edge::Spline(3, knots, control.into_iter().rev().collect()); + let in_order = vertices(&[line(A, B), spline]); + assert!(in_order.len() > 8, "{in_order:?}"); + assert_same(&vertices(&[line(A, B), spline_back]), &in_order); +} + +#[test] +fn ends_that_differ_by_rounding_still_meet() { + // A 1,000 by 10 rectangle whose corners are 5e-4 apart: half a millionth of its length, + // far more than the 1e-9 within which two points are one vertex, so each joint keeps both + // points. + let (x, y, w, h, e) = (5e5, -3e5, 1e3, 10.0, 5e-4); + let p = [[x, y], [x + w, y], [x + w, y + h], [x, y + h]]; + let q = |i: usize| [p[i][0] + e, p[i][1] - e]; + let edges = [line(p[0], p[1]), line(q(1), p[2]), line(q(2), p[3]), line(q(3), q(0))]; + let in_order = vertices(&edges); + assert_eq!(in_order.len(), 8, "{in_order:?}"); + let shuffled = vertices(&[edges[0].clone(), line(p[3], q(2)), edges[3].clone(), line(p[2], q(1))]); + assert_same(&shuffled, &in_order); +} + +#[test] +fn an_open_path_is_chained_from_both_ends() { + // Three sides of the square, A to D, listed from the middle: the edges before the first + // listed one go in front, as stored or turned around. + let in_order = vertices(&[line(A, B), line(B, C), line(C, D)]); + assert_same(&vertices(&[line(B, C), line(C, D), line(B, A)]), &in_order); + assert_same(&vertices(&[line(C, D), line(B, C), line(A, B)]), &in_order); +} + +#[test] +fn a_path_whose_edges_run_on_keeps_its_order_and_its_points() { + // Clockwise, starting at C, with a gap of 1e-6 at D: within a millionth of the outline + // (1e-5), so the edges run on, but more than 1e-9, so both points stay. + let d_off = [D[0], D[1] + 1e-6]; + let edges = [line(C, B), line(B, A), line(A, D), line(d_off, C)]; + let got = vertices(&edges); + let expected: Vec = [C, B, A, D, d_off].iter().map(|p| PolyVertex::new(Vec2::new(p[0], p[1]))).collect(); + assert_eq!(got, expected); +} + +#[test] +fn separate_outlines_in_one_path_fill_separately() { + let square = |x: f64, y: f64| { + let p = [[x, y], [x + 10.0, y], [x + 10.0, y + 10.0], [x, y + 10.0]]; + [line(p[0], p[1]), line(p[1], p[2]), line(p[2], p[3]), line(p[3], p[0])] + }; + let [a, b, c] = [square(0.0, 0.0), square(100.0, 0.0), square(50.0, 100.0)]; + // In file order, the jumps from one square to the next and back to the first make a + // triangle between them, which the even-odd fill filled. + let in_order: Vec = a.iter().chain(&b).chain(&c).cloned().collect(); + // The same squares, their edges interleaved and the third square's turned around. + let mixed = vec![ + a[0].clone(), + b[2].clone(), + line([60.0, 110.0], [60.0, 100.0]), + a[2].clone(), + b[0].clone(), + line([50.0, 110.0], [60.0, 110.0]), + a[1].clone(), + b[3].clone(), + line([50.0, 100.0], [50.0, 110.0]), + a[3].clone(), + b[1].clone(), + line([60.0, 100.0], [50.0, 100.0]), + ]; + for edges in [in_order, mixed] { + let loops = read_loops(&[edges]); + for p in [[5.0, 5.0], [105.0, 5.0], [55.0, 105.0]] { + assert!(filled(&loops, Vec2::new(p[0], p[1])), "{p:?}"); + } + for p in [[50.0, 30.0], [30.0, 5.0], [55.0, 50.0]] { + assert!(!filled(&loops, Vec2::new(p[0], p[1])), "{p:?}"); + } + } +} + +#[test] +fn an_outline_left_open_is_closed_on_itself() { + // A square, then three sides of another listed apart from it: the second is closed by its + // missing side, not through the first square's corner. + let b = [[100.0, 0.0], [110.0, 0.0], [110.0, 10.0], [100.0, 10.0]]; + let edges = vec![line(A, B), line(B, C), line(C, D), line(D, A), line(b[1], b[2]), line(b[0], b[1]), line(b[2], b[3])]; + let loops = read_loops(&[edges]); + assert!(filled(&loops, Vec2::new(5.0, 5.0))); + assert!(filled(&loops, Vec2::new(105.0, 5.0))); + assert!(!filled(&loops, Vec2::new(90.0, 5.0))); +} + +#[test] +fn outlines_with_missing_edges_are_joined_in_file_order() { + // The bottom from right to left, then the top and a cut corner from left to right, of an + // outline whose sides are missing: the two open runs are joined straight in the order they + // are listed, so the outline still fills. + let loops = read_loops(&[vec![line(B, A), line(D, [8.0, 10.0]), line([8.0, 10.0], [10.0, 8.0])]]); + for p in [[5.0, 5.0], [9.0, 2.0], [1.0, 8.0]] { + assert!(filled(&loops, Vec2::new(p[0], p[1])), "{p:?}"); + } + assert!(!filled(&loops, Vec2::new(9.8, 9.8))); +} + +#[test] +fn a_chained_loop_is_saved_as_it_was_read() { + let in_order = vertices(&[line(A, B), line(B, C), line(C, D), line(D, A)]); + let shuffled = cadcraft_io::read(dxf(&[vec![line(A, B), line(D, C), line(B, C), line(A, D)]]).as_bytes(), "edges.dxf").expect("read"); + let saved = cadcraft_io::write_dxf(&shuffled); + let back = loops_of(&cadcraft_io::read(saved.as_bytes(), "saved.dxf").expect("reopen")); + assert_eq!(back.len(), 1); + assert_same(&back[0].vertices, &in_order); + assert_same(&back[0].vertices, &loops_of(&shuffled)[0].vertices); +} + +#[test] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +fn a_dwg_edge_path_out_of_order_reads_as_the_outline() { + cadcraft_io::dwg_worker::allow_in_process(); + let in_order = vertices(&[line(A, B), line(B, C), line(C, D), line(D, A)]); + let text = dxf(&[vec![line(A, B), line(D, C), line(B, C), line(A, D)]]); + let doc = acadrust::DxfReader::from_reader(std::io::Cursor::new(text.into_bytes())).expect("acadrust reads the DXF").read().expect("parse"); + let dwg = acadrust::DwgWriter::write_to_vec(&doc).expect("acadrust writes a DWG"); + let loops = loops_of(&cadcraft_io::read(&dwg, "edges.dwg").expect("read DWG")); + assert_eq!(loops.len(), 1); + assert_same(&loops[0].vertices, &in_order); +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index dc0bc0931..6055624a4 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -36,6 +36,7 @@ mod exhausted_handseed; mod followups_626; mod groups_roundtrip; mod hatch_assoc_roundtrip; +mod hatch_edge_chain; mod hatch_elliptic_edge_dedup; mod hatch_loop_flags; mod hatch_pattern_def; From 3da5c2c31943d3c762e61bf83fe20ab30489726e Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:36:01 +0700 Subject: [PATCH 2/3] Hatch edge chaining: ends meet only within the tolerance The end lookup took any unused end in the 3x3 grid cells around a point, so ends up to about 2.8 tolerances apart could be joined (review). The grid now only gives candidates; each is checked with Vec2::near against the tolerance and the lowest eligible end wins, as the "runs on" and closed-run checks already did. A cell's scan stops at the best match so far, and the ends visited are capped at 32 per end of the loop: past that, a crafted loop is read in file order. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_read/hatch/chain.rs | 102 ++++++++++++++++--------- crates/io/tests/it/hatch_edge_chain.rs | 54 +++++++++++++ 2 files changed, 120 insertions(+), 36 deletions(-) diff --git a/crates/io/src/dxf_read/hatch/chain.rs b/crates/io/src/dxf_read/hatch/chain.rs index 2727315b8..cbd5ea1d2 100644 --- a/crates/io/src/dxf_read/hatch/chain.rs +++ b/crates/io/src/dxf_read/hatch/chain.rs @@ -35,6 +35,9 @@ const MEET_SHARE: f64 = 1e-6; /// it, turned around when that end is its first point. Of several, the one listed first. /// - An edge that meets no run starts a new one. /// +/// Two ends meet when they are within the tolerance of each other (see [`MEET_SHARE`]). A loop +/// whose lookups pass their budget ([`CHECKS_PER_END`]) is joined in file order instead. +/// /// A closed run, one that ends where it starts, is a loop of its own. The runs left open make up /// one loop together, in the order of their first edges, each joined straight to the next as a /// path read in file order is (a path with missing edges then still closes as before). The vertex @@ -43,13 +46,15 @@ const MEET_SHARE: f64 = 1e-6; /// twice, so it fills each loop as a loop of its own. pub(super) fn chain(points: &[PolyVertex], edges: &[Range]) -> Vec { let mut out = Vec::with_capacity(points.len().saturating_add(edges.len())); - let Some(frame) = Frame::of(points).filter(|frame| !runs_on(points, edges, frame.tol)) else { + let chained = Frame::of(points) + .filter(|frame| !runs_on(points, edges, frame.tol)) + .and_then(|frame| runs(&frame, points, edges, CHECKS_PER_END).map(|runs| (frame, runs))); + let Some((frame, (order, run_ends))) = chained else { for edge in edges { append(&mut out, edge_points(points, edge), false); } return out; }; - let (order, run_ends) = runs(&frame, points, edges); let span = |run: &[(usize, bool)]| { let first = run.first().and_then(|&(edge, turned)| placed_ends(points, edges, edge, turned))?; let last = run.last().and_then(|&(edge, turned)| placed_ends(points, edges, edge, turned))?; @@ -98,10 +103,17 @@ fn runs_on(points: &[PolyVertex], edges: &[Range], tol: f64) -> bool { }) } +/// Ends the lookups may visit, per end of the loop. A lookup visits, in up to nine cells, the +/// ends after each cell's first unused one and before the best match so far; in a drawing that +/// is a few. A crafted loop can keep many unused ends just past the tolerance of a point it +/// returns to again and again, and visit them at every return. +const CHECKS_PER_END: usize = 32; + /// The edges in the order they are chained, each with whether it is turned around, and where -/// each run ends in that list. -fn runs(frame: &Frame, points: &[PolyVertex], edges: &[Range]) -> (Vec<(usize, bool)>, Vec) { - let mut index = EndIndex::new(frame, points, edges); +/// each run ends in that list. None when the lookups visit more than `checks_per_end` ends per +/// end of the loop: the loop is then read in file order. +fn runs(frame: &Frame, points: &[PolyVertex], edges: &[Range], checks_per_end: usize) -> Option<(Vec<(usize, bool)>, Vec)> { + let mut index = EndIndex::new(frame, points, edges, checks_per_end); let mut used = vec![false; edges.len()]; let (mut order, mut run_ends) = (Vec::with_capacity(edges.len()), Vec::new()); let mut run = VecDeque::new(); @@ -127,10 +139,13 @@ fn runs(frame: &Frame, points: &[PolyVertex], edges: &[Range]) -> (Vec<(u run.push_front((edge, !at_last)); head = if at_last { start } else { end }; } + if index.spent { + return None; + } order.extend(run.drain(..)); run_ends.push(order.len()); } - (order, run_ends) + Some((order, run_ends)) } /// Marks an edge used; false when it already was. @@ -162,57 +177,72 @@ impl Frame { } } -/// The finite edge ends of a loop by cell. Ends in the same or the next cell meet: ends within -/// `tol` of each other always do, ends more than three times `tol` apart never. +/// The finite edge ends of a loop, by cell. A cell is `tol` wide, so an end within `tol` of a +/// point is in the point's cell or one next to it. struct EndIndex { - /// Each end's cell and id (twice its edge's index, plus one for the edge's last point), - /// sorted. - ends: Vec<((i64, i64), usize)>, + /// Each end's cell, id (twice its edge's index, plus one for the edge's last point) and + /// point, sorted by cell and id. + ends: Vec<((i64, i64), usize, Vec2)>, /// At a cell's first entry: the cell's first entry that may still be unused. next: Vec, + /// Ends lookups may still visit. + checks: usize, + /// The lookups visited every end they were allowed: they find nothing more. + spent: bool, } impl EndIndex { - fn new(frame: &Frame, points: &[PolyVertex], edges: &[Range]) -> EndIndex { - let mut ends: Vec<((i64, i64), usize)> = edges + fn new(frame: &Frame, points: &[PolyVertex], edges: &[Range], checks_per_end: usize) -> EndIndex { + let mut ends: Vec<((i64, i64), usize, Vec2)> = edges .iter() .enumerate() .filter_map(|(i, edge)| ends(points, edge).map(|(start, end)| (i, start, end))) - .flat_map(|(i, start, end)| [(frame.cell(start), 2 * i), (frame.cell(end), 2 * i + 1)]) - .filter_map(|(cell, id)| cell.map(|cell| (cell, id))) + .flat_map(|(i, start, end)| [(2 * i, start), (2 * i + 1, end)]) + .filter_map(|(id, p)| frame.cell(p).map(|cell| (cell, id, p))) .collect(); - ends.sort_unstable(); + ends.sort_unstable_by_key(|&(cell, id, _)| (cell, id)); let next = (0..ends.len()).collect(); - EndIndex { ends, next } + let checks = ends.len().saturating_mul(checks_per_end); + EndIndex { ends, next, checks, spent: false } } - /// The unused edge listed first with an end in `p`'s cell or one next to it, and whether - /// that end is the edge's last point (its first point when both are there). + /// The unused edge listed first with an end within `tol` of `p`, and whether that end is the + /// edge's last point (its first point when both are). fn find(&mut self, frame: &Frame, p: Vec2, used: &[bool]) -> Option<(usize, bool)> { let (x, y) = frame.cell(p)?; - let id = (-1..=1).flat_map(|dx| (-1..=1).map(move |dy| (x + dx, y + dy))).filter_map(|cell| self.first_unused(cell, used)).min()?; - Some((id / 2, id % 2 == 1)) + let mut best = None; + for cell in (-1..=1).flat_map(|dx| (-1..=1).map(move |dy| (x + dx, y + dy))) { + best = self.first_within(cell, p, frame.tol, used, best).or(best); + } + best.map(|id| (id / 2, id % 2 == 1)) } - /// The first end in `cell` whose edge is unused. Used ends are skipped once for good. - fn first_unused(&mut self, cell: (i64, i64), used: &[bool]) -> Option { - let first = self.ends.partition_point(|(c, _)| *c < cell); + /// The first end in `cell` within `tol` of `p` whose edge is unused, listed before `below`. + /// Used ends at the front of the cell are skipped once for good. + fn first_within(&mut self, cell: (i64, i64), p: Vec2, tol: f64, used: &[bool], below: Option) -> Option { + let unused = |id: usize| !used.get(id / 2).copied().unwrap_or(true); + let first = self.ends.partition_point(|(c, ..)| *c < cell); let mut at = self.next.get(first).copied()?; - let found = loop { - match self.ends.get(at) { - Some(&(c, id)) if c == cell => { - if !used.get(id / 2).copied().unwrap_or(true) { - break Some(id); - } - at += 1; - } - _ => break None, - } - }; + while self.ends.get(at).is_some_and(|&(c, id, _)| c == cell && !unused(id)) { + at += 1; + } if let Some(next) = self.next.get_mut(first) { *next = at; } - found + for &(c, id, q) in self.ends.get(at..).unwrap_or_default() { + if c != cell || below.is_some_and(|below| id >= below) { + break; + } + if self.checks == 0 { + self.spent = true; + return None; + } + self.checks -= 1; + if unused(id) && q.near(p, tol) { + return Some(id); + } + } + None } } diff --git a/crates/io/tests/it/hatch_edge_chain.rs b/crates/io/tests/it/hatch_edge_chain.rs index 4ed3c0942..40a3a7e47 100644 --- a/crates/io/tests/it/hatch_edge_chain.rs +++ b/crates/io/tests/it/hatch_edge_chain.rs @@ -179,6 +179,60 @@ fn ends_that_differ_by_rounding_still_meet() { assert_same(&shuffled, &in_order); } +#[test] +fn an_end_just_past_the_tolerance_does_not_meet() { + // A 1,000-wide path: ends meet within 1e-3. The triangle A T C is stored with a gap of 5e-4 + // at T; a second triangle has a corner X 1.7e-3 from T, in the next lookup cell. Listed + // before the edge that does meet T, X's edge must still not be joined there. + let (a, t, t2, c) = ([0.0, 0.0], [500.0002, 0.0], [500.0007, 0.0], [250.0, 10.0]); + let (x, r, q) = ([500.0019, 0.0], [1000.0, 0.0], [750.0, 10.0]); + let after = vertices(&[line(a, t), line(t2, c), line(c, a), line(q, x), line(x, r), line(r, q)]); + let before = vertices(&[line(a, t), line(q, x), line(t2, c), line(c, a), line(x, r), line(r, q)]); + assert_same(&before, &after); +} + +/// Line edges joined in file order: each edge's start unless the list already ends there, then +/// its end, and the closing point dropped. +fn in_file_order(edges: &[Edge]) -> Vec { + let mut out: Vec = Vec::new(); + for edge in edges { + let Edge::Line(a, b) = edge else { panic!("lines only") }; + for p in [a, b] { + let p = Vec2::new(p[0], p[1]); + if out.last().is_none_or(|last| !last.p.near(p, 1e-9)) { + out.push(PolyVertex::new(p)); + } + } + } + if out.len() > 1 && out[0].p.near(out[out.len() - 1].p, 1e-9) { + out.pop(); + } + out +} + +#[test] +fn a_loop_whose_lookups_take_too_long_is_read_in_file_order() { + // Petals from a point Q out and back, and many edges from two points 1.4 tolerances either + // side of Q, listed between the first petal and the rest: every return to Q looks at those + // on one side (the other is two cells away). Past the lookup budget the loop is read in file + // order, as before chaining. + let at = |r: f64, k: usize, n: usize| { + let a = std::f64::consts::TAU * k as f64 / n as f64; + [r * a.cos(), r * a.sin()] + }; + let (q, side) = ([0.0, 0.0], 2.8e-3); + let mut edges = vec![line(q, at(1000.0, 0, 1000))]; + for i in 0..2000 { + edges.push(line([if i % 2 == 0 { side } else { -side }, 0.0], at(500.0, i, 2000))); + } + edges.push(line(at(1000.0, 0, 1000), q)); + for k in 1..1000 { + edges.push(line(q, at(1000.0, k, 1000))); + edges.push(line(at(1000.0, k, 1000), q)); + } + assert_eq!(vertices(&edges), in_file_order(&edges)); +} + #[test] fn an_open_path_is_chained_from_both_ends() { // Three sides of the square, A to D, listed from the middle: the edges before the first From 364881867c7f5a28b17d8a6399e5c6f2a8550aa3 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:17:07 +0700 Subject: [PATCH 3/3] Hatch edge chaining: close each later outline at its exact start A later outline was closed back to its start only when its end lay farther than the tolerance from it (review). With the end within the tolerance but not equal, the jump back to the first outline left from the end while the jump out arrived at the start, so the two did not cancel under even-odd fill and a sliver between them was filled. The start is now added whenever the end differs from it. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_read/hatch/chain.rs | 4 +++- crates/io/tests/it/hatch_edge_chain.rs | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/io/src/dxf_read/hatch/chain.rs b/crates/io/src/dxf_read/hatch/chain.rs index cbd5ea1d2..f0d8df7cd 100644 --- a/crates/io/src/dxf_read/hatch/chain.rs +++ b/crates/io/src/dxf_read/hatch/chain.rs @@ -88,7 +88,9 @@ pub(super) fn chain(points: &[PolyVertex], edges: &[Range]) -> Vec