mirror of
https://github.com/storytold/cadcraft.git
synced 2026-12-02 20:22:15 -05:00
* HATCH by internal point keeps the arcs of its boundary (#1167) The boundary search works on flattened curves, so a hatch made by picking inside a circle stored 158 chords and AREA came out short (5025.22 for pi*40^2 = 5026.55). Each traced edge now keeps the input polyline it came from (region::Boundary::outer_edges, Island::edges, outline_edges, enclosing_loop_edges_gap; bridged gaps are None), and each input polyline is one piece of one object: a line, a circle, an arc or one segment of a polyline. arcs::with_arcs turns each run of edges on the same circular piece back into one bulged vertex and moves the corners onto the exact curves (line-circle or circle-circle crossing nearest the traced corner, within the reach a shallow crossing needs, else onto the circle). Nothing is matched by proximity, so a line or an ellipse next to a circle is never taken for it. The associative refill does the same, so a hatch keeps its arcs when its objects move. dedup_loops now merges only loops with the same role: a loop that is one pick's outer loop and another's island stays twice, as the even-odd fill needs (one hatch picked inside a circle and around it, or inside a square within a square, left the inner shape empty once the two loops matched). A boundary object selected twice is used once. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Hatch arcs: origin from the arcs' extents; opposite-role duplicate loops cancel - HPORIGINMODE's corners came from the loop vertices only, so a circle kept as two half-circles had no height and its corner origins fell on its centre line. The extents now include each bulged edge's arc. - A pick inside a circle and one around it keep the circle as an outer loop and as an island. The renderer collapsed the two into one loop, so the circle drew empty, and AREA measured them by nesting. Two loops that are the same boundary now collapse only in the same role (a repeated loop); in opposite roles they cancel, as they do under the odd-parity fill. AREA measures the loops the fill keeps (`hatch_fill_loop_indices`), exactly with their arcs. - Tests: the circle's corner origins, BOUNDARY keeping a circle's and a rounded rectangle's arcs, and the drawn fill and AREA of the circle inside a square. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Hatch loops: same-role repeats collapse before opposite roles cancel; HATCHEDIT keeps islands - The renderer cancelled an outer loop and an island as it met them, so the same loops in another order filled differently (outer, island, outer left a hole; outer, outer, island left none). Repeats within a role now collapse first, then an outer loop and an island that are the same boundary cancel, spending the same comparison budget. - HATCHEDIT adding a boundary the hatch already has (its island) added a second copy, which then cancelled the island. A boundary already there is no longer added. Co-Authored-By: Claude Opus 5.5 <[email protected]> * HATCHEDIT: a boundary already there takes the added objects' links Adding a boundary the hatch already has dropped the added loop, and with it the objects it came from, so an unlinked island picked with addBoundary stayed unlinked. The objects now join the loop already there (no second copy is added). Co-Authored-By: Claude Opus 5.5 <[email protected]> * AREA of a hatch tests nesting at an edge's middle, as the fill does AREA tested whether a loop is an island at its first vertex, which can lie on the loop around it (an island touching the outer boundary): the island was then added instead of subtracted. It now uses the fill's own test point, the middle of the first non-degenerate edge (`hatch_loop_probe`). Co-Authored-By: Claude Opus 5.5 <[email protected]> * Hatch loop dedup: look only at loops that could match, stop when the budget is spent The comparison budget bounded `same_polygon`, but both passes still walked every kept loop for each new one, O(n²) in the number of loops however few matched. Loops are now found by (role, vertex count), so only possible matches are looked at, and once the budget is spent no more are. A test sorts 40,000 distinct loops. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs: hatch gap tolerance (HPGAPTOL) is done, not missing Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs: BOUNDARY keeps the arcs of what it traces Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: FredApps <[email protected]>
This commit is contained in:
11 files changed
+771
-77
No files matched your search
@@ -17,6 +17,7 @@ use super::{CommandSpec, bad, bool_or, f64_or, point_param, points_param, size_p
|
||||
|
||||
use crate::{Accept, EngineError, Input, Interactive, Picker, Prompt, Result, Session, Step};
|
||||
|
||||
mod arcs;
|
||||
mod assoc;
|
||||
pub(crate) use assoc::detach;
|
||||
mod edit;
|
||||
@@ -54,13 +55,15 @@ pub(super) fn outline_tol(ext: Bounds2) -> f64 {
|
||||
}
|
||||
|
||||
/// Tessellated outlines of every visible curve in the space (hatch boundary candidates), each
|
||||
/// with the handle of the object it came from.
|
||||
fn outlines(d: &Drawing, space: &Space, near: Option<Bounds2>) -> (Vec<Vec<Vec2>>, Vec<Handle>) {
|
||||
let Some(store) = d.space(space) else { return (Vec::new(), Vec::new()) };
|
||||
/// with the handle of the object it came from and its exact piece ([`arcs::pieces_of`]), and
|
||||
/// the flattening tolerance.
|
||||
fn outlines(d: &Drawing, space: &Space, near: Option<Bounds2>) -> (Vec<Vec<Vec2>>, Vec<Handle>, Vec<Option<arcs::Piece>>, f64) {
|
||||
let ext = d.extents(space);
|
||||
let tol = outline_tol(ext);
|
||||
let Some(store) = d.space(space) else { return (Vec::new(), Vec::new(), Vec::new(), tol) };
|
||||
let mut out = Vec::new();
|
||||
let mut owners = Vec::new();
|
||||
let mut pieces = Vec::new();
|
||||
for e in store.iter() {
|
||||
if !d.is_visible(e) || matches!(e.kind, EntityKind::Hatch(_) | EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Dimension(_)) {
|
||||
continue;
|
||||
@@ -73,9 +76,10 @@ fn outlines(d: &Drawing, space: &Space, near: Option<Bounds2>) -> (Vec<Vec<Vec2>
|
||||
}
|
||||
let polys = object_polys(d, e, tol, ext);
|
||||
owners.extend(std::iter::repeat_n(e.handle, polys.len()));
|
||||
pieces.extend(arcs::pieces_of(e, polys.len()));
|
||||
out.extend(polys);
|
||||
}
|
||||
(out, owners)
|
||||
(out, owners, pieces, tol)
|
||||
}
|
||||
|
||||
/// An object's outline as polylines (tolerance `tol`), infinite lines clipped to a generous
|
||||
@@ -193,7 +197,7 @@ impl OriginMode {
|
||||
}
|
||||
/// The origin for loops: `current` when the mode keeps it.
|
||||
pub(crate) fn origin(self, loops: &[HatchLoop], current: Vec2) -> Vec2 {
|
||||
let b = Bounds2::from_points(loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p)).filter(|p| p.is_finite()));
|
||||
let b = loops_bounds(loops);
|
||||
if b.is_empty() {
|
||||
return current;
|
||||
}
|
||||
@@ -208,6 +212,25 @@ impl OriginMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// The extents of hatch loops with their arcs: a bulged edge reaches past its vertices (a circle
|
||||
/// kept as two half-circle vertices spans its whole height).
|
||||
fn loops_bounds(loops: &[HatchLoop]) -> Bounds2 {
|
||||
let mut b = Bounds2::from_points(loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p)).filter(|p| p.is_finite()));
|
||||
for l in loops {
|
||||
let vs = &l.vertices;
|
||||
for (i, v) in vs.iter().enumerate() {
|
||||
let Some(next) = vs.get((i + 1) % vs.len()) else { continue };
|
||||
if let Some((arc, _)) = cadcraft_geom::bulge_to_arc(v.p, next.p, v.bulge) {
|
||||
let ab = arc.bounds();
|
||||
if ab.min.is_finite() && ab.max.is_finite() {
|
||||
b = b.union(&ab);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Island detection style by name (HPISLANDDETECTION 0 normal, 1 outer, 2 ignore).
|
||||
pub(crate) fn island_style(t: &str) -> Option<u8> {
|
||||
match t.trim().to_ascii_lowercase().as_str() {
|
||||
@@ -224,15 +247,17 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
|
||||
let space = s.space();
|
||||
let ext = d.extents(&space);
|
||||
let tol = ((ext.width() + ext.height()) * 1e-9).max(1e-9);
|
||||
let (polys, owners) = outlines(d, &space, None);
|
||||
let (polys, owners, pieces, ftol) = outlines(d, &space, None);
|
||||
// A line that ends on a flattened curve (an ellipse) can stop short of its chords.
|
||||
let polys = cadcraft_geom::region::snap_ends(&polys, outline_tol(ext), tol);
|
||||
let polys = cadcraft_geom::region::snap_ends(&polys, ftol, tol);
|
||||
let found = cadcraft_geom::region::boundary_at_gap(&polys, p, tol, gap_tolerance(d))
|
||||
.ok_or_else(|| EngineError::Other("Valid hatch boundary not found.".into()))?;
|
||||
let outer = found.outer;
|
||||
let ob = Bounds2::from_points(outer.iter().copied());
|
||||
let sources = handles_of(&owners, &found.outer_sources);
|
||||
let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, boundary_flags: None, sources }];
|
||||
// The traced outline is flattened: circular runs become arcs again (#1167).
|
||||
let mut loops =
|
||||
vec![HatchLoop { vertices: arcs::with_arcs(&outer, &found.outer_edges, &pieces, ftol), outer: true, boundary_flags: None, sources }];
|
||||
// Islands: closed objects entirely inside the outer loop that don't contain the pick point.
|
||||
if let Some(store) = d.space(&space) {
|
||||
for e in store.iter() {
|
||||
@@ -261,7 +286,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
|
||||
if open_curves {
|
||||
let sources = handles_of(&owners, &island.sources);
|
||||
loops.push(HatchLoop {
|
||||
vertices: island.outline.into_iter().map(PolyVertex::new).collect(),
|
||||
vertices: arcs::with_arcs(&island.outline, &island.edges, &pieces, ftol),
|
||||
outer: false,
|
||||
boundary_flags: None,
|
||||
sources,
|
||||
@@ -274,7 +299,9 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
|
||||
pub(crate) fn loops_from_handles(s: &Session, hs: &[Handle]) -> Result<Vec<HatchLoop>> {
|
||||
let d = s.doc()?;
|
||||
let mut loops = Vec::new();
|
||||
for h in hs {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
// An object selected twice is one boundary.
|
||||
for h in hs.iter().filter(|h| seen.insert(**h)) {
|
||||
if let Some(vs) = d.entity(*h).and_then(|e| closed_loop(d, e)) {
|
||||
loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), boundary_flags: None, sources: vec![*h] });
|
||||
}
|
||||
@@ -429,17 +456,18 @@ fn same_loop(a: &HatchLoop, b: &HatchLoop) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Deduplicate boundary loops that describe the same boundary.
|
||||
/// Deduplicate boundary loops that describe the same boundary in the same role. A loop that is
|
||||
/// one pick's outer loop and another's island (a pick inside a circle and one around it) stays
|
||||
/// twice: merged, the island would be gone and the even-odd fill would leave the circle empty.
|
||||
fn dedup_loops(loops: &mut Vec<HatchLoop>) {
|
||||
let mut unique: Vec<HatchLoop> = Vec::with_capacity(loops.len());
|
||||
for l in loops.drain(..) {
|
||||
if let Some(existing) = unique.iter_mut().find(|u| same_loop(u, &l)) {
|
||||
if let Some(existing) = unique.iter_mut().find(|u| u.outer == l.outer && same_loop(u, &l)) {
|
||||
for s in l.sources {
|
||||
if !existing.sources.contains(&s) {
|
||||
existing.sources.push(s);
|
||||
}
|
||||
}
|
||||
existing.outer = existing.outer || l.outer;
|
||||
} else {
|
||||
unique.push(l);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Exact arcs in traced hatch boundaries (#1167).
|
||||
//!
|
||||
//! The boundary search works on flattened curves, so a loop traced around an internal point
|
||||
//! comes out as chords: a hatch in a circle had 158 straight edges and the wrong area. Each
|
||||
//! traced edge knows the input polyline it lies on, and each input polyline is one piece of one
|
||||
//! object (a line, a circle, an arc or one segment of a polyline), so nothing is guessed from
|
||||
//! nearby geometry: a run of edges on the same circular piece becomes one bulged vertex again,
|
||||
//! and the corners move onto the exact curves (where a line or another circle crosses).
|
||||
|
||||
use cadcraft_doc::{Entity, EntityKind, Prim};
|
||||
use cadcraft_geom::{Circle, Line, PolyVertex, Segment, Vec2, arc_to_bulge, circle_circle, line_circle, shoelace};
|
||||
|
||||
/// The exact curve behind one input polyline.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) enum Piece {
|
||||
Line(Line),
|
||||
Circle(Circle),
|
||||
}
|
||||
|
||||
/// The exact piece behind each of `e`'s `n` outline polylines (one per primitive, in order, as
|
||||
/// `select::hit_polylines` makes them), or `None` for each when `e` isn't made of lines and
|
||||
/// circular arcs or the count doesn't match.
|
||||
pub(crate) fn pieces_of(e: &Entity, n: usize) -> Vec<Option<Piece>> {
|
||||
if !matches!(e.kind, EntityKind::Line(_) | EntityKind::Arc(_) | EntityKind::Circle(_) | EntityKind::LwPolyline(_)) {
|
||||
return vec![None; n];
|
||||
}
|
||||
let prims = e.kind.prims();
|
||||
if prims.len() != n {
|
||||
return vec![None; n];
|
||||
}
|
||||
prims
|
||||
.iter()
|
||||
.map(|p| match p {
|
||||
Prim::Seg(Segment::Line(l)) => Some(Piece::Line(*l)),
|
||||
Prim::Seg(Segment::Arc { arc, .. }) => Some(Piece::Circle(Circle::new(arc.center, arc.radius))),
|
||||
Prim::Circle(c) => Some(Piece::Circle(*c)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn same_circle(a: &Circle, b: &Circle) -> bool {
|
||||
a.center == b.center && a.radius == b.radius
|
||||
}
|
||||
|
||||
/// The loop `pts` (edge `i` from `pts[i]` to the next vertex, closed) with its circular runs
|
||||
/// as bulged vertices. `edges` names each edge's input polyline, `pieces` each polyline's exact
|
||||
/// curve; `tol` is the flattening tolerance the polylines were made with. Anything that doesn't
|
||||
/// check out stays as traced.
|
||||
pub(crate) fn with_arcs(pts: &[Vec2], edges: &[Option<usize>], pieces: &[Option<Piece>], tol: f64) -> Vec<PolyVertex> {
|
||||
let n = pts.len();
|
||||
let plain = || pts.iter().map(|p| PolyVertex::new(*p)).collect::<Vec<_>>();
|
||||
if n < 3 || edges.len() != n || !(tol.is_finite() && tol > 0.0) || pts.iter().any(|p| !p.is_finite()) {
|
||||
return plain();
|
||||
}
|
||||
let at = |i: usize| pts.get(i % n).copied().unwrap_or_default();
|
||||
let piece = |i: usize| edges.get(i % n).copied().flatten().and_then(|k| pieces.get(k).copied().flatten());
|
||||
// A chord of a curve flattened to `tol` stays within `tol` of it; corners split where two
|
||||
// chords cross may be a little further.
|
||||
let slack = tol * 4.0;
|
||||
let near_circle = |c: &Circle, q: Vec2| (c.center.dist(q) - c.radius).abs() <= slack;
|
||||
// The circle each edge lies on: its piece is a circle and both ends and the middle are on
|
||||
// it (the middle, so a long chord across the circle doesn't pass for an arc).
|
||||
let circ: Vec<Option<(usize, Circle)>> = (0..n)
|
||||
.map(|i| {
|
||||
let k = edges.get(i).copied().flatten()?;
|
||||
let Some(Piece::Circle(c)) = piece(i) else { return None };
|
||||
let (a, b) = (at(i), at(i + 1));
|
||||
(c.radius.is_finite() && c.radius > slack && near_circle(&c, a) && near_circle(&c, b) && near_circle(&c, a.mid(b))).then_some((k, c))
|
||||
})
|
||||
.collect();
|
||||
let key = |i: usize| circ.get(i % n).copied().flatten().map(|(k, _)| k);
|
||||
if circ.iter().all(Option::is_none) {
|
||||
return plain();
|
||||
}
|
||||
let ccw = shoelace(pts) > 0.0;
|
||||
// One whole circle: two half circles, as a hatch made by selecting the circle has.
|
||||
if let Some(Some((k0, c))) = circ.first().copied()
|
||||
&& (0..n).all(|i| key(i) == Some(k0))
|
||||
{
|
||||
let b = if ccw { 1.0 } else { -1.0 };
|
||||
return vec![PolyVertex::with_bulge(c.center - Vec2::X * c.radius, b), PolyVertex::with_bulge(c.center + Vec2::X * c.radius, b)];
|
||||
}
|
||||
let line_of = |i: usize| match piece(i) {
|
||||
Some(Piece::Line(l)) if l.a != l.b && [at(i), at(i + 1)].iter().all(|q| ((*q - l.a).cross(l.b - l.a) / l.a.dist(l.b)).abs() <= slack) => {
|
||||
Some(l)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let onto = |c: &Circle, q: Vec2| {
|
||||
let d = q - c.center;
|
||||
if d.len() > 0.0 { c.center + d.normalized() * c.radius } else { q }
|
||||
};
|
||||
// Vertex `i` (between edges `i - 1` and `i`) on the exact curves: where the two pieces
|
||||
// cross, nearest the traced corner, or else moved onto the circle it is on.
|
||||
let corner = |i: usize| -> Vec2 {
|
||||
let p = at(i);
|
||||
let (prev, next) = (circ.get((i + n - 1) % n).copied().flatten(), circ.get(i % n).copied().flatten());
|
||||
let crossings: Vec<Vec2> = match (prev, next) {
|
||||
(Some((_, a)), Some((_, b))) if same_circle(&a, &b) => return onto(&a, p),
|
||||
(Some((_, a)), Some((_, b))) => circle_circle(&a, &b),
|
||||
(Some((_, c)), None) => line_of(i).map(|l| line_circle(&l, &c).into_iter().map(|x| x.0).collect()).unwrap_or_default(),
|
||||
(None, Some((_, c))) => line_of(i + n - 1).map(|l| line_circle(&l, &c).into_iter().map(|x| x.0).collect()).unwrap_or_default(),
|
||||
(None, None) => return p,
|
||||
};
|
||||
// Where two curves cross at a shallow angle, a corner off them by the flattening
|
||||
// tolerance can be off along them by up to about √(2·r·tolerance): the crossing nearest
|
||||
// the traced corner is taken within that reach, when no other crossing is as near.
|
||||
let r = prev.or(next).map_or(0.0, |(_, c)| c.radius);
|
||||
let reach = slack * 2.0 + (2.0 * r * slack).sqrt();
|
||||
let mut xs: Vec<(f64, Vec2)> = crossings.into_iter().filter(|x| x.is_finite()).map(|x| (x.dist(p), x)).collect();
|
||||
xs.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
match (xs.first(), xs.get(1)) {
|
||||
(Some(&(d, x)), second) if d <= reach && second.is_none_or(|&(d2, _)| d2 > 2.0 * d + slack) => x,
|
||||
_ => prev.or(next).map_or(p, |(_, c)| onto(&c, p)),
|
||||
}
|
||||
};
|
||||
// Start where a run begins, so no run wraps past the end.
|
||||
let Some(s) = (0..n).find(|&i| key(i) != key(i + n - 1)) else { return plain() };
|
||||
let mut out = Vec::with_capacity(n);
|
||||
let mut i = 0;
|
||||
while i < n {
|
||||
let e = (s + i) % n;
|
||||
let p = corner(e);
|
||||
let Some((k, c)) = circ.get(e).copied().flatten() else {
|
||||
out.push(PolyVertex::new(p));
|
||||
i += 1;
|
||||
continue;
|
||||
};
|
||||
// The angle the run turns through about the centre, edge by edge.
|
||||
let mut sweep = 0.0;
|
||||
let mut a = p;
|
||||
let mut j = i;
|
||||
while j < n && key(s + j) == Some(k) {
|
||||
let last = j + 1 >= n || key(s + j + 1) != Some(k);
|
||||
let b = if last { corner(s + j + 1) } else { at(s + j + 1) };
|
||||
let (u, v) = (a - c.center, b - c.center);
|
||||
sweep += u.cross(v).atan2(u.dot(v));
|
||||
a = b;
|
||||
j += 1;
|
||||
}
|
||||
let bulge = arc_to_bulge(sweep);
|
||||
out.push(PolyVertex::with_bulge(p, if bulge.is_finite() { bulge } else { 0.0 }));
|
||||
i = j;
|
||||
}
|
||||
if out.len() < 2 { plain() } else { out }
|
||||
}
|
||||
@@ -87,8 +87,14 @@ fn refill(before: &Drawing, after: &Drawing, l: &HatchLoop) -> Refill {
|
||||
return Refill::Open;
|
||||
}
|
||||
let tol = super::outline_tol(nb);
|
||||
let mut polys: Vec<Vec<Vec2>> = Vec::new();
|
||||
let mut pieces = Vec::new();
|
||||
for e in live.iter().filter_map(|h| after.entity(*h)) {
|
||||
let ps = object_polys(after, e, tol, nb);
|
||||
pieces.extend(super::arcs::pieces_of(e, ps.len()));
|
||||
polys.extend(ps);
|
||||
}
|
||||
let snap = ((nb.width() + nb.height()) * 1e-9).max(1e-9);
|
||||
let polys: Vec<Vec<Vec2>> = live.iter().filter_map(|h| after.entity(*h)).flat_map(|e| object_polys(after, e, tol, nb)).collect();
|
||||
let polys = region::snap_ends(&polys, tol, snap);
|
||||
let gap = gap_tolerance(after);
|
||||
let found = if l.outer {
|
||||
@@ -97,13 +103,14 @@ fn refill(before: &Drawing, after: &Drawing, l: &HatchLoop) -> Refill {
|
||||
let ob = if ob.is_empty() { nb } else { ob };
|
||||
let old = outline_of(&l.vertices, (ob.width() + ob.height()).max(1e-9) / 20000.0);
|
||||
region::interior_point(&old)
|
||||
.and_then(|q| region::enclosing_loop_gap(&polys, map_point(q, &ob, &nb), snap, gap))
|
||||
.or_else(|| region::outline(&polys, snap, gap))
|
||||
.and_then(|q| region::enclosing_loop_edges_gap(&polys, map_point(q, &ob, &nb), snap, gap))
|
||||
.or_else(|| region::outline_edges(&polys, snap, gap))
|
||||
} else {
|
||||
region::outline(&polys, snap, gap)
|
||||
region::outline_edges(&polys, snap, gap)
|
||||
};
|
||||
match found {
|
||||
Some(pts) => Refill::Loop(pts.into_iter().map(PolyVertex::new).collect()),
|
||||
// Traced again from flattened curves: circular runs become arcs again (#1167).
|
||||
Some((pts, edges)) => Refill::Loop(super::arcs::with_arcs(&pts, &edges, &pieces, tol)),
|
||||
None => Refill::Open,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ use cadcraft_geom::{Bounds2, Polyline, Vec2, point_in_polygon};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::assoc::{detach, same_shape};
|
||||
use super::{GRADIENT_NAMES, ORIGIN_KW, OriginMode, closed_loop, dedup_loops, gradient_name, island_style, loops_at, loops_from_handles};
|
||||
use super::{GRADIENT_NAMES, ORIGIN_KW, OriginMode, closed_loop, dedup_loops, gradient_name, island_style, loops_at, loops_from_handles, same_loop};
|
||||
use crate::cmd::helpers::lwpoly;
|
||||
use crate::cmd::{bad, bool_or, point_param, points_param, size_param, str_param, targets};
|
||||
use crate::{Accept, Input, Interactive, Picker, Prompt, Result, Session, Step};
|
||||
@@ -420,7 +420,21 @@ fn edit_loops(h: &mut Hatch, added: &[HatchLoop], removed: &[usize]) -> Result<(
|
||||
return Ok(());
|
||||
}
|
||||
h.loops = h.loops.drain(..).enumerate().filter_map(|(i, l)| (!removed.contains(&i)).then_some(l)).collect();
|
||||
h.loops.extend_from_slice(added);
|
||||
// A boundary the hatch already has is not added again (whatever role it has here): a second
|
||||
// copy would cancel it under the odd-parity fill. Its objects join the loop there, so picking
|
||||
// it links an unlinked loop to them.
|
||||
for a in added {
|
||||
match h.loops.iter_mut().find(|l| same_loop(l, a)) {
|
||||
Some(l) => {
|
||||
for s in &a.sources {
|
||||
if !l.sources.contains(s) {
|
||||
l.sources.push(*s);
|
||||
}
|
||||
}
|
||||
}
|
||||
None => h.loops.push(a.clone()),
|
||||
}
|
||||
}
|
||||
dedup_loops(&mut h.loops);
|
||||
if h.loops.is_empty() {
|
||||
return Err(bad("hatchedit", "a hatch needs at least one boundary loop"));
|
||||
|
||||
@@ -532,12 +532,17 @@ pub(super) fn object_area(s: &Session, h: Handle) -> Result<(f64, f64)> {
|
||||
(cadcraft_geom::PI * a * b, arc.arc_length_from(0.0, cadcraft_geom::TAU))
|
||||
}
|
||||
EntityKind::Hatch(hh) => {
|
||||
// Odd parity, as drawn: a loop nested inside an odd number of other loops is an unfilled island.
|
||||
let geoms: Vec<Polyline> = hh.loops.iter().map(|l| Polyline { vertices: l.vertices.clone(), closed: true }).collect();
|
||||
let polys: Vec<Vec<Vec2>> = geoms.iter().map(|g| g.tessellate(1e-3)).collect();
|
||||
// Odd parity, as drawn: a loop nested inside an odd number of other loops is an unfilled
|
||||
// island. The loops the fill keeps (a repeated loop once; an outer loop and an island
|
||||
// that are the same boundary cancel), each measured exactly with its arcs.
|
||||
let kept = cadcraft_render::hatch_fill_loop_indices(hh, 1e-3);
|
||||
let geoms: Vec<Polyline> =
|
||||
kept.iter().filter_map(|(i, _)| hh.loops.get(*i)).map(|l| Polyline { vertices: l.vertices.clone(), closed: true }).collect();
|
||||
let polys: Vec<Vec<Vec2>> = kept.into_iter().map(|(_, p)| p).collect();
|
||||
let mut total = (0.0, 0.0);
|
||||
for (i, g) in geoms.iter().enumerate() {
|
||||
let probe = polys.get(i).and_then(|p| p.first().copied());
|
||||
// As the fill tests nesting: an edge's middle (a vertex may touch the loop around).
|
||||
let probe = polys.get(i).and_then(|p| cadcraft_render::hatch_loop_probe(p));
|
||||
let depth = probe.map_or(0, |pt| polys.iter().enumerate().filter(|(j, q)| *j != i && cadcraft_geom::point_in_polygon(q, pt)).count());
|
||||
total.0 += if depth % 2 == 0 { g.area().abs() } else { -g.area().abs() };
|
||||
total.1 += g.len();
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
//! A hatch made by picking an internal point keeps the arcs of its boundary (#1167): the traced
|
||||
//! outline comes from flattened curves, and its runs along a circle, an arc or a polyline's arc
|
||||
//! segment become arcs again, so AREA on the hatch equals AREA on the objects. Only edges traced
|
||||
//! from those circular pieces become arcs: a line or an ellipse near a circle stays as it is.
|
||||
|
||||
use std::f64::consts::PI;
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{EntityKind, Handle, Hatch, HatchLoop};
|
||||
use cadcraft_engine::geom::Polyline;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn handle(v: &Value) -> String {
|
||||
v["handle"].as_str().or_else(|| v["handles"][0].as_str()).unwrap().to_string()
|
||||
}
|
||||
|
||||
fn hatch(s: &Session, h: &str) -> Hatch {
|
||||
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
|
||||
EntityKind::Hatch(x) => x.clone(),
|
||||
k => panic!("not a hatch: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn pl(l: &HatchLoop) -> Polyline {
|
||||
Polyline { vertices: l.vertices.clone(), closed: true }
|
||||
}
|
||||
|
||||
/// Filled area, exact with bulges: outer loops minus islands.
|
||||
fn area(h: &Hatch) -> f64 {
|
||||
h.loops.iter().map(|l| pl(l).area().abs() * if l.outer { 1.0 } else { -1.0 }).sum()
|
||||
}
|
||||
|
||||
fn bulges(l: &HatchLoop) -> usize {
|
||||
l.vertices.iter().filter(|v| v.bulge.abs() > 1e-9).count()
|
||||
}
|
||||
|
||||
fn close(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-6 * (1.0 + b.abs())
|
||||
}
|
||||
|
||||
fn hatch_at(s: &mut Session, points: &[[f64; 2]]) -> String {
|
||||
handle(&s.execute("hatch", &json!({ "points": points, "pattern": "SOLID" })).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_hatched_inside_is_two_half_circles_with_the_circles_area() {
|
||||
let mut s = Session::new();
|
||||
let c = handle(&s.execute("circle", &json!({ "center": [50, 50], "radius": 40 })).unwrap());
|
||||
let h = {
|
||||
let hh = hatch_at(&mut s, &[[50.0, 50.0]]);
|
||||
hatch(&s, &hh)
|
||||
};
|
||||
let l = &h.loops[0];
|
||||
assert_eq!(l.vertices.len(), 2, "{:?}", l.vertices);
|
||||
assert!(l.vertices.iter().all(|v| (v.bulge.abs() - 1.0).abs() < 1e-12));
|
||||
assert!(close(area(&h), PI * 1600.0), "{}", area(&h));
|
||||
assert!(h.associative && l.sources.iter().any(|x| x.hex() == c));
|
||||
// Typed at the command line, as in the report.
|
||||
let mut s = Session::new();
|
||||
s.script("CIRCLE 50,50 40\n-HATCH P SOLID\n50,50\n\n").unwrap();
|
||||
let h = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Hatch(x) = &e.kind { Some(x.clone()) } else { None }).unwrap();
|
||||
assert!(close(area(&h), PI * 1600.0), "{}", area(&h));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rounded_rectangle_keeps_its_arc_as_one_polyline_or_as_lines_and_an_arc() {
|
||||
// 100 x 50 with a semicircular right side: 5000 + π·25²/2.
|
||||
let want = 5000.0 + PI * 625.0 / 2.0;
|
||||
let mut s = Session::new();
|
||||
s.execute("pline", &json!({ "vertices": [[0, 0], { "p": [100, 0], "bulge": 1.0 }, [100, 50], [0, 50]], "closed": true })).unwrap();
|
||||
let h = {
|
||||
let hh = hatch_at(&mut s, &[[50.0, 25.0]]);
|
||||
hatch(&s, &hh)
|
||||
};
|
||||
assert_eq!(h.loops[0].vertices.len(), 4, "{:?}", h.loops[0].vertices);
|
||||
assert_eq!(bulges(&h.loops[0]), 1);
|
||||
assert!(close(area(&h), want), "{}", area(&h));
|
||||
// The same shape as three lines and an arc, then moved with its objects.
|
||||
let mut s = Session::new();
|
||||
let mut objs = Vec::new();
|
||||
for (a, b) in [([0, 0], [100, 0]), ([100, 50], [0, 50]), ([0, 50], [0, 0])] {
|
||||
objs.push(handle(&s.execute("line", &json!({ "points": [a, b] })).unwrap()));
|
||||
}
|
||||
objs.push(handle(&s.execute("arc", &json!({ "center": [100, 25], "radius": 25, "start": -90, "end": 90 })).unwrap()));
|
||||
let hh = hatch_at(&mut s, &[[50.0, 25.0]]);
|
||||
let h = hatch(&s, &hh);
|
||||
assert_eq!(bulges(&h.loops[0]), 1);
|
||||
assert!(close(area(&h), want), "{}", area(&h));
|
||||
objs.push(hh.clone());
|
||||
s.execute("move", &json!({ "handles": objs, "delta": [7, 3] })).unwrap();
|
||||
let h = hatch(&s, &hh);
|
||||
assert_eq!(bulges(&h.loops[0]), 1, "{:?}", h.loops[0].vertices);
|
||||
assert!(close(area(&h), want), "{}", area(&h));
|
||||
}
|
||||
|
||||
/// A circle of radius 10 at the origin cut by a line `y = c`: the cap above it and the rest.
|
||||
fn cut_circle(c: f64) -> (Session, f64, f64) {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[-20, c], [20, c]] })).unwrap();
|
||||
let theta = 2.0 * (c / 10.0).acos();
|
||||
let cap = 50.0 * (theta - theta.sin());
|
||||
(s, cap, PI * 100.0 - cap)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_cut_by_a_line_gives_the_exact_segments_even_for_a_shallow_cut() {
|
||||
// (A cut shallower than the flattening tolerance finds no boundary, as before.)
|
||||
for c in [3.0, 9.9, 9.99] {
|
||||
let (mut s, cap, rest) = cut_circle(c);
|
||||
let top = {
|
||||
let hh = hatch_at(&mut s, &[[0.0, (c + 10.0) / 2.0]]);
|
||||
hatch(&s, &hh)
|
||||
};
|
||||
let bottom = {
|
||||
let hh = hatch_at(&mut s, &[[0.0, 0.0]]);
|
||||
hatch(&s, &hh)
|
||||
};
|
||||
assert!(close(area(&top), cap), "cap at {c}: {} vs {cap}", area(&top));
|
||||
assert!(close(area(&bottom), rest), "rest at {c}: {} vs {rest}", area(&bottom));
|
||||
// Every point of both outlines stays on or inside the circle and on its side of the line.
|
||||
for (h, above) in [(&top, true), (&bottom, false)] {
|
||||
for q in pl(&h.loops[0]).tessellate(1e-4) {
|
||||
assert!(q.len() <= 10.0 + 1e-6, "{q:?} outside the circle (cut at {c})");
|
||||
assert!(if above { q.y >= c - 1e-6 } else { q.y <= c + 1e-6 }, "{q:?} past the line (cut at {c})");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ellipse_or_a_line_next_to_a_circle_is_not_taken_for_it() {
|
||||
// An ellipse a hair wider than the circle crosses it four times; the region inside both is
|
||||
// bounded by circle arcs and ellipse pieces, which stay flattened.
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
|
||||
s.execute("ellipse", &json!({ "center": [0, 0], "major": [10.05, 0], "ratio": 0.99 })).unwrap();
|
||||
let h = {
|
||||
let hh = hatch_at(&mut s, &[[0.0, 0.0]]);
|
||||
hatch(&s, &hh)
|
||||
};
|
||||
// Within the flattening tolerance of both curves, as the flattened outline was: where the
|
||||
// two cross at a shallow angle the corner is only known to that tolerance.
|
||||
let tol = 2.0 * (s.doc().unwrap().extents(&cadcraft_engine::doc::Space::Model).width() + 20.1) / 20000.0;
|
||||
for q in pl(&h.loops[0]).tessellate(1e-4) {
|
||||
assert!(q.len() <= 10.0 + tol, "{q:?} outside the circle");
|
||||
let r = 10.05 * (q.x * q.x + q.y * q.y / (0.99 * 0.99)).sqrt() / 10.05;
|
||||
assert!(r <= 10.05 + tol, "{q:?} outside the ellipse");
|
||||
}
|
||||
// A line just outside the circle, tangent-close: the hatch inside the circle is the circle.
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
|
||||
s.execute("line", &json!({ "points": [[-20, 10.0001], [20, 10.0001]] })).unwrap();
|
||||
let h = {
|
||||
let hh = hatch_at(&mut s, &[[0.0, 0.0]]);
|
||||
hatch(&s, &hh)
|
||||
};
|
||||
assert!(close(area(&h), PI * 100.0), "{}", area(&h));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_hatch_inside_and_around_a_circle_fills_both() {
|
||||
// Picked inside the circle and in the square around it: the circle is filled too.
|
||||
let mut s = Session::new();
|
||||
s.execute("rectang", &json!({ "p1": [0, 0], "p2": [100, 100] })).unwrap();
|
||||
s.execute("circle", &json!({ "center": [50, 50], "radius": 20 })).unwrap();
|
||||
let hh = hatch_at(&mut s, &[[50.0, 50.0], [5.0, 5.0]]);
|
||||
let h = hatch(&s, &hh);
|
||||
assert!(close(filled(&h), 10000.0), "{} from {:?}", filled(&h), h.loops.iter().map(|l| (l.outer, l.vertices.len())).collect::<Vec<_>>());
|
||||
// As drawn and as AREA measures it: the circle's outer loop and island cancel, the square
|
||||
// is filled whole.
|
||||
let drawn = cadcraft_engine::render::hatch_fill_loops(&h, 1e-3);
|
||||
let centre = cadcraft_engine::geom::Vec2::new(50.0, 50.0);
|
||||
assert_eq!(drawn.iter().filter(|l| cadcraft_engine::geom::point_in_polygon(l, centre)).count() % 2, 1, "the circle is filled");
|
||||
let a = s.execute("area", &json!({ "handle": hh })).unwrap()["area"].as_f64().unwrap();
|
||||
assert!(close(a, 10000.0), "{a}");
|
||||
// The same with a square inside the square (exact on main too, so merged there).
|
||||
let mut s = Session::new();
|
||||
s.execute("rectang", &json!({ "p1": [0, 0], "p2": [100, 100] })).unwrap();
|
||||
s.execute("rectang", &json!({ "p1": [40, 40], "p2": [60, 60] })).unwrap();
|
||||
let hh = hatch_at(&mut s, &[[50.0, 50.0], [5.0, 5.0]]);
|
||||
let h = hatch(&s, &hh);
|
||||
assert!(close(filled(&h), 10000.0), "{}", filled(&h));
|
||||
}
|
||||
|
||||
/// The area the even-odd fill covers: points on a fine grid inside an odd number of loops.
|
||||
fn filled(h: &Hatch) -> f64 {
|
||||
let polys: Vec<Vec<cadcraft_engine::geom::Vec2>> = h.loops.iter().map(|l| pl(l).tessellate(1e-3)).collect();
|
||||
let n = 400;
|
||||
let step = 100.0 / n as f64;
|
||||
let mut inside = 0usize;
|
||||
for i in 0..n {
|
||||
for j in 0..n {
|
||||
let q = cadcraft_engine::geom::Vec2::new((i as f64 + 0.5) * step, (j as f64 + 0.5) * step);
|
||||
if polys.iter().filter(|p| cadcraft_engine::geom::point_in_polygon(p, q)).count() % 2 == 1 {
|
||||
inside += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
inside as f64 * step * step
|
||||
}
|
||||
|
||||
/// HPORIGINMODE's corners take the circle's extents, not only its two vertices (a circle kept as
|
||||
/// two half-circles spans its whole height).
|
||||
#[test]
|
||||
fn a_circles_hatch_origin_takes_its_extents() {
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [50, 50], "radius": 40 })).unwrap();
|
||||
let h = handle(&s.execute("hatch", &json!({ "points": [[50, 50]], "pattern": "ANSI31", "originMode": "bottomLeft" })).unwrap());
|
||||
let o = hatch(&s, &h).origin;
|
||||
assert!(close(o.x, 10.0) && close(o.y, 10.0), "{o:?}");
|
||||
let h = handle(&s.execute("hatch", &json!({ "points": [[50, 50]], "pattern": "ANSI31", "originMode": "topRight" })).unwrap());
|
||||
let o = hatch(&s, &h).origin;
|
||||
assert!(close(o.x, 90.0) && close(o.y, 90.0), "{o:?}");
|
||||
}
|
||||
|
||||
/// The polyline BOUNDARY makes keeps the arcs: a circle gives two half-circles, a rounded
|
||||
/// rectangle one arc segment, each with the object's exact area.
|
||||
#[test]
|
||||
fn boundary_keeps_the_arcs() {
|
||||
let lw = |s: &Session, h: &str| -> Polyline {
|
||||
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
|
||||
EntityKind::LwPolyline(p) => Polyline { vertices: p.vertices.clone(), closed: p.closed },
|
||||
k => panic!("not a polyline: {k:?}"),
|
||||
}
|
||||
};
|
||||
let mut s = Session::new();
|
||||
s.execute("circle", &json!({ "center": [50, 50], "radius": 40 })).unwrap();
|
||||
let b = handle(&s.execute("boundary", &json!({ "points": [[50, 50]] })).unwrap());
|
||||
let p = lw(&s, &b);
|
||||
assert_eq!(p.vertices.len(), 2, "{:?}", p.vertices);
|
||||
assert!(p.vertices.iter().all(|v| (v.bulge.abs() - 1.0).abs() < 1e-12));
|
||||
assert!(close(p.area().abs(), PI * 1600.0), "{}", p.area());
|
||||
|
||||
let mut s = Session::new();
|
||||
s.execute("pline", &json!({ "vertices": [[0, 0], { "p": [100, 0], "bulge": 1.0 }, [100, 50], [0, 50]], "closed": true })).unwrap();
|
||||
let b = handle(&s.execute("boundary", &json!({ "points": [[50, 25]] })).unwrap());
|
||||
let p = lw(&s, &b);
|
||||
assert_eq!(p.vertices.iter().filter(|v| v.bulge.abs() > 1e-9).count(), 1, "{:?}", p.vertices);
|
||||
assert!(close(p.area().abs(), 5000.0 + PI * 625.0 / 2.0), "{}", p.area());
|
||||
}
|
||||
|
||||
/// HATCHEDIT adding a boundary the hatch already has (its island) changes nothing: a second copy
|
||||
/// of the island would cancel it and fill the circle.
|
||||
#[test]
|
||||
fn hatchedit_adding_an_existing_island_keeps_it() {
|
||||
let mut s = Session::new();
|
||||
s.execute("rectang", &json!({ "p1": [0, 0], "p2": [100, 100] })).unwrap();
|
||||
let c = handle(&s.execute("circle", &json!({ "center": [50, 50], "radius": 20 })).unwrap());
|
||||
// Not associative: its island is linked to nothing until the circle is added.
|
||||
let hh = handle(&s.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "SOLID", "associative": false })).unwrap());
|
||||
assert!(hatch(&s, &hh).loops.iter().all(|l| l.sources.is_empty()));
|
||||
let before = hatch(&s, &hh).loops.len();
|
||||
s.execute("hatchedit", &json!({ "handles": [hh], "addBoundary": [c] })).unwrap();
|
||||
let h = hatch(&s, &hh);
|
||||
assert_eq!(h.loops.len(), before, "{:?}", h.loops.iter().map(|l| (l.outer, l.vertices.len())).collect::<Vec<_>>());
|
||||
let drawn = cadcraft_engine::render::hatch_fill_loops(&h, 1e-3);
|
||||
let centre = cadcraft_engine::geom::Vec2::new(50.0, 50.0);
|
||||
assert_eq!(drawn.iter().filter(|l| cadcraft_engine::geom::point_in_polygon(l, centre)).count() % 2, 0, "the island stays empty");
|
||||
// The island is linked to the circle that was added.
|
||||
assert!(
|
||||
h.loops.iter().any(|l| !l.outer && l.sources.iter().any(|x| x.hex() == c)),
|
||||
"{:?}",
|
||||
h.loops.iter().map(|l| (l.outer, l.sources.clone())).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
/// AREA tests a loop's nesting at an edge's middle, as the fill does: an island whose first vertex
|
||||
/// lies on the outer loop (here on its right edge, where a vertex test says "outside") is still
|
||||
/// subtracted.
|
||||
#[test]
|
||||
fn area_subtracts_an_island_touching_the_outer_loop() {
|
||||
use cadcraft_engine::geom::{PolyVertex, Vec2};
|
||||
let lp = |pts: &[(f64, f64)], outer: bool| HatchLoop {
|
||||
vertices: pts.iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(),
|
||||
outer,
|
||||
boundary_flags: None,
|
||||
sources: vec![],
|
||||
};
|
||||
let mut s = Session::new();
|
||||
let h = Hatch {
|
||||
loops: vec![lp(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)], true), lp(&[(10.0, 5.0), (5.0, 4.0), (5.0, 6.0)], false)],
|
||||
pattern: "SOLID".into(),
|
||||
solid: true,
|
||||
scale: 1.0,
|
||||
..hatch_template(&mut s)
|
||||
};
|
||||
let id = s.add_entity(EntityKind::Hatch(h)).unwrap();
|
||||
let a = s.execute("area", &json!({ "handle": id.hex() })).unwrap()["area"].as_f64().unwrap();
|
||||
assert!(close(a, 100.0 - 5.0), "{a}");
|
||||
}
|
||||
|
||||
/// Any hatch's fields, to build one by hand.
|
||||
fn hatch_template(s: &mut Session) -> Hatch {
|
||||
s.execute("rectang", &json!({ "p1": [200, 200], "p2": [210, 210] })).unwrap();
|
||||
let hh = hatch_at(s, &[[205.0, 205.0]]);
|
||||
hatch(s, &hh)
|
||||
}
|
||||
@@ -71,6 +71,7 @@ mod grip_options;
|
||||
mod grip_selection;
|
||||
mod group_selection;
|
||||
mod groups;
|
||||
mod hatch_arcs;
|
||||
mod hatch_assoc;
|
||||
mod hatch_dialog_helpers;
|
||||
mod hatch_generate_boundary;
|
||||
|
||||
+72
-13
@@ -33,6 +33,9 @@ pub struct Boundary {
|
||||
pub islands: Vec<Island>,
|
||||
/// Indices into the input polylines that make up `outer`, ascending.
|
||||
pub outer_sources: Vec<usize>,
|
||||
/// The input polyline of each edge of `outer` (`outer[i]` to the next vertex), `None` for a
|
||||
/// gap bridged with HPGAPTOL.
|
||||
pub outer_edges: Vec<Option<usize>>,
|
||||
}
|
||||
|
||||
/// One island: the outside outline of a connected group of curves.
|
||||
@@ -42,6 +45,8 @@ pub struct Island {
|
||||
pub outline: Vec<Vec2>,
|
||||
/// Indices into the input polylines that make up the group, ascending.
|
||||
pub sources: Vec<usize>,
|
||||
/// The input polyline of each edge of `outline`, as [`Boundary::outer_edges`].
|
||||
pub edges: Vec<Option<usize>>,
|
||||
}
|
||||
|
||||
#[expect(
|
||||
@@ -62,6 +67,8 @@ struct Graph {
|
||||
src: Vec<(usize, usize)>,
|
||||
/// The input polyline of every edge (lower vertex index first).
|
||||
edge_src: HashMap<(usize, usize), usize>,
|
||||
/// Edges that bridge a gap between curve ends (HPGAPTOL), lower vertex index first.
|
||||
gap: std::collections::HashSet<(usize, usize)>,
|
||||
}
|
||||
|
||||
/// Records the crossing of segments `i` and `j`, if any, as split parameters on both.
|
||||
@@ -210,7 +217,7 @@ fn build_with(polys: &[Vec<Vec2>], tol: f64, find_splits: impl Fn(&[(Vec2, Vec2)
|
||||
let bb = Bounds2::from_points(segs.iter().flat_map(|(a, b)| [*a, *b]));
|
||||
let n = segs.len();
|
||||
let splits = find_splits(&segs, &bb)?;
|
||||
let mut g = Graph { pts: Vec::new(), adj: Vec::new(), src: Vec::with_capacity(n), edge_src: HashMap::new() };
|
||||
let mut g = Graph { pts: Vec::new(), adj: Vec::new(), src: Vec::with_capacity(n), edge_src: HashMap::new(), gap: Default::default() };
|
||||
let mut index: HashMap<(i64, i64), usize> = HashMap::new();
|
||||
let mut vid = |p: Vec2, g: &mut Graph| -> usize {
|
||||
let k = key(p, bb.min, tol);
|
||||
@@ -295,6 +302,7 @@ fn build_gap(polys: &[Vec<Vec2>], tol: f64, gap: f64) -> Option<Graph> {
|
||||
if let Some(k) = owner {
|
||||
g.edge_src.insert((u.min(v), u.max(v)), k);
|
||||
}
|
||||
g.gap.insert((u.min(v), u.max(v)));
|
||||
if let Some(f) = joined.get_mut(i) {
|
||||
*f = true;
|
||||
}
|
||||
@@ -342,6 +350,17 @@ fn points(g: &Graph, ids: &[usize]) -> Option<Vec<Vec2>> {
|
||||
ids.iter().map(|&i| g.pts.get(i).copied()).collect()
|
||||
}
|
||||
|
||||
/// The input polyline of each edge of the closed loop `ids` (`None` for a bridged gap).
|
||||
fn edge_owners(g: &Graph, ids: &[usize]) -> Vec<Option<usize>> {
|
||||
ids.iter()
|
||||
.zip(ids.iter().cycle().skip(1))
|
||||
.map(|(&u, &v)| {
|
||||
let k = (u.min(v), u.max(v));
|
||||
if g.gap.contains(&k) { None } else { g.edge_src.get(&k).copied() }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The face around `p`, as vertex indices (counter-clockwise).
|
||||
#[expect(clippy::many_single_char_names, reason = "Ray/edge traversal keeps conventional graph and point notation.")]
|
||||
fn outer_face(g: &Graph, p: Vec2) -> Option<Vec<usize>> {
|
||||
@@ -420,12 +439,12 @@ fn prune(g: &Graph) -> Graph {
|
||||
}
|
||||
}
|
||||
}
|
||||
Graph { pts: g.pts.clone(), adj, src: Vec::new(), edge_src: HashMap::new() }
|
||||
Graph { pts: g.pts.clone(), adj, src: Vec::new(), edge_src: g.edge_src.clone(), gap: g.gap.clone() }
|
||||
}
|
||||
|
||||
/// The outline of the outside of a group of curves on cycles, traced counter-clockwise from its
|
||||
/// leftmost (then lowest) vertex `u`, giving up after `steps` edges.
|
||||
fn outside(core: &Graph, u: usize, steps: usize) -> Option<Vec<Vec2>> {
|
||||
fn outside(core: &Graph, u: usize, steps: usize) -> Option<(Vec<Vec2>, Vec<Option<usize>>)> {
|
||||
let pu = *core.pts.get(u)?;
|
||||
// Every neighbour lies to the right of the leftmost vertex; the one turned furthest
|
||||
// counter-clockwise has the outside of the group on its left.
|
||||
@@ -436,9 +455,9 @@ fn outside(core: &Graph, u: usize, steps: usize) -> Option<Vec<Vec2>> {
|
||||
})
|
||||
};
|
||||
let w = core.adj.get(u).into_iter().flatten().filter_map(|w| Some((signed(w)?, *w))).max_by(|a, b| a.0.total_cmp(&b.0)).map(|(_, w)| w)?;
|
||||
let mut lp = trace(core, u, w, steps).and_then(|ids| points(core, &ids))?;
|
||||
lp.reverse();
|
||||
Some(lp)
|
||||
let mut ids = trace(core, u, w, steps)?;
|
||||
ids.reverse();
|
||||
Some((points(core, &ids)?, edge_owners(core, &ids)))
|
||||
}
|
||||
|
||||
/// Outlines of the groups of curves inside the face `outer` (vertex indices into `g`).
|
||||
@@ -497,7 +516,7 @@ fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Option<Vec<Island>> {
|
||||
continue;
|
||||
}
|
||||
let steps = edges.get(&c).copied().unwrap_or(0).saturating_add(4);
|
||||
let Some(lp) = outside(&core, u, steps) else { continue };
|
||||
let Some((lp, edges)) = outside(&core, u, steps) else { continue };
|
||||
let area = shoelace(&lp);
|
||||
let ib = Bounds2::from_points(lp.iter().copied());
|
||||
if lp.len() < 3 || !area.is_finite() || area <= 0.0 || !ob.contains_box(&ib) {
|
||||
@@ -511,7 +530,7 @@ fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Option<Vec<Island>> {
|
||||
let mut src = sources.remove(&c).unwrap_or_default();
|
||||
src.sort_unstable();
|
||||
src.dedup();
|
||||
out.push(Island { outline: lp, sources: src });
|
||||
out.push(Island { outline: lp, sources: src, edges });
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
@@ -619,8 +638,14 @@ pub fn enclosing_loop(polys: &[Vec<Vec2>], p: Vec2, tol: f64) -> Option<Vec<Vec2
|
||||
|
||||
/// [`enclosing_loop`], with gaps of up to `gap` between curve ends closed (HPGAPTOL).
|
||||
pub fn enclosing_loop_gap(polys: &[Vec<Vec2>], p: Vec2, tol: f64, gap: f64) -> Option<Vec<Vec2>> {
|
||||
enclosing_loop_edges_gap(polys, p, tol, gap).map(|(lp, _)| lp)
|
||||
}
|
||||
|
||||
/// [`enclosing_loop_gap`] with the input polyline of each edge, as [`Boundary::outer_edges`].
|
||||
pub fn enclosing_loop_edges_gap(polys: &[Vec<Vec2>], p: Vec2, tol: f64, gap: f64) -> Option<(Vec<Vec2>, Vec<Option<usize>>)> {
|
||||
let g = build_gap(polys, tol, gap)?;
|
||||
points(&g, &outer_face(&g, p)?)
|
||||
let ids = outer_face(&g, p)?;
|
||||
Some((points(&g, &ids)?, edge_owners(&g, &ids)))
|
||||
}
|
||||
|
||||
/// The closed loop enclosing `p` plus the islands inside it, or `None` when `p` isn't enclosed.
|
||||
@@ -638,14 +663,20 @@ pub fn boundary_at_gap(polys: &[Vec<Vec2>], p: Vec2, tol: f64, gap: f64) -> Opti
|
||||
ids.iter().zip(ids.iter().cycle().skip(1)).filter_map(|(&u, &v)| g.edge_src.get(&(u.min(v), u.max(v))).copied()).collect();
|
||||
outer_sources.sort_unstable();
|
||||
outer_sources.dedup();
|
||||
Some(Boundary { outer, islands, outer_sources })
|
||||
let outer_edges = edge_owners(&g, &ids);
|
||||
Some(Boundary { outer, islands, outer_sources, outer_edges })
|
||||
}
|
||||
|
||||
/// The outside outline of curves that together enclose an area (counter-clockwise, dangling
|
||||
/// ends removed), or `None` when they enclose nothing or form more than one separate group.
|
||||
/// Gaps of up to `gap` between curve ends are closed (HPGAPTOL).
|
||||
#[expect(clippy::float_cmp, reason = "Exact x equality is required for the deterministic lexicographic tie-break.")]
|
||||
pub fn outline(polys: &[Vec<Vec2>], tol: f64, gap: f64) -> Option<Vec<Vec2>> {
|
||||
outline_edges(polys, tol, gap).map(|(lp, _)| lp)
|
||||
}
|
||||
|
||||
/// [`outline`] with the input polyline of each edge, as [`Boundary::outer_edges`].
|
||||
#[expect(clippy::float_cmp, reason = "Exact x equality is required for the deterministic lexicographic tie-break.")]
|
||||
pub fn outline_edges(polys: &[Vec<Vec2>], tol: f64, gap: f64) -> Option<(Vec<Vec2>, Vec<Option<usize>>)> {
|
||||
let g = build_gap(polys, tol, gap)?;
|
||||
let core = prune(&g);
|
||||
let comp = components(&core);
|
||||
@@ -667,8 +698,8 @@ pub fn outline(polys: &[Vec<Vec2>], tol: f64, gap: f64) -> Option<Vec<Vec2>> {
|
||||
start = Some(u);
|
||||
}
|
||||
}
|
||||
let lp = outside(&core, start?, edges.saturating_add(4))?;
|
||||
(lp.len() >= 3 && shoelace(&lp) > 0.0).then_some(lp)
|
||||
let (lp, owners) = outside(&core, start?, edges.saturating_add(4))?;
|
||||
(lp.len() >= 3 && shoelace(&lp) > 0.0).then_some((lp, owners))
|
||||
}
|
||||
|
||||
/// A point strictly inside a closed polygon (either orientation), for re-finding the face a
|
||||
@@ -1075,6 +1106,34 @@ mod tests {
|
||||
assert!(interior_point(&[Vec2::new(f64::NAN, 0.0); 4]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edges_name_their_input_polyline_and_bridged_gaps_none() {
|
||||
// A square of four separate sides; the right side stops short of the top (a gap).
|
||||
let sides = vec![
|
||||
vec![Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)],
|
||||
vec![Vec2::new(10.0, 0.0), Vec2::new(10.0, 9.9)],
|
||||
vec![Vec2::new(10.0, 10.0), Vec2::new(0.0, 10.0)],
|
||||
vec![Vec2::new(0.0, 10.0), Vec2::new(0.0, 0.0)],
|
||||
];
|
||||
let b = boundary_at_gap(&sides, Vec2::new(5.0, 5.0), 1e-9, 0.5).unwrap();
|
||||
assert_eq!(b.outer_edges.len(), b.outer.len());
|
||||
// Each edge names the side it lies on; the bridged gap names none.
|
||||
for (i, e) in b.outer_edges.iter().enumerate() {
|
||||
let (a, c) = (b.outer[i], b.outer[(i + 1) % b.outer.len()]);
|
||||
match e {
|
||||
Some(k) => {
|
||||
let s = &sides[*k];
|
||||
let on = |q: Vec2| crate::Line::new(s[0], s[1]).closest(q).dist(q) < 1e-9;
|
||||
assert!(on(a) && on(c), "edge {i} not on side {k}");
|
||||
}
|
||||
None => assert!(a.dist(c) < 0.5 + 1e-9, "only the gap is unnamed"),
|
||||
}
|
||||
}
|
||||
assert_eq!(b.outer_edges.iter().filter(|e| e.is_none()).count(), 1);
|
||||
let (lp, edges) = outline_edges(&sides, 1e-9, 0.5).unwrap();
|
||||
assert_eq!(lp.len(), edges.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gap_tolerance_closes_small_gaps() {
|
||||
// Four lines with 0.5 gaps at two corners.
|
||||
|
||||
+165
-35
@@ -81,43 +81,97 @@ fn same_polygon(a: &[Vec2], b: &[Vec2]) -> bool {
|
||||
|
||||
/// Remove degenerate and duplicate boundary loops within a shared comparison budget.
|
||||
/// Retain remaining loops without further comparisons once the budget is exhausted.
|
||||
#[cfg(test)]
|
||||
fn dedup_polygons(loops: &mut Vec<Vec<Vec2>>) {
|
||||
let roled: Vec<(usize, bool, Vec<Vec2>)> = loops.drain(..).enumerate().map(|(i, l)| (i, true, l)).collect();
|
||||
*loops = dedup_roles(roled).into_iter().map(|(_, _, l)| l).collect();
|
||||
}
|
||||
|
||||
/// [`dedup_polygons`] with each loop's role (outer, or island) and index: a loop the same as one
|
||||
/// kept in the same role is a duplicate and goes (a file can repeat a loop); one the same as a
|
||||
/// kept loop in the other role cancels it, both going, as they do under the odd-parity fill (one
|
||||
/// pick's outer loop that is another's island: a pick inside a circle and one around it fill the
|
||||
/// circle too).
|
||||
fn dedup_roles(loops: Vec<(usize, bool, Vec<Vec2>)>) -> Vec<(usize, bool, Vec<Vec2>)> {
|
||||
// `same_polygon` is O(n²) in a polygon's vertex count (every cyclic alignment, both windings),
|
||||
// and each loop is compared against every unique one kept so far, so adversarial boundary
|
||||
// geometry could force quadratic-on-quadratic work. Charge every vertex comparison against a
|
||||
// shared budget; once it is spent, stop deduplicating and keep the remaining loops as-is
|
||||
// (CWE-407).
|
||||
// and each loop is compared with the loops kept so far, so adversarial boundary geometry could
|
||||
// force quadratic-on-quadratic work. Only loops that could match are looked at (same role, or
|
||||
// the other one, and the same vertex count, found by key), every vertex comparison is charged
|
||||
// against a shared budget, and once it is spent no more loops are looked at: the rest are kept
|
||||
// as they are (CWE-407).
|
||||
let mut budget: u64 = MAX_DEDUP_COMPARISONS;
|
||||
let mut unique: Vec<Vec<Vec2>> = Vec::with_capacity(loops.len());
|
||||
for l in loops.drain(..) {
|
||||
// First a repeat within its role goes: the first of each boundary per role is kept.
|
||||
let mut unique: Vec<(usize, bool, Vec<Vec2>)> = Vec::with_capacity(loops.len());
|
||||
let mut by_shape: std::collections::HashMap<(bool, usize), Vec<usize>> = std::collections::HashMap::new();
|
||||
for (i, outer, l) in loops {
|
||||
if l.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let mut dup = false;
|
||||
for u in &unique {
|
||||
if u.len() != l.len() {
|
||||
continue;
|
||||
}
|
||||
// Each `same_polygon` call costs about 2·len² comparisons; stop if that would overrun.
|
||||
let cost = 2u64.saturating_mul((u.len() as u64).saturating_mul(l.len() as u64));
|
||||
match budget.checked_sub(cost) {
|
||||
Some(left) => budget = left,
|
||||
None => {
|
||||
// Out of budget: keep `l` without further comparison.
|
||||
budget = 0;
|
||||
break;
|
||||
}
|
||||
let key = (outer, l.len());
|
||||
let mut repeat = false;
|
||||
for &k in by_shape.get(&key).map_or(&[][..], Vec::as_slice) {
|
||||
let Some((_, _, u)) = unique.get(k) else { continue };
|
||||
if !charge(&mut budget, u.len(), l.len()) {
|
||||
break;
|
||||
}
|
||||
if same_polygon(u, &l) {
|
||||
dup = true;
|
||||
repeat = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !dup {
|
||||
unique.push(l);
|
||||
if !repeat {
|
||||
by_shape.entry(key).or_default().push(unique.len());
|
||||
unique.push((i, outer, l));
|
||||
}
|
||||
}
|
||||
// Then an outer loop and an island that are the same boundary cancel, whatever their order.
|
||||
let mut slots: Vec<Option<(usize, bool, Vec<Vec2>)>> = Vec::with_capacity(unique.len());
|
||||
let mut open: std::collections::HashMap<(bool, usize), Vec<usize>> = std::collections::HashMap::new();
|
||||
for (i, outer, l) in unique {
|
||||
let twin_key = (!outer, l.len());
|
||||
let mut twin = None;
|
||||
for (at, &k) in open.get(&twin_key).map_or(&[][..], Vec::as_slice).iter().enumerate() {
|
||||
let Some(Some((_, _, u))) = slots.get(k) else { continue };
|
||||
if !charge(&mut budget, u.len(), l.len()) {
|
||||
break;
|
||||
}
|
||||
if same_polygon(u, &l) {
|
||||
twin = Some((at, k));
|
||||
break;
|
||||
}
|
||||
}
|
||||
match twin {
|
||||
Some((at, k)) => {
|
||||
if let Some(slot) = slots.get_mut(k) {
|
||||
*slot = None;
|
||||
}
|
||||
if let Some(ks) = open.get_mut(&twin_key) {
|
||||
ks.remove(at);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
open.entry((outer, l.len())).or_default().push(slots.len());
|
||||
slots.push(Some((i, outer, l)));
|
||||
}
|
||||
}
|
||||
}
|
||||
slots.into_iter().flatten().collect()
|
||||
}
|
||||
|
||||
/// Charge a `same_polygon` call between loops of `a` and `b` vertices (about 2·a·b comparisons)
|
||||
/// against `budget`: false, with the budget spent, when it would overrun.
|
||||
fn charge(budget: &mut u64, a: usize, b: usize) -> bool {
|
||||
let cost = 2u64.saturating_mul((a as u64).saturating_mul(b as u64));
|
||||
match budget.checked_sub(cost) {
|
||||
Some(left) if *budget > 0 => {
|
||||
*budget = left;
|
||||
true
|
||||
}
|
||||
_ => {
|
||||
*budget = 0;
|
||||
false
|
||||
}
|
||||
}
|
||||
*loops = unique;
|
||||
}
|
||||
|
||||
/// Vertex comparisons `dedup_polygons` may perform before it stops deduplicating.
|
||||
@@ -128,32 +182,45 @@ const MAX_DEDUP_COMPARISONS: u64 = 50_000_000;
|
||||
/// within islands alternate), 1 outer keeps the outermost loops and their first islands, 2
|
||||
/// ignore keeps only the outermost loops. Nesting depth = how many other loops enclose a loop.
|
||||
pub fn fill_loops(h: &Hatch, tol: f64) -> Vec<Vec<Vec2>> {
|
||||
fill_loop_indices(h, tol).into_iter().map(|(_, l)| l).collect()
|
||||
}
|
||||
|
||||
/// [`fill_loops`] with the index in `h.loops` of each loop kept (AREA measures those exactly).
|
||||
pub fn fill_loop_indices(h: &Hatch, tol: f64) -> Vec<(usize, Vec<Vec2>)> {
|
||||
// One point budget for all the loops: many short arcs across loops must not add up unbounded.
|
||||
let mut budget = cadcraft_geom::MAX_TESSELLATED_POINTS;
|
||||
// Source loops that are the same boundary up to start vertex and winding are tessellated once, so a
|
||||
// duplicate cannot be sampled coarser than its twin by the shared budget and then escape `dedup_polygons`.
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut loops: Vec<Vec<Vec2>> = h
|
||||
// Source loops that are the same boundary up to start vertex and winding are tessellated once and
|
||||
// share that tessellation, so a duplicate cannot be sampled coarser than its twin by the shared
|
||||
// budget and then escape `dedup_roles`. Each keeps its own role: a repeat in the same role still
|
||||
// collapses there, and an outer loop still cancels against the same boundary as an island.
|
||||
let mut tessellated: std::collections::HashMap<Vec<[u64; 3]>, Vec<Vec2>> = std::collections::HashMap::new();
|
||||
let roled: Vec<(usize, bool, Vec<Vec2>)> = h
|
||||
.loops
|
||||
.iter()
|
||||
.filter(|l| seen.insert(canonical_key(&l.vertices)))
|
||||
.map(|l| Polyline { vertices: l.vertices.clone(), closed: true }.tessellate_within(tol, &mut budget))
|
||||
.enumerate()
|
||||
.map(|(i, l)| {
|
||||
let pts = tessellated
|
||||
.entry(canonical_key(&l.vertices))
|
||||
.or_insert_with(|| Polyline { vertices: l.vertices.clone(), closed: true }.tessellate_within(tol, &mut budget))
|
||||
.clone();
|
||||
(i, l.outer, pts)
|
||||
})
|
||||
.collect();
|
||||
dedup_polygons(&mut loops);
|
||||
let loops: Vec<(usize, Vec<Vec2>)> = dedup_roles(roled).into_iter().map(|(i, _, l)| (i, l)).collect();
|
||||
let max_depth = match h.style {
|
||||
1 => 1,
|
||||
2 => 0,
|
||||
_ => return loops,
|
||||
};
|
||||
let verts: usize = loops.iter().map(Vec::len).sum();
|
||||
let verts: usize = loops.iter().map(|(_, l)| l.len()).sum();
|
||||
if loops.len().saturating_mul(verts) > MAX_ISLAND_WORK {
|
||||
return loops;
|
||||
}
|
||||
let depth = |i: usize, l: &[Vec2]| {
|
||||
let Some(p) = probe(l) else { return 0 };
|
||||
loops.iter().enumerate().filter(|(j, o)| *j != i && point_in_polygon(o, p)).count()
|
||||
loops.iter().enumerate().filter(|(j, (_, o))| *j != i && point_in_polygon(o, p)).count()
|
||||
};
|
||||
loops.iter().enumerate().filter(|(i, l)| depth(*i, l) <= max_depth).map(|(_, l)| l.clone()).collect()
|
||||
loops.iter().enumerate().filter(|(i, (_, l))| depth(*i, l) <= max_depth).map(|(_, x)| x.clone()).collect()
|
||||
}
|
||||
|
||||
/// Start index of the least rotation of `s` (two-pointer scan, O(n)).
|
||||
@@ -202,7 +269,7 @@ fn canonical_key(v: &[PolyVertex]) -> Vec<[u64; 3]> {
|
||||
|
||||
/// A point of a loop to test its nesting with: the middle of its first non-degenerate edge
|
||||
/// (vertices may touch an enclosing loop; edge midpoints rarely do).
|
||||
fn probe(l: &[Vec2]) -> Option<Vec2> {
|
||||
pub fn probe(l: &[Vec2]) -> Option<Vec2> {
|
||||
let n = l.len();
|
||||
(0..n).find_map(|i| {
|
||||
let (a, b) = (*l.get(i)?, *l.get((i + 1) % n)?);
|
||||
@@ -710,6 +777,69 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod role_dedup_tests {
|
||||
use super::*;
|
||||
use cadcraft_doc::{Hatch, HatchLoop};
|
||||
use cadcraft_geom::PolyVertex;
|
||||
|
||||
fn square(x0: f64, x1: f64, outer: bool) -> HatchLoop {
|
||||
HatchLoop {
|
||||
vertices: [(x0, x0), (x1, x0), (x1, x1), (x0, x1)].iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(),
|
||||
outer,
|
||||
boundary_flags: None,
|
||||
sources: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// The same boundary as outer and island loops: repeats within a role collapse first, then an
|
||||
/// outer loop and an island cancel, so the fill doesn't depend on the loops' order.
|
||||
#[test]
|
||||
fn coincident_loops_give_the_same_fill_in_any_order() {
|
||||
let hatch = |loops: Vec<HatchLoop>| Hatch {
|
||||
origin: Vec2::ZERO,
|
||||
pattern: "SOLID".into(),
|
||||
solid: true,
|
||||
loops,
|
||||
scale: 1.0,
|
||||
angle: 0.0,
|
||||
associative: false,
|
||||
style: 0,
|
||||
elevation: 0.0,
|
||||
gradient: None,
|
||||
background: None,
|
||||
pattern_lines: vec![],
|
||||
};
|
||||
let inner = |o: bool| square(40.0, 60.0, o);
|
||||
for order in [vec![true, false, true], vec![true, true, false], vec![false, true, true]] {
|
||||
let mut loops = vec![square(0.0, 100.0, true)];
|
||||
loops.extend(order.iter().map(|&o| inner(o)));
|
||||
let kept = fill_loops(&hatch(loops), 1e-4);
|
||||
assert_eq!(kept.len(), 1, "{order:?}: only the enclosing square is left");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod role_dedup_scale_tests {
|
||||
use super::*;
|
||||
|
||||
/// Many distinct loops (as an adversarial file may hold) are sorted out quickly: only loops
|
||||
/// that could match are looked at, and once the budget is spent none are.
|
||||
#[test]
|
||||
fn many_distinct_loops_are_handled_quickly() {
|
||||
let tri = |k: usize| {
|
||||
let x = k as f64;
|
||||
vec![Vec2::new(x, 0.0), Vec2::new(x + 0.5, 0.0), Vec2::new(x, 0.5)]
|
||||
};
|
||||
let loops: Vec<(usize, bool, Vec<Vec2>)> = (0..40_000).map(|k| (k, k % 2 == 0, tri(k))).collect();
|
||||
let start = std::time::Instant::now();
|
||||
let kept = dedup_roles(loops);
|
||||
assert_eq!(kept.len(), 40_000);
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod dedup_budget_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -33,7 +33,7 @@ use pen::Pen;
|
||||
|
||||
pub use dim::{ArrowGeom, Arrowhead, DimGeometry, DimText, LineRole, arrowhead, dimension_geometry, dimension_geometry_with, format_linear_value};
|
||||
pub use fill::triangulate_evenodd;
|
||||
pub use hatch::{fill_loops as hatch_fill_loops, pattern_swatch};
|
||||
pub use hatch::{fill_loop_indices as hatch_fill_loop_indices, fill_loops as hatch_fill_loops, pattern_swatch, probe as hatch_loop_probe};
|
||||
pub use paper::{PAPER_SIZES, PaperSize, Sheet, paper_size, sheet};
|
||||
pub use tolerance::{gdt_points, tolerance_in};
|
||||
|
||||
|
||||
@@ -112,9 +112,13 @@ Where line and arc are supported the results are exact.
|
||||
`geom/src/region.rs`: curves are polygonised, crossings split on a grid, vertices merged at
|
||||
`tol`, a ray picks the edge and the face is traced by sharpest left turn; islands by
|
||||
connectivity (including islands made of separate lines, #163). Caps: 60,000 segments, 4,096
|
||||
islands. Gap tolerance (HPGAPTOL) bridges gaps between open curve ends only (`build_gap`). Missing: true arcs and curves in boundaries (boundaries
|
||||
come out tessellated, so a hatched circle's boundary is a polygon), island detection modes
|
||||
beyond the default, boundary sets, and retained associative boundaries for every case. Pattern
|
||||
islands. Gap tolerance (HPGAPTOL) bridges gaps between open curve ends only (`build_gap`). Each
|
||||
traced edge keeps the input polyline it came from, so the circular runs of a loop traced around a
|
||||
point become arcs again with their corners on the exact curves (`engine/src/cmd/hatch/arcs.rs`,
|
||||
#1167): a hatched circle is two half circles and its area is exact. BOUNDARY uses the same tracing,
|
||||
so its polylines keep the arcs too, as AutoCAD's do. Missing: ellipses and splines in traced
|
||||
boundaries (they stay tessellated), island detection modes beyond the default, boundary sets, and
|
||||
retained associative boundaries for every case. Pattern
|
||||
lines are scanline families clipped against the tessellated loops (`render/src/hatch.rs`).
|
||||
|
||||
## Constraint solver (≈ 50%)
|
||||
@@ -150,7 +154,7 @@ coordinates to 1e-9 relative.
|
||||
3. A tolerance context relative to the drawing's extents, and a known-answer test suite at
|
||||
origin and at 1e6–1e7 coordinates. 8–12 h.
|
||||
4. Exact areas and MASSPROP for bulge polylines, regions (2D) and hatch loops. 6–10 h.
|
||||
5. Hatch gap tolerance and curved boundaries. 8–12 h.
|
||||
5. Hatch curved boundaries: ellipses and splines in traced boundaries. 8–12 h.
|
||||
6. ~~Solver: DOF reporting, G2 Smooth, ellipse/spline geometry, constraint inference.~~ Done (#546).
|
||||
7. Spline fit options (end tangents, knot parameterisation, fit tolerance, periodic). 6–10 h.
|
||||
|
||||
@@ -172,3 +176,4 @@ Total ≈ 90–140 h; items 1–6 parallelise across two or three agents.
|
||||
| 2026-10-11 | minor | FILLET with elliptical arcs and splines; trim/extend section 55% → 65% (#466) |
|
||||
| 2026-10-11 | minor | FILLET/CHAMFER with polyline segments (same polyline, end segment with a line); section 65% → 70% (#466) |
|
||||
| 2026-10-11 | minor | Constraint solver (#546): DOF report, G2 Smooth, ellipse/spline/block geometry, CONSTRAINTINFER |
|
||||
| 2026-10-16 | minor | Hatch by internal point keeps exact arcs: circles, arcs and polyline arc segments in traced outer loops and open-curve islands, also after an associative refill (#1167) |
|
||||
Reference in new issue
Block a user