From 2ac6d98dacdb7b899dd03b64ec8294a0c22971fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Sat, 31 Oct 2026 18:32:23 +0100 Subject: [PATCH 1/4] refactor(geom): satisfy Clippy pedantic lints --- crates/geom/src/bounds.rs | 21 +++++-- crates/geom/src/curve.rs | 70 +++++++++++++++++++++- crates/geom/src/fillet.rs | 9 +++ crates/geom/src/intersect.rs | 8 +++ crates/geom/src/lib.rs | 13 ++++- crates/geom/src/mat.rs | 20 +++++++ crates/geom/src/nurbs.rs | 84 ++++++++++++++++++++------ crates/geom/src/property_tests.rs | 16 +++-- crates/geom/src/region.rs | 29 ++++++++- crates/geom/src/spline.rs | 41 +++++++++++-- crates/geom/src/spline/tests.rs | 33 +++++++---- crates/geom/src/spline_fit.rs | 97 +++++++++++++++++++++++-------- crates/geom/src/tests.rs | 6 +- crates/geom/src/vec.rs | 29 +++++++++ 14 files changed, 403 insertions(+), 73 deletions(-) diff --git a/crates/geom/src/bounds.rs b/crates/geom/src/bounds.rs index ba5b7175d..ad7f2549f 100644 --- a/crates/geom/src/bounds.rs +++ b/crates/geom/src/bounds.rs @@ -24,6 +24,7 @@ impl Default for Bounds2 { impl Bounds2 { pub const EMPTY: Bounds2 = Bounds2 { min: Vec2 { x: f64::INFINITY, y: f64::INFINITY }, max: Vec2 { x: f64::NEG_INFINITY, y: f64::NEG_INFINITY } }; + #[must_use] pub fn new(a: Vec2, b: Vec2) -> Self { Bounds2 { min: a.min(b), max: a.max(b) } } @@ -34,6 +35,7 @@ impl Bounds2 { } b } + #[must_use] pub fn is_empty(&self) -> bool { !(self.min.x <= self.max.x && self.min.y <= self.max.y) } @@ -43,6 +45,7 @@ impl Bounds2 { self.max = self.max.max(p); } } + #[must_use] pub fn union(&self, o: &Bounds2) -> Bounds2 { if o.is_empty() { return *self; @@ -52,12 +55,15 @@ impl Bounds2 { } Bounds2 { min: self.min.min(o.min), max: self.max.max(o.max) } } + #[must_use] pub fn width(&self) -> f64 { if self.is_empty() { 0.0 } else { span(self.min.x, self.max.x) } } + #[must_use] pub fn height(&self) -> f64 { if self.is_empty() { 0.0 } else { span(self.min.y, self.max.y) } } + #[must_use] pub fn center(&self) -> Vec2 { if self.is_empty() { return Vec2::ZERO; @@ -65,26 +71,31 @@ impl Bounds2 { // (max - min) can overflow even when both endpoints and their midpoint // are finite. Halve first when the endpoints have opposite signs. let mid = |a: f64, b: f64| { - if a.is_sign_negative() != b.is_sign_negative() { a * 0.5 + b * 0.5 } else { a + (b - a) * 0.5 } + if a.is_sign_negative() == b.is_sign_negative() { a + (b - a) * 0.5 } else { a * 0.5 + b * 0.5 } }; Vec2::new(mid(self.min.x, self.max.x), mid(self.min.y, self.max.y)) } + #[must_use] pub fn contains(&self, p: Vec2) -> bool { p.x >= self.min.x && p.x <= self.max.x && p.y >= self.min.y && p.y <= self.max.y } /// True when `o` lies entirely inside. + #[must_use] pub fn contains_box(&self, o: &Bounds2) -> bool { !o.is_empty() && self.contains(o.min) && self.contains(o.max) } + #[must_use] pub fn intersects(&self, o: &Bounds2) -> bool { !(self.is_empty() || o.is_empty() || o.min.x > self.max.x || o.max.x < self.min.x || o.min.y > self.max.y || o.max.y < self.min.y) } + #[must_use] pub fn expand(&self, d: f64) -> Bounds2 { if self.is_empty() { return *self; } Bounds2 { min: self.min - Vec2::new(d, d), max: self.max + Vec2::new(d, d) } } + #[must_use] pub fn corners(&self) -> [Vec2; 4] { [self.min, Vec2::new(self.max.x, self.min.y), self.max, Vec2::new(self.min.x, self.max.y)] } @@ -101,17 +112,17 @@ mod tests { let b = Bounds2::new(Vec2::new(1e308, 0.0), Vec2::new(1.6e308, 10.0)); assert!(b.center().x.is_finite()); assert!((b.center().x / 1e308 - 1.3).abs() < 1e-12); - assert_eq!(b.center().y, 5.0); + assert_eq!(b.center().y.to_bits(), 5.0_f64.to_bits()); assert_eq!(Bounds2::EMPTY.center(), Vec2::ZERO); } #[test] fn width_and_height_stay_finite_for_opposite_large_coordinates() { let b = Bounds2::new(Vec2::new(-1e308, -1e308), Vec2::new(1e308, 1e308)); - assert_eq!(b.width(), f64::MAX); - assert_eq!(b.height(), f64::MAX); + assert_eq!(b.width().to_bits(), f64::MAX.to_bits()); + assert_eq!(b.height().to_bits(), f64::MAX.to_bits()); let b = Bounds2::new(Vec2::new(1e308, 0.0), Vec2::new(1.6e308, 10.0)); assert!((b.width() / 1e308 - 0.6).abs() < 1e-12); - assert_eq!(b.height(), 10.0); + assert_eq!(b.height().to_bits(), 10.0_f64.to_bits()); } } diff --git a/crates/geom/src/curve.rs b/crates/geom/src/curve.rs index 5d0e53f17..ddda27e82 100644 --- a/crates/geom/src/curve.rs +++ b/crates/geom/src/curve.rs @@ -10,42 +10,53 @@ pub struct Line { } impl Line { + #[must_use] pub fn new(a: Vec2, b: Vec2) -> Self { Line { a, b } } + #[must_use] pub fn len(&self) -> f64 { self.a.dist(self.b) } + #[must_use] pub fn dir(&self) -> Vec2 { (self.b - self.a).normalized() } + #[must_use] pub fn mid(&self) -> Vec2 { self.a.mid(self.b) } /// Parameter (0..1 on the segment) of the projection of `p`. + #[must_use] pub fn param_of(&self, p: Vec2) -> f64 { let d = self.b - self.a; let l2 = d.len2(); if l2 <= EPS * EPS { 0.0 } else { (p - self.a).dot(d) / l2 } } + #[must_use] pub fn at(&self, t: f64) -> Vec2 { self.a.lerp(self.b, t) } /// Closest point on the segment. + #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { self.at(self.param_of(p).clamp(0.0, 1.0)) } /// Foot of the perpendicular on the infinite line. + #[must_use] pub fn project(&self, p: Vec2) -> Vec2 { self.at(self.param_of(p)) } + #[must_use] pub fn dist(&self, p: Vec2) -> f64 { self.closest(p).dist(p) } /// Signed side: > 0 left of a→b. + #[must_use] pub fn side(&self, p: Vec2) -> f64 { (self.b - self.a).cross(p - self.a) } + #[must_use] pub fn offset(&self, d: f64) -> Line { let n = (self.b - self.a).normalized().perp() * d; Line::new(self.a + n, self.b + n) @@ -62,32 +73,41 @@ pub struct Arc { } impl Arc { + #[must_use] pub fn new(center: Vec2, radius: f64, start: f64, end: f64) -> Self { Arc { center, radius: radius.abs(), start: norm_angle(start), end: norm_angle(end) } } + #[must_use] pub fn sweep(&self) -> f64 { ccw_sweep(self.start, self.end) } + #[must_use] pub fn start_point(&self) -> Vec2 { Vec2::polar(self.center, self.radius, self.start) } + #[must_use] pub fn end_point(&self) -> Vec2 { Vec2::polar(self.center, self.radius, self.end) } + #[must_use] pub fn mid_point(&self) -> Vec2 { Vec2::polar(self.center, self.radius, self.start + self.sweep() / 2.0) } + #[must_use] pub fn len(&self) -> f64 { self.radius * self.sweep() } + #[must_use] pub fn contains_angle(&self, a: f64) -> bool { angle_in_sweep(a, self.start, self.end) } /// Point at parameter `t` in 0..1 along the sweep. + #[must_use] pub fn at(&self, t: f64) -> Vec2 { Vec2::polar(self.center, self.radius, self.start + self.sweep() * t) } /// Arc through three points, or `None` when collinear. + #[must_use] pub fn from_3_points(p1: Vec2, p2: Vec2, p3: Vec2) -> Option { let c = Circle::from_3_points(p1, p2, p3)?; let a1 = c.center.angle_to(p1); @@ -97,9 +117,11 @@ impl Arc { if angle_in_sweep(a2, a1, a3) { Some(Arc::new(c.center, c.radius, a1, a3)) } else { Some(Arc::new(c.center, c.radius, a3, a1)) } } /// Arc from start point, center and end point (CCW). + #[must_use] pub fn from_start_center_end(s: Vec2, c: Vec2, e: Vec2) -> Arc { Arc::new(c, s.dist(c), c.angle_to(s), c.angle_to(e)) } + #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { let a = self.center.angle_to(p); if self.contains_angle(a) && p.dist(self.center) > EPS { @@ -110,16 +132,18 @@ impl Arc { if s.dist(p) <= e.dist(p) { s } else { e } } } + #[must_use] pub fn bounds(&self) -> Bounds2 { let mut b = Bounds2::from_points([self.start_point(), self.end_point()]); for k in 0..4 { - let a = k as f64 * PI / 2.0; + let a = f64::from(k) * PI / 2.0; if self.contains_angle(a) { b.add(Vec2::polar(self.center, self.radius, a)); } } b } + #[expect(clippy::cast_precision_loss, reason = "arc_segments caps the sample count at 4096, so every sample index is exact as f64.")] pub fn tessellate(&self, tol: f64, out: &mut Vec) { let sweep = self.sweep(); let n = arc_segments(self.radius, sweep, tol); @@ -137,9 +161,11 @@ pub struct Circle { } impl Circle { + #[must_use] pub fn new(center: Vec2, radius: f64) -> Self { Circle { center, radius: radius.abs() } } + #[must_use] pub fn from_3_points(p1: Vec2, p2: Vec2, p3: Vec2) -> Option { // Work in point-relative coordinates. Absolute coordinate squares lose the small // differences between points in drawings far from the origin. @@ -165,13 +191,16 @@ impl Circle { } Some(Circle::new(c, radius)) } + #[must_use] pub fn from_2_points(p1: Vec2, p2: Vec2) -> Circle { Circle::new(p1.mid(p2), p1.dist(p2) / 2.0) } + #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { let d = p - self.center; if d.len() < EPS { self.center + Vec2::X * self.radius } else { self.center + d.normalized() * self.radius } } + #[must_use] pub fn bounds(&self) -> Bounds2 { Bounds2::new(self.center - Vec2::new(self.radius, self.radius), self.center + Vec2::new(self.radius, self.radius)) } @@ -179,6 +208,7 @@ impl Circle { Arc { center: self.center, radius: self.radius, start: 0.0, end: TAU }.tessellate(tol, out); } /// Tangent points from external point `p`. + #[must_use] pub fn tangent_points(&self, p: Vec2) -> Vec { let d = p.dist(self.center); if d <= self.radius + EPS { @@ -192,6 +222,8 @@ impl Circle { /// up to two outer (belt) tangents and two inner (crossed) tangents. Empty for concentric /// circles or when one circle lies inside the other; tangents that touch both circles at the /// same point (circles touching each other) are left out. + #[must_use] + #[expect(clippy::many_single_char_names, reason = "Circle-tangent equations use conventional r/v/d/u/c/h/n/p/q notation.")] pub fn common_tangents(&self, other: &Circle) -> Vec<(Vec2, Vec2)> { let (r1, r2) = (self.radius, other.radius); let v = other.center - self.center; @@ -232,18 +264,23 @@ pub struct Ellipse { } impl Ellipse { + #[must_use] pub fn full(center: Vec2, major: Vec2, ratio: f64) -> Self { Ellipse { center, major, ratio, start: 0.0, end: TAU } } + #[must_use] pub fn is_full(&self) -> bool { (ccw_sweep(self.start, self.end) - TAU).abs() < 1e-9 } + #[must_use] pub fn minor(&self) -> Vec2 { self.major.perp() * self.ratio } + #[must_use] pub fn at_param(&self, t: f64) -> Vec2 { self.center + self.major * t.cos() + self.minor() * t.sin() } + #[must_use] pub fn sweep(&self) -> f64 { ccw_sweep(self.start, self.end) } @@ -264,6 +301,7 @@ impl Ellipse { let (start, end) = if u.cross(v) >= 0.0 { (self.start - t0, self.end - t0) } else { (t0 - self.end, t0 - self.start) }; Ellipse { center, major: u, ratio, start: norm_angle(start), end: norm_angle(end) } } + #[expect(clippy::cast_precision_loss, reason = "arc_segments caps the sample count at 4096, so every sample index is exact as f64.")] pub fn tessellate(&self, tol: f64, out: &mut Vec) { let r = self.major.len(); let sweep = self.sweep(); @@ -272,6 +310,7 @@ impl Ellipse { out.push(self.at_param(self.start + sweep * i as f64 / n as f64)); } } + #[must_use] pub fn bounds(&self) -> Bounds2 { // Sampled bounds can cut off the true extrema, especially on a small arc or // a large drawing. The derivative of each coordinate gives two exact @@ -286,6 +325,7 @@ impl Ellipse { bounds } /// Parameter of the point on the ellipse nearest the direction of `p` (approximate). + #[must_use] pub fn param_of(&self, p: Vec2) -> f64 { let ma = self.major.len(); if ma < EPS { @@ -298,6 +338,7 @@ impl Ellipse { let mb = ma * self.ratio; norm_angle((y / mb.max(EPS)).atan2(x / ma)) } + #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { let mut pts = Vec::new(); self.tessellate(self.major.len() * 1e-3, &mut pts); @@ -332,6 +373,7 @@ pub enum Segment { } impl Segment { + #[must_use] pub fn start(&self) -> Vec2 { match self { Segment::Line(l) => l.a, @@ -339,6 +381,7 @@ impl Segment { Segment::Arc { arc, ccw: false } => arc.end_point(), } } + #[must_use] pub fn end(&self) -> Vec2 { match self { Segment::Line(l) => l.b, @@ -346,24 +389,28 @@ impl Segment { Segment::Arc { arc, ccw: false } => arc.start_point(), } } + #[must_use] pub fn len(&self) -> f64 { match self { Segment::Line(l) => l.len(), Segment::Arc { arc, .. } => arc.len(), } } + #[must_use] pub fn mid(&self) -> Vec2 { match self { Segment::Line(l) => l.mid(), Segment::Arc { arc, .. } => arc.mid_point(), } } + #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { match self { Segment::Line(l) => l.closest(p), Segment::Arc { arc, .. } => arc.closest(p), } } + #[must_use] pub fn bounds(&self) -> Bounds2 { match self { Segment::Line(l) => Bounds2::new(l.a, l.b), @@ -381,12 +428,13 @@ impl Segment { let start = out.len(); arc.tessellate(tol, out); if !ccw && let Some(s) = out.get_mut(start..) { - s.reverse() + s.reverse(); } } } } /// Point at parameter `t` (0..1) in segment direction. + #[must_use] pub fn at(&self, t: f64) -> Vec2 { match self { Segment::Line(l) => l.at(t), @@ -394,6 +442,7 @@ impl Segment { Segment::Arc { arc, ccw: false } => arc.at(1.0 - t), } } + #[must_use] pub fn reversed(&self) -> Segment { match *self { Segment::Line(l) => Segment::Line(Line::new(l.b, l.a)), @@ -401,6 +450,7 @@ impl Segment { } } /// Tangent direction (unit) at parameter t. + #[must_use] pub fn tangent(&self, t: f64) -> Vec2 { match self { Segment::Line(l) => l.dir(), @@ -412,6 +462,7 @@ impl Segment { } } /// Offset by `d` to the left of travel direction. `None` if an arc collapses. + #[must_use] pub fn offset(&self, d: f64) -> Option { match *self { Segment::Line(l) => Some(Segment::Line(l.offset(d))), @@ -440,15 +491,18 @@ pub struct PolyVertex { } impl PolyVertex { + #[must_use] pub fn new(p: Vec2) -> Self { PolyVertex { p, ..Default::default() } } + #[must_use] pub fn with_bulge(p: Vec2, bulge: f64) -> Self { PolyVertex { p, bulge, ..Default::default() } } } /// Convert a bulge segment to an arc. `None` for a straight (zero-bulge or degenerate) segment. +#[must_use] pub fn bulge_to_arc(a: Vec2, b: Vec2, bulge: f64) -> Option<(Arc, bool)> { if bulge.abs() < 1e-12 || !bulge.is_finite() || a.near(b, EPS) { return None; @@ -473,6 +527,7 @@ pub fn bulge_to_arc(a: Vec2, b: Vec2, bulge: f64) -> Option<(Arc, bool)> { } /// Bulge for an arc traversed from `a` to `b` with the given sweep (signed: + = CCW). +#[must_use] pub fn arc_to_bulge(signed_sweep: f64) -> f64 { (signed_sweep / 4.0).tan() } @@ -488,10 +543,12 @@ pub struct Polyline { pub const MAX_TESSELLATED_POINTS: usize = 4_000_000; impl Polyline { + #[must_use] pub fn from_points(pts: &[Vec2], closed: bool) -> Self { Polyline { vertices: pts.iter().map(|p| PolyVertex::new(*p)).collect(), closed } } /// The segments, including the closing segment when closed. + #[must_use] pub fn segments(&self) -> Vec { let n = self.vertices.len(); let mut out = Vec::with_capacity(n); @@ -511,6 +568,7 @@ impl Polyline { pub fn len(&self) -> f64 { self.segments().iter().map(Segment::len).sum() } + #[must_use] pub fn bounds(&self) -> Bounds2 { let mut b = Bounds2::from_points(self.vertices.iter().map(|v| v.p)); for s in self.segments() { @@ -518,6 +576,7 @@ impl Polyline { } b } + #[must_use] pub fn tessellate(&self, tol: f64) -> Vec { let mut budget = MAX_TESSELLATED_POINTS; self.tessellate_within(tol, &mut budget) @@ -546,6 +605,7 @@ impl Polyline { out } /// Signed area (CCW positive) of a closed polyline including bulge areas. + #[must_use] pub fn area(&self) -> f64 { // Integrate the chords exactly and add the signed circular-segment area // for every bulge. A tessellated shoelace loses precision on large arcs. @@ -573,6 +633,7 @@ impl Polyline { } twice_area / 2.0 } + #[must_use] pub fn closest(&self, p: Vec2) -> Option { let mut best: Option<(f64, Vec2)> = None; for s in self.segments() { @@ -585,11 +646,13 @@ impl Polyline { best.map(|(_, c)| c).or_else(|| self.vertices.first().map(|v| v.p)) } /// True if `p` is inside a closed polyline (even-odd on the tessellation). + #[must_use] pub fn contains(&self, p: Vec2) -> bool { point_in_polygon(&self.tessellate(1e-3), p) } /// Area centroid of the closed polyline, exact with bulges: the chord triangles fanned from the /// first vertex plus each bulge's circular segment, weighted by signed area. `None` at zero area. + #[expect(clippy::many_single_char_names, reason = "Centroid integration uses conventional a/b/c/d/t area and point notation.")] pub fn centroid(&self) -> Option { let origin = self.vertices.first()?.p; let n = self.vertices.len(); @@ -622,11 +685,13 @@ impl Polyline { } /// Area centroid of a closed polygon. `None` at zero area. +#[must_use] pub fn polygon_centroid(pts: &[Vec2]) -> Option { Polyline::from_points(pts, true).centroid() } /// Signed polygon area (CCW positive). +#[must_use] pub fn shoelace(pts: &[Vec2]) -> f64 { let n = pts.len(); if n < 3 { @@ -647,6 +712,7 @@ pub fn shoelace(pts: &[Vec2]) -> f64 { } /// Even-odd point-in-polygon test. +#[must_use] pub fn point_in_polygon(poly: &[Vec2], p: Vec2) -> bool { let n = poly.len(); if n < 3 { diff --git a/crates/geom/src/fillet.rs b/crates/geom/src/fillet.rs index 78e1fc93b..74b06385b 100644 --- a/crates/geom/src/fillet.rs +++ b/crates/geom/src/fillet.rs @@ -49,6 +49,7 @@ struct Range { impl TanCurve { /// Point at parameter `t`. + #[must_use] pub fn point(&self, t: f64) -> Vec2 { match self { TanCurve::Line(l) => l.a + (l.b - l.a) * t, @@ -59,6 +60,7 @@ impl TanCurve { } /// First derivative at parameter `t`. + #[must_use] pub fn derivative(&self, t: f64) -> Vec2 { match self { TanCurve::Line(l) => l.b - l.a, @@ -69,6 +71,7 @@ impl TanCurve { } /// The point at distance `d` along the left normal at `t` (`None` where the curve stops). + #[expect(clippy::many_single_char_names, reason = "The offset equation uses conventional t/d/p/n/q geometric notation.")] fn offset(&self, t: f64, d: f64) -> Option { let p = self.point(t); if d == 0.0 { @@ -125,6 +128,11 @@ impl TanCurve { } /// A sampled offset curve: runs of consecutive (parameter, point) samples. +#[expect( + clippy::cast_precision_loss, + clippy::many_single_char_names, + reason = "Sample counts are capped by MAX_SPLINE_SAMPLES, and c/r/d/i/t/p name the curve, range, offset and sample equations." +)] fn sample(c: &TanCurve, r: &Range, d: f64) -> Vec> { let n = c.sample_count(); let mut runs: Vec> = vec![Vec::new()]; @@ -232,6 +240,7 @@ fn refine(c1: &TanCurve, r1: &Range, d1: f64, c2: &TanCurve, r2: &Range, d2: f64 /// Circles of radius `r` tangent to both curves (`r = 0`: the points where they cross). `near` /// (the pick points) widens the search window for lines. Every distinct solution is returned; /// callers choose one, usually the nearest the picks. +#[must_use] pub fn tangent_circles(c1: &TanCurve, c2: &TanCurve, r: f64, near: &[Vec2]) -> Vec { if !(r.is_finite() && r >= 0.0) { return Vec::new(); diff --git a/crates/geom/src/intersect.rs b/crates/geom/src/intersect.rs index 653cd61c9..4e7714b6e 100644 --- a/crates/geom/src/intersect.rs +++ b/crates/geom/src/intersect.rs @@ -1,6 +1,7 @@ use crate::{Arc, Circle, EPS, Line, Segment, Vec2}; /// Intersection of two infinite lines through (a1,a2) and (b1,b2), with parameters on each. +#[must_use] pub fn line_line_infinite(a1: Vec2, a2: Vec2, b1: Vec2, b2: Vec2) -> Option<(Vec2, f64, f64)> { let r = a2 - a1; let s = b2 - b1; @@ -14,6 +15,8 @@ pub fn line_line_infinite(a1: Vec2, a2: Vec2, b1: Vec2, b2: Vec2) -> Option<(Vec } /// Intersection of two finite segments. +#[must_use] +#[expect(clippy::many_single_char_names, reason = "Segment endpoints and parameters use conventional a/b/p/t/u geometric notation.")] pub fn line_line(a: &Line, b: &Line) -> Option { let (p, t, u) = line_line_infinite(a.a, a.b, b.a, b.b)?; let tol = 1e-9; @@ -21,6 +24,8 @@ pub fn line_line(a: &Line, b: &Line) -> Option { } /// Intersections of the infinite line through `l` with a circle. Returns points with line params. +#[must_use] +#[expect(clippy::many_single_char_names, reason = "The line/circle quadratic uses conventional a/d/f/t mathematical notation.")] pub fn line_circle(l: &Line, c: &Circle) -> Vec<(Vec2, f64)> { let d = l.b - l.a; let f = l.a - c.center; @@ -52,6 +57,7 @@ pub fn line_circle(l: &Line, c: &Circle) -> Vec<(Vec2, f64)> { } /// Intersections of two full circles. +#[must_use] pub fn circle_circle(c1: &Circle, c2: &Circle) -> Vec { let delta = c2.center - c1.center; let d = delta.len(); @@ -101,12 +107,14 @@ fn on_arc(a: &Arc, p: Vec2) -> bool { } /// Intersections between two segments (finite). +#[must_use] pub fn intersect_segments(s1: &Segment, s2: &Segment) -> Vec { intersect_segments_ext(s1, s2, false) } /// Intersections; with `extend` true, lines are infinite and arcs are full circles /// (used by TRIM/EXTEND edge mode and apparent intersections). +#[must_use] pub fn intersect_segments_ext(s1: &Segment, s2: &Segment, extend: bool) -> Vec { let tol = 1e-9; match (s1, s2) { diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index d482141fd..40b47d6d5 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -1,4 +1,4 @@ -//! CADCraft geometry: double-precision 2D/3D math for drafting. +//! `CADCraft` geometry: double-precision 2D/3D math for drafting. //! //! Everything a CAD kernel needs below the document model: vectors and affine transforms, //! bounding boxes, angles, lines, circular arcs (and polyline bulges), ellipses, NURBS splines, @@ -36,6 +36,7 @@ pub const TAU: f64 = std::f64::consts::TAU; pub const PI: f64 = std::f64::consts::PI; /// Normalize an angle to `[0, 2π)`. +#[must_use] pub fn norm_angle(a: f64) -> f64 { if !a.is_finite() { return 0.0; @@ -45,26 +46,36 @@ pub fn norm_angle(a: f64) -> f64 { } /// Counter-clockwise sweep from `start` to `end`, in `(0, 2π]`. +#[must_use] pub fn ccw_sweep(start: f64, end: f64) -> f64 { let s = norm_angle(end - start); if s <= EPS { TAU } else { s } } /// True when angle `a` lies on the CCW sweep from `start` to `end` (inclusive, with tolerance). +#[must_use] pub fn angle_in_sweep(a: f64, start: f64, end: f64) -> bool { let sweep = ccw_sweep(start, end); let d = norm_angle(a - start); d <= sweep + 1e-12 || (TAU - d) < 1e-12 } +#[must_use] pub fn deg(r: f64) -> f64 { r.to_degrees() } +#[must_use] pub fn rad(d: f64) -> f64 { d.to_radians() } /// Number of segments needed to approximate an arc of `radius` and `sweep` within `tol`. +#[must_use] +#[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "The segment count is nonnegative and immediately clamped to 1..=4096; float-to-usize saturation handles out-of-range values." +)] pub fn arc_segments(radius: f64, sweep: f64, tol: f64) -> usize { let r = radius.abs(); if !(r.is_finite() && sweep.is_finite()) || r <= EPS { diff --git a/crates/geom/src/mat.rs b/crates/geom/src/mat.rs index 5f28b068d..ec7a2075b 100644 --- a/crates/geom/src/mat.rs +++ b/crates/geom/src/mat.rs @@ -22,24 +22,30 @@ impl Default for Mat3 { impl Mat3 { pub const IDENTITY: Mat3 = Mat3 { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0 }; + #[must_use] pub fn translate(v: Vec2) -> Mat3 { Mat3 { e: v.x, f: v.y, ..Mat3::IDENTITY } } + #[must_use] pub fn scale(sx: f64, sy: f64) -> Mat3 { Mat3 { a: sx, d: sy, ..Mat3::IDENTITY } } + #[must_use] pub fn rotate(angle: f64) -> Mat3 { let (s, c) = angle.sin_cos(); Mat3 { a: c, b: s, c: -s, d: c, e: 0.0, f: 0.0 } } /// Scale about `base`. + #[must_use] pub fn scale_about(base: Vec2, s: f64) -> Mat3 { Mat3::translate(base).then_before(Mat3::scale(s, s)).then_before(Mat3::translate(-base)) } + #[must_use] pub fn rotate_about(base: Vec2, angle: f64) -> Mat3 { Mat3::translate(base).then_before(Mat3::rotate(angle)).then_before(Mat3::translate(-base)) } /// Reflection across the line through `p1`, `p2`. + #[must_use] pub fn mirror(p1: Vec2, p2: Vec2) -> Mat3 { let d = (p2 - p1).normalized(); if d == Vec2::ZERO { @@ -50,6 +56,7 @@ impl Mat3 { Mat3::translate(p1).then_before(r).then_before(Mat3::translate(-p1)) } /// `self * o`: apply `o` first, then `self`. + #[must_use] pub fn then_before(self, o: Mat3) -> Mat3 { Mat3 { a: self.a * o.a + self.c * o.b, @@ -61,18 +68,24 @@ impl Mat3 { } } /// Apply `self` first, then `o`. + #[must_use] pub fn then(self, o: Mat3) -> Mat3 { o.then_before(self) } + #[must_use] pub fn apply(&self, p: Vec2) -> Vec2 { Vec2::new(self.a * p.x + self.c * p.y + self.e, self.b * p.x + self.d * p.y + self.f) } + #[must_use] pub fn apply_vec(&self, v: Vec2) -> Vec2 { Vec2::new(self.a * v.x + self.c * v.y, self.b * v.x + self.d * v.y) } + #[must_use] pub fn det(&self) -> f64 { self.a * self.d - self.b * self.c } + #[must_use] + #[expect(clippy::many_single_char_names, reason = "Matrix coefficients use the same a–f notation as Mat3 and the affine-transform formula.")] pub fn inverse(&self) -> Option { let det = self.det(); if det.abs() < 1e-300 || !det.is_finite() { @@ -88,13 +101,16 @@ impl Mat3 { Some(Mat3 { a, b, c, d, e, f }) } /// Uniform scale factor (geometric mean of the axis scales). + #[must_use] pub fn scale_factor(&self) -> f64 { self.det().abs().sqrt() } /// Rotation angle of the transformed X axis. + #[must_use] pub fn rotation(&self) -> f64 { crate::norm_angle(self.b.atan2(self.a)) } + #[must_use] pub fn is_mirroring(&self) -> bool { self.det() < 0.0 } @@ -122,6 +138,7 @@ impl Default for Mat4 { impl Mat4 { pub const IDENTITY: Mat4 = Mat4 { m: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] }; + #[must_use] pub fn mul(&self, o: &Mat4) -> Mat4 { let mut r = [[0.0; 4]; 4]; for (i, row) in r.iter_mut().enumerate() { @@ -131,6 +148,7 @@ impl Mat4 { } Mat4 { m: r } } + #[must_use] pub fn apply(&self, p: Vec3) -> Vec3 { let m = &self.m; let w = m[3][0] * p.x + m[3][1] * p.y + m[3][2] * p.z + m[3][3]; @@ -141,10 +159,12 @@ impl Mat4 { (m[2][0] * p.x + m[2][1] * p.y + m[2][2] * p.z + m[2][3]) / w, ) } + #[must_use] pub fn from_mat3(t: &Mat3) -> Mat4 { Mat4 { m: [[t.a, t.c, 0.0, t.e], [t.b, t.d, 0.0, t.f], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] } } /// The "arbitrary axis algorithm" frame for an extrusion direction (DXF OCS → WCS). + #[must_use] pub fn ocs(normal: Vec3) -> Mat4 { let n = normal.normalized(); if n == Vec3::ZERO || (n.x.abs() < 1e-12 && n.y.abs() < 1e-12 && n.z > 0.0) { diff --git a/crates/geom/src/nurbs.rs b/crates/geom/src/nurbs.rs index 04cf933cb..2c8e070f5 100644 --- a/crates/geom/src/nurbs.rs +++ b/crates/geom/src/nurbs.rs @@ -44,8 +44,9 @@ const GAUSS: [(f64, f64); 5] = [ (0.906_179_845_938_664, 0.236_926_885_056_189_1), ]; +#[expect(clippy::many_single_char_names, reason = "Gauss–Legendre quadrature uses conventional a/b/f/m/h/x/w notation.")] fn gauss(a: f64, b: f64, f: impl Fn(f64) -> f64) -> f64 { - let (m, h) = ((a + b) / 2.0, (b - a) / 2.0); + let (m, h) = (f64::midpoint(a, b), (b - a) / 2.0); GAUSS.iter().map(|(x, w)| w * f(m + h * x)).sum::() * h } @@ -55,8 +56,12 @@ const MAX_GAUSS_DEPTH: usize = 10; /// `gauss` over [a, b], halving until the two halves agree with the whole: a fixed panel count /// is far off on a tight bend, and the arc-length inverse must agree with the measure. +#[expect( + clippy::many_single_char_names, + reason = "Adaptive quadrature keeps the panel endpoints, midpoint and left/right integrals in mathematical notation." +)] fn adaptive_gauss(a: f64, b: f64, whole: f64, f: &impl Fn(f64) -> f64, depth: usize) -> f64 { - let m = (a + b) / 2.0; + let m = f64::midpoint(a, b); let (l, r) = (gauss(a, m, f), gauss(m, b, f)); if depth == 0 || !(l + r).is_finite() || (l + r - whole).abs() <= 1e-10 * (l + r).abs() { return l + r; @@ -76,6 +81,7 @@ fn bezier_knots(breaks: &[f64], p: usize) -> Vec { } /// One degree elevation of a homogeneous Bézier piece. +#[expect(clippy::cast_precision_loss, reason = "Bézier pieces are bounded by MAX_EDIT_DEGREE, so their control indices are exact as f64.")] fn elevate_bezier(p: &[H]) -> Vec { let n = p.len(); let zero = (Vec2::ZERO, 0.0); @@ -122,6 +128,7 @@ impl Spline { } /// True when the spline carries weights (a NURBS rather than a plain B-spline). + #[must_use] pub fn is_rational(&self) -> bool { !self.weights.is_empty() } @@ -148,6 +155,7 @@ impl Spline { } /// First derivative dC/dt (zero on an invalid spline). + #[must_use] pub fn derivative(&self, t: f64) -> Vec2 { if !self.is_valid() { return Vec2::ZERO; @@ -208,6 +216,7 @@ impl Spline { /// Unit tangent at `t` in the direction of increasing parameter; a central difference stands /// in where the derivative vanishes. Zero when the curve does not move at all. + #[must_use] pub fn unit_tangent(&self, t: f64) -> Vec2 { let d = self.derivative(t).normalized(); if d != Vec2::ZERO { @@ -220,6 +229,8 @@ impl Spline { /// Insert knot `t` once (Boehm's algorithm, in homogeneous coordinates). The result has no /// fit data and is open. + #[must_use] + #[expect(clippy::many_single_char_names, reason = "Boehm knot insertion keeps the standard p/n/k/i/h/a equation notation.")] pub fn insert_knot(&self, t: f64) -> Option { if !self.is_valid() || !t.is_finite() || self.control.len() >= MAX_EDIT_CONTROL { return None; @@ -287,6 +298,7 @@ impl Spline { } /// Split at parameter `t` into (before, after). `None` at the ends or on invalid input. + #[must_use] pub fn split_at(&self, t: f64) -> Option<(Spline, Spline)> { let (lo, hi) = self.domain(); if !(t > lo + 1e-12 && t < hi - 1e-12) { @@ -297,6 +309,7 @@ impl Spline { } /// The open piece between parameters `a < b`. + #[must_use] pub fn sub_between(&self, a: f64, b: f64) -> Option { let (lo, hi) = self.domain(); let mut s = self.clone(); @@ -313,6 +326,7 @@ impl Spline { /// The same curve with clamped ends (end knots repeated degree + 1 times), so it starts and /// ends on its first and last control points. Fit data is dropped. + #[must_use] pub fn clamped(&self) -> Option { if !self.is_valid() { return None; @@ -321,7 +335,7 @@ impl Spline { let (lo, hi) = self.domain(); let mut s = self.clone(); s.fit.clear(); - s.fit_opts = Default::default(); + s.fit_opts = crate::FitOptions::default(); if !s.knots.get(..=p).is_some_and(|k| k.iter().all(|x| (*x - lo).abs() < 1e-12)) { s = s.split_raw(lo)?.1; } @@ -335,6 +349,7 @@ impl Spline { /// Reversed direction: control points, weights, fit points and knots (and the fit end /// tangents swap ends and turn round). + #[must_use] pub fn reversed(&self) -> Spline { let (lo, hi) = (self.knots.first().copied().unwrap_or(0.0), self.knots.last().copied().unwrap_or(1.0)); Spline { @@ -387,6 +402,7 @@ impl Spline { } /// The same curve at a higher (or equal) degree, clamped. + #[must_use] pub fn elevated(&self, degree: usize) -> Option { if degree < self.degree || degree > MAX_EDIT_DEGREE { return None; @@ -412,6 +428,11 @@ impl Spline { /// point becomes their midpoint). Degrees are matched by elevation, weights rescaled so the /// junction carries one weight, and `other`'s parameters follow on at a similar speed. The /// junction is a knot of multiplicity `degree`, so the curve passes through it exactly. + #[must_use] + #[expect( + clippy::many_single_char_names, + reason = "Spline joining keeps the two curves, homogeneous points and knot spans in standard short notation." + )] pub fn joined(&self, other: &Spline) -> Option { let deg = self.degree.max(other.degree); let a = self.elevated(deg)?; @@ -440,6 +461,8 @@ impl Spline { /// A straight line from `a` to `b` as a clamped spline of `degree` (evenly spaced control /// points, parameter = distance). + #[must_use] + #[expect(clippy::cast_precision_loss, reason = "The degree is clamped by MAX_EDIT_DEGREE (25), so every control index is exact as f64.")] pub fn from_line(a: Vec2, b: Vec2, degree: usize) -> Spline { let p = degree.clamp(1, MAX_EDIT_DEGREE); let control = (0..=p).map(|i| a.lerp(b, i as f64 / p as f64)).collect(); @@ -453,6 +476,14 @@ impl Spline { /// The elliptical arc `center + u·cos θ + v·sin θ` for θ from `start` over `sweep` (negative /// runs clockwise) as an exact rational quadratic spline, in pieces of at most a quarter /// turn. Circular arcs are the case `|u| = |v|`, `u ⟂ v`. + #[must_use] + #[expect( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + clippy::many_single_char_names, + reason = "Conic decomposition uses one to four pieces and standard parametric notation, so all piece indices are exact as f64." + )] pub fn from_conic_arc(center: Vec2, u: Vec2, v: Vec2, start: f64, sweep: f64) -> Option { if !(start.is_finite() && sweep.is_finite() && center.is_finite() && u.is_finite() && v.is_finite()) || sweep.abs() < 1e-12 @@ -482,6 +513,7 @@ impl Spline { } /// An ellipse or elliptical arc as an exact rational spline (counter-clockwise). + #[must_use] pub fn from_ellipse(e: &Ellipse) -> Option { let s = Spline::from_conic_arc(e.center, e.major, e.minor(), e.start, e.sweep())?; Some(Spline { closed: e.is_full(), ..s }) @@ -489,6 +521,7 @@ impl Spline { /// Run the spline on in a straight line along its end tangent by `dist` > 0: past the end /// (`at_end`) or before the start. The result is clamped, open and has no fit data. + #[must_use] pub fn extended(&self, at_end: bool, dist: f64) -> Option { if !(dist.is_finite() && dist > 0.0) || self.closed { return None; @@ -515,7 +548,7 @@ impl Spline { for w in cuts.windows(2) { let (Some(&x0), Some(&x1)) = (w.first(), w.get(1)) else { continue }; for i in 0..4 { - out.push((x0 + (x1 - x0) * i as f64 / 4.0, x0 + (x1 - x0) * (i + 1) as f64 / 4.0)); + out.push((x0 + (x1 - x0) * f64::from(i) / 4.0, x0 + (x1 - x0) * f64::from(i + 1) / 4.0)); } } out @@ -531,12 +564,14 @@ impl Spline { } /// Arc length between parameters `a` and `b` (adaptive Gauss–Legendre over each knot span). + #[must_use] pub fn length_between(&self, a: f64, b: f64) -> f64 { let l = self.integrated_length(a, b); if l.is_finite() { l } else { 0.0 } } /// Arc length of the whole spline. + #[must_use] pub fn length(&self) -> f64 { let (lo, hi) = self.domain(); self.length_between(lo, hi) @@ -563,6 +598,7 @@ impl Spline { /// The parameter `len` along the curve from parameter `from` (forward for positive `len`, /// backward for negative), clamped to the domain. + #[must_use] pub fn param_at_length(&self, from: f64, len: f64) -> f64 { let (lo, hi) = self.domain(); if !self.is_valid() { @@ -587,7 +623,7 @@ impl Spline { let (near, far) = if len > 0.0 { (x0, x1) } else { (x1, x0) }; let (mut s0, mut s1) = (near, far); for _ in 0..60 { - let m = (s0 + s1) / 2.0; + let m = f64::midpoint(s0, s1); let lm = self.panel_length(near.min(m), near.max(m), Spline::derivative_unchecked); if lm < rest { s0 = m; @@ -595,7 +631,7 @@ impl Spline { s1 = m; } } - return (s0 + s1) / 2.0; + return f64::midpoint(s0, s1); } acc += l; } @@ -605,11 +641,19 @@ impl Spline { impl Ellipse { /// dP/dθ at parameter `t`. + #[must_use] pub fn derivative(&self, t: f64) -> Vec2 { self.minor() * t.cos() - self.major * t.sin() } /// Arc length from parameter `t0` counter-clockwise over `sweep` (radians, >= 0). + #[must_use] + #[expect( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "The quadrature panel count is clamped to 1..=512, so panel indices are nonnegative and exact as f64." + )] pub fn arc_length_from(&self, t0: f64, sweep: f64) -> f64 { if !(t0.is_finite() && sweep.is_finite()) || sweep <= 0.0 { return 0.0; @@ -628,12 +672,14 @@ impl Ellipse { } /// Arc length of the ellipse or elliptical arc. + #[must_use] pub fn length(&self) -> f64 { self.arc_length_from(self.start, self.sweep()) } /// The parameter reached `len` along the ellipse from `t0`: counter-clockwise for positive /// `len`, clockwise for negative. `None` for a whole turn or more, or degenerate input. + #[must_use] pub fn param_at_length(&self, t0: f64, len: f64) -> Option { let full = self.arc_length_from(0.0, TAU); if !(t0.is_finite() && len.is_finite() && full > EPS) || len.abs() >= full { @@ -643,14 +689,14 @@ impl Ellipse { let along = |s: f64| if len >= 0.0 { self.arc_length_from(t0, s) } else { self.arc_length_from(t0 - s, s) }; let (mut a, mut b) = (0.0, TAU); for _ in 0..80 { - let m = (a + b) / 2.0; + let m = f64::midpoint(a, b); if along(m) < target { a = m; } else { b = m; } } - let s = (a + b) / 2.0; + let s = f64::midpoint(a, b); Some(if len >= 0.0 { t0 + s } else { t0 - s }) } } @@ -795,7 +841,7 @@ mod tests { s.weights = vec![1.0, 2.0, 0.5, 1.0, 1.5]; let (lo, hi) = s.domain(); for i in 1..20 { - let t = lo + (hi - lo) * i as f64 / 20.0; + let t = lo + (hi - lo) * f64::from(i) / 20.0; let h = 1e-6; let fd = (s.eval(t + h) - s.eval(t - h)) / (2.0 * h); assert!(s.derivative(t).near(fd, 1e-4), "{t}: {:?} vs {fd:?}", s.derivative(t)); @@ -825,7 +871,7 @@ mod tests { assert!(!c.is_periodic()); let ((plo, phi), (clo, chi)) = (p.domain(), c.domain()); for i in 0..=20 { - let f = i as f64 / 20.0; + let f = f64::from(i) / 20.0; assert!(p.eval(plo + (phi - plo) * f).near(c.eval(clo + (chi - clo) * f), 1e-9)); } assert!(c.control.first().unwrap().near(p.eval(plo), 1e-9)); @@ -837,7 +883,7 @@ mod tests { let e = s.elevated(5).unwrap(); assert_eq!(e.degree, 5); for i in 0..=20 { - let t = i as f64 / 20.0; + let t = f64::from(i) / 20.0; assert!(e.eval(t).near(s.eval(t), 1e-9), "{t}"); } // A rational quarter circle elevated to a cubic stays on the circle. @@ -845,12 +891,13 @@ mod tests { let q3 = q.elevated(3).unwrap(); let (lo, hi) = q3.domain(); for i in 0..=20 { - assert!((q3.eval(lo + (hi - lo) * i as f64 / 20.0).len() - 2.0).abs() < 1e-9); + assert!((q3.eval(lo + (hi - lo) * f64::from(i) / 20.0).len() - 2.0).abs() < 1e-9); } assert!(s.elevated(2).is_none() && s.elevated(1000).is_none()); } #[test] + #[expect(clippy::many_single_char_names, reason = "The ellipse equation check keeps conventional center/axis/point notation.")] fn conic_arcs_are_exact() { let e = Ellipse { center: Vec2::new(1.0, 2.0), major: Vec2::new(4.0, 3.0), ratio: 0.5, start: 0.3, end: 5.5 }; let s = Spline::from_ellipse(&e).unwrap(); @@ -860,7 +907,7 @@ mod tests { let (a, b) = (e.major.len(), e.major.len() * e.ratio); let ux = e.major.normalized(); for i in 0..=40 { - let p = s.eval(lo + (hi - lo) * i as f64 / 40.0) - e.center; + let p = s.eval(lo + (hi - lo) * f64::from(i) / 40.0) - e.center; let (x, y) = (p.dot(ux), p.dot(ux.perp())); assert!(((x / a).powi(2) + (y / b).powi(2) - 1.0).abs() < 1e-9); } @@ -881,8 +928,8 @@ mod tests { assert!(j.eval(lo).near(Vec2::new(-5.0, 0.0), 1e-12) && j.eval(hi).near(Vec2::new(12.0, 2.0), 1e-12)); // The line part is straight (parameter = distance), the spline part unchanged. for i in 0..=10 { - assert!(j.eval(lo + 0.5 * i as f64).near(Vec2::new(-5.0 + 0.5 * i as f64, 0.0), 1e-12)); - let f = i as f64 / 10.0; + assert!(j.eval(lo + 0.5 * f64::from(i)).near(Vec2::new(-5.0 + 0.5 * f64::from(i), 0.0), 1e-12)); + let f = f64::from(i) / 10.0; assert!(j.eval(5.0 + (hi - 5.0) * f).near(s.eval(f), 1e-9)); } assert!((j.length() - (5.0 + s.length())).abs() < 1e-6); @@ -917,7 +964,7 @@ mod tests { assert!(q.eval(t).near(Vec2::new(0.0, 2.0), 1e-6)); let t = q.param_at_length(hi, -std::f64::consts::PI / 2.0); assert!(q.eval(t).near(Vec2::new(-2f64.sqrt(), 2f64.sqrt()), 1e-6)); - assert_eq!(q.param_at_length(lo, 1e9), hi); + assert_eq!(q.param_at_length(lo, 1e9).to_bits(), hi.to_bits()); } #[test] @@ -966,12 +1013,13 @@ mod tests { nan.knots[nan.degree] = f64::NAN; assert!(!nan.is_valid() && nan.domain().0.is_nan()); for s in [reversed, nan] { - assert_eq!(s.param_at_length(0.5, 1.0), 0.5); - assert_eq!(s.param_at_length(0.5, -1.0), 0.5); + assert_eq!(s.param_at_length(0.5, 1.0).to_bits(), 0.5_f64.to_bits()); + assert_eq!(s.param_at_length(0.5, -1.0).to_bits(), 0.5_f64.to_bits()); } } #[test] + #[expect(clippy::many_single_char_names, reason = "The ellipse arc-length reference uses conventional a/b/h/t notation.")] fn ellipse_arc_length() { let c = Ellipse::full(Vec2::ZERO, Vec2::new(3.0, 0.0), 1.0); assert!((c.length() - TAU * 3.0).abs() < 1e-9); diff --git a/crates/geom/src/property_tests.rs b/crates/geom/src/property_tests.rs index 0584c9109..27299d641 100644 --- a/crates/geom/src/property_tests.rs +++ b/crates/geom/src/property_tests.rs @@ -22,13 +22,15 @@ impl Rng { x ^= x << 25; x ^= x >> 27; self.0 = x; - x.wrapping_mul(0x2545F4914F6CDD1D) + x.wrapping_mul(0x2545_F491_4F6C_DD1D) } /// Uniform in `[-scale, scale]`. + #[expect(clippy::cast_precision_loss, reason = "The generator keeps exactly 53 random bits, and 2^53 is exactly representable as f64.")] fn f64(&mut self, scale: f64) -> f64 { ((self.next() >> 11) as f64 / (1u64 << 53) as f64) * 2.0 * scale - scale } /// Uniform in `[lo, hi]`. + #[expect(clippy::cast_precision_loss, reason = "The generator keeps exactly 53 random bits, and 2^53 is exactly representable as f64.")] fn range(&mut self, lo: f64, hi: f64) -> f64 { lo + (hi - lo) * (self.next() >> 11) as f64 / (1u64 << 53) as f64 } @@ -96,7 +98,7 @@ fn on_line(p: Vec2, a: Vec2, d: Vec2, rel: f64) -> bool { /// The infinite-line intersection lies on both lines, and swapping the lines gives the same point. #[test] fn line_line_infinite_lies_on_both_and_is_symmetric() { - let mut r = Rng::new(0xC0FFEE); + let mut r = Rng::new(0xC0_FFEE); let mut checked = 0; for _ in 0..4000 { let (a1, a2, b1, b2) = (r.vec(1000.0), r.vec(1000.0), r.vec(1000.0), r.vec(1000.0)); @@ -115,8 +117,9 @@ fn line_line_infinite_lies_on_both_and_is_symmetric() { /// The finite-line result agrees with the parameters of the infinite one. #[test] +#[expect(clippy::many_single_char_names, reason = "The property uses the same a/b/p/t/u notation as the geometric equations under test.")] fn line_line_matches_infinite_parameters() { - let mut r = Rng::new(0xBAD5EED); + let mut r = Rng::new(0xBAD_5EED); for _ in 0..4000 { let a = Line::new(r.vec(100.0), r.vec(100.0)); let b = Line::new(r.vec(100.0), r.vec(100.0)); @@ -220,7 +223,7 @@ fn circle_circle_hits_lie_on_both_and_match_the_closed_form() { /// Degenerate and hostile circles: concentric, contained, negative/NaN radii, extreme centres. #[test] fn circle_circle_degenerate_and_hostile_never_panic() { - let mut r = Rng::new(0xD15EA5E); + let mut r = Rng::new(0xD15_EA5E); for _ in 0..3000 { let c1 = Circle { center: Vec2::new(r.hostile(), r.hostile()), radius: r.hostile() }; let c2 = Circle { center: Vec2::new(r.hostile(), r.hostile()), radius: r.hostile() }; @@ -240,7 +243,7 @@ fn circle_circle_degenerate_and_hostile_never_panic() { /// Extending segments only adds hits: the finite result is a subset of the extended one. #[test] fn segment_extension_only_adds_hits() { - let mut r = Rng::new(0x5E6C0DE); + let mut r = Rng::new(0x5E6_C0DE); for _ in 0..3000 { let s1 = Segment::Line(Line::new(r.vec(100.0), r.vec(100.0))); let s2 = Segment::Line(Line::new(r.vec(100.0), r.vec(100.0))); @@ -259,6 +262,7 @@ fn segment_extension_only_adds_hits() { /// The closest point on a line is a fixed point of `closest`, and the offset is perpendicular. #[test] +#[expect(clippy::many_single_char_names, reason = "The property uses conventional line/point/parameter notation from the closest-point equations.")] fn line_closest_is_a_fixed_point_and_perpendicular() { let mut r = Rng::new(0xC105E); for _ in 0..4000 { @@ -309,7 +313,7 @@ fn arc_endpoints_and_sampling_are_consistent() { assert!(pt_eq(a.at(0.0), a.start_point(), 1e-9), "at(0) != start_point"); assert!(pt_eq(a.at(1.0), a.end_point(), 1e-9), "at(1) != end_point"); for k in 0..=10 { - let t = k as f64 / 10.0; + let t = f64::from(k) / 10.0; let p = a.at(t); assert!(p.x.is_finite() && p.y.is_finite(), "arc sample not finite at t={t}: {p:?}"); assert!(on_circle(p, a.center, a.radius, 1e-9), "arc sample at t={t} off the circle: {p:?}"); diff --git a/crates/geom/src/region.rs b/crates/geom/src/region.rs index a132c699b..6c7578606 100644 --- a/crates/geom/src/region.rs +++ b/crates/geom/src/region.rs @@ -44,6 +44,10 @@ pub struct Island { pub sources: Vec, } +#[expect( + clippy::cast_possible_truncation, + reason = "Rounded tolerance-bin coordinates intentionally use the defined saturating f64-to-i64 conversion." +)] fn key(p: Vec2, origin: Vec2, q: f64) -> (i64, i64) { // The drawing may be georeferenced far from (0, 0). Quantizing absolute // coordinates saturates i64 and aliases distinct vertices into one key. @@ -90,6 +94,12 @@ fn pair_splits(segs: &[(Vec2, Vec2)], bb: &Bounds2) -> Option>> { /// `pair_splits` with explicit budgets: `None` once more than `max_visits` candidate pairs were visited /// or more than `max_pairs` distinct pairs were tested. +#[expect( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "At most 60,000 segments and 512 grid cells bound the numeric conversions; cell coordinates are clamped before casting." +)] fn pair_splits_limited(segs: &[(Vec2, Vec2)], bb: &Bounds2, max_visits: u64, max_pairs: usize) -> Option>> { let n = segs.len(); let cells = ((n as f64).sqrt().ceil() as usize).clamp(1, 512); @@ -333,6 +343,7 @@ fn points(g: &Graph, ids: &[usize]) -> Option> { } /// 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> { // Try hits along a ray to +X from nearest outward, so nested faces resolve to the innermost. let mut hits: Vec<(f64, usize, usize)> = Vec::new(); @@ -431,6 +442,11 @@ fn outside(core: &Graph, u: usize, steps: usize) -> Option> { } /// Outlines of the groups of curves inside the face `outer` (vertex indices into `g`). +#[expect( + clippy::float_cmp, + clippy::many_single_char_names, + reason = "Exact x equality is required for the deterministic lexicographic tie-break; graph equations keep their conventional short names." +)] fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Option> { let comp = components(g); let outer_comp: std::collections::HashSet = outer.iter().filter_map(|&i| comp.get(i).copied()).collect(); @@ -503,6 +519,7 @@ fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Option> { /// The point of the nearest other curve within `snap` of the end `e` of curve `i`, as (curve, /// segment, parameter, point). `None` when the end touches a curve, or none is near. `Err` when /// the budget of segment checks runs out. +#[expect(clippy::many_single_char_names, reason = "Nearest-point search keeps conventional i/j/k/a/b/t/q/d geometry notation.")] fn nearest_curve(polys: &[Vec], i: usize, e: Vec2, snap: f64, tol: f64, budget: &mut usize) -> Result, ()> { let mut best: Option<(f64, usize, usize, f64, Vec2)> = None; let mut touching = false; @@ -546,6 +563,8 @@ fn nearest_curve(polys: &[Vec], i: usize, e: Vec2, snap: f64, tol: f64, bu /// curve (which gains a vertex there), so the two meet exactly. A curve that is flattened /// into chords (an ellipse, a spline) lies up to the flattening tolerance off the true curve, /// so a line that ends on the true curve can stop just short of the chords. +#[must_use] +#[expect(clippy::many_single_char_names, reason = "Endpoint snapping keeps conventional polyline, segment and point notation.")] pub fn snap_ends(polys: &[Vec], snap: f64, tol: f64) -> Vec> { let mut out: Vec> = polys.to_vec(); if !(snap.is_finite() && snap > tol) { @@ -595,22 +614,26 @@ pub fn snap_ends(polys: &[Vec], snap: f64, tol: f64) -> Vec> { } /// The closed loop enclosing `p`, counter-clockwise, or `None`. +#[must_use] pub fn enclosing_loop(polys: &[Vec], p: Vec2, tol: f64) -> Option> { enclosing_loop_gap(polys, p, tol, 0.0) } /// [`enclosing_loop`], with gaps of up to `gap` between curve ends closed (HPGAPTOL). +#[must_use] pub fn enclosing_loop_gap(polys: &[Vec], p: Vec2, tol: f64, gap: f64) -> Option> { let g = build_gap(polys, tol, gap)?; points(&g, &outer_face(&g, p)?) } /// The closed loop enclosing `p` plus the islands inside it, or `None` when `p` isn't enclosed. +#[must_use] pub fn boundary_at(polys: &[Vec], p: Vec2, tol: f64) -> Option { boundary_at_gap(polys, p, tol, 0.0) } /// [`boundary_at`], with gaps of up to `gap` between curve ends closed (HPGAPTOL). +#[must_use] pub fn boundary_at_gap(polys: &[Vec], p: Vec2, tol: f64, gap: f64) -> Option { let g = build_gap(polys, tol, gap)?; let ids = outer_face(&g, p)?; @@ -626,6 +649,8 @@ pub fn boundary_at_gap(polys: &[Vec], p: Vec2, tol: f64, gap: f64) -> Opti /// 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). +#[must_use] +#[expect(clippy::float_cmp, reason = "Exact x equality is required for the deterministic lexicographic tie-break.")] pub fn outline(polys: &[Vec], tol: f64, gap: f64) -> Option> { let g = build_gap(polys, tol, gap)?; let core = prune(&g); @@ -869,6 +894,7 @@ mod tests { } #[test] + #[expect(clippy::cast_precision_loss, reason = "The test generates 17,000 segments, so every grid index is exact as f64.")] fn long_segment_crossing_in_unsampled_cell_is_split() { // A diagonal long enough to skip the grid, and a short segment crossing it in a cell the old coarse sampling missed. let mut polys = vec![vec![Vec2::new(0.0, 0.0), Vec2::new(1000.0, 1000.0)], vec![Vec2::new(11.0, 12.0), Vec2::new(12.0, 11.0)]]; @@ -943,7 +969,7 @@ mod tests { } fn lines_of(poly: &[Vec2]) -> Vec> { - poly.windows(2).map(|w| w.to_vec()).collect() + poly.windows(2).map(<[Vec2]>::to_vec).collect() } #[test] @@ -1096,6 +1122,7 @@ mod tests { } #[test] + #[expect(clippy::cast_precision_loss, reason = "The test is capped at MAX_SEGMENTS (60,000), so every generated coordinate is exact as f64.")] fn snap_ends_skips_input_over_the_segment_cap() { let mut polys: Vec> = (0..=MAX_SEGMENTS) .map(|i| { diff --git a/crates/geom/src/spline.rs b/crates/geom/src/spline.rs index 99b63f941..8192cbb30 100644 --- a/crates/geom/src/spline.rs +++ b/crates/geom/src/spline.rs @@ -6,7 +6,7 @@ use crate::{Bounds2, Vec2}; /// Largest B-spline degree treated as valid. Basis evaluation is O(degree²) per sample and /// tessellation takes O(degree) samples, so an unbounded degree (DXF/HATCH can declare up to /// 100 000) turns a tiny spline into billions of iterations (CWE-407). Real splines are low -/// degree (AutoCAD caps at 11); above this a spline evaluates to its control polygon instead. +/// degree (`AutoCAD` caps at 11); above this a spline evaluates to its control polygon instead. pub const MAX_DEGREE: usize = 64; /// A (possibly rational) B-spline curve, DXF SPLINE style. @@ -30,6 +30,7 @@ pub struct Spline { impl Spline { /// A clamped uniform spline over control points. + #[must_use] pub fn from_control(control: Vec, degree: usize) -> Spline { let n = control.len(); let degree = degree.clamp(1, n.saturating_sub(1).max(1)); @@ -39,6 +40,7 @@ impl Spline { /// Cubic interpolation through fit points (chord-length parametrisation, natural-ish ends /// via a clamped knot vector: solve the banded system for control points). + #[must_use] pub fn from_fit_points(fit: &[Vec2]) -> Spline { Spline::fit_with(fit, false, FitOptions::default()) } @@ -47,20 +49,24 @@ impl Spline { /// include the closing chord; the knot vector is the periodic (unclamped) extension and the /// first `degree` control points repeat at the end, so the curve has continuous tangent and /// curvature at the seam. A repeated closing fit point is dropped. + #[must_use] pub fn from_fit_points_closed(fit: &[Vec2]) -> Spline { Spline::fit_with(fit, true, FitOptions::default()) } /// Interpolation through fit points, open or closed (see `from_fit_points_closed`). + #[must_use] pub fn from_fit(fit: &[Vec2], closed: bool) -> Spline { Spline::fit_with(fit, closed, FitOptions::default()) } /// Closed with an unclamped (periodic) knot vector, as DXF flags it (group 70 bit 2). + #[must_use] pub fn is_periodic(&self) -> bool { self.closed && self.knots.first() != self.knots.get(self.degree) } + #[must_use] pub fn is_valid(&self) -> bool { let n = self.control.len(); n > self.degree @@ -70,6 +76,7 @@ impl Spline { && self.knots.windows(2).all(|w| w.first() <= w.get(1)) } + #[must_use] pub fn domain(&self) -> (f64, f64) { let lo = self.knots.get(self.degree).copied().unwrap_or(0.0); let hi = self.knots.get(self.control.len()).copied().unwrap_or(1.0); @@ -77,6 +84,7 @@ impl Spline { } /// Evaluate at parameter `t` (de Boor via basis functions). + #[must_use] pub fn eval(&self, t: f64) -> Vec2 { if !self.is_valid() { return self.control.first().copied().unwrap_or_default(); @@ -87,6 +95,7 @@ impl Spline { /// `eval` on a spline `is_valid` has accepted, given its `domain()`, so sampling many points /// validates once (`is_valid` walks the knot vector). + #[expect(clippy::many_single_char_names, reason = "De Boor evaluation keeps the standard p/w/b/k notation shared with basis_ref.")] fn eval_valid(&self, t: f64, lo: f64, hi: f64) -> Vec2 { let n = self.control.len().saturating_sub(1); let t = t.clamp(lo, hi); @@ -113,6 +122,7 @@ impl Spline { if wsum.abs() > 1e-300 { p / wsum } else { p } } + #[must_use] pub fn tessellate(&self, tol: f64) -> Vec { if !self.is_valid() { return self.control.clone(); @@ -128,16 +138,22 @@ impl Spline { /// The segments for a control polygon `ratio` times the tolerance: dimensionless, so a /// spline and its scaled copy sample alike at any scale. + #[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "The floating count is clamped to 8..=2000 before its truncating conversion to usize." + )] fn segments_for(&self, ratio: f64) -> usize { let n = (ratio.sqrt() * 2.0).clamp(8.0, 2000.0) as usize * self.degree.max(1); n.min(MAX_SAMPLES) } fn polygon_length(&self) -> f64 { - self.control.windows(2).map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0)).sum() + self.control.windows(2).map(|w| w.first().zip(w.get(1)).map_or(0.0, |(a, b)| a.dist(*b))).sum() } /// `n + 1` points evenly spaced in parameter over the domain (the spline must be valid). + #[expect(clippy::cast_precision_loss, reason = "Internal callers cap sample counts at MAX_SAMPLES (4000), so every index is exact as f64.")] fn samples(&self, n: usize) -> impl Iterator + '_ { let (lo, hi) = self.domain(); (0..=n).map(move |i| self.eval_valid(lo + (hi - lo) * i as f64 / n as f64, lo, hi)) @@ -159,6 +175,13 @@ impl Spline { /// is its control polygon, so its control box is exact; a degenerate spline gets its control /// box, which contains the curve (the box of the finite control points when one is not /// finite: `hull` skips it, but it would poison every sample). + #[must_use] + #[expect( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "Budgets and per-span counts are capped at MAX_SAMPLES; span fractions are nonnegative before conversion." + )] pub fn bounds(&self) -> Bounds2 { let hull = Bounds2::from_points(self.control.iter().copied()); let diag = hull.min.dist(hull.max); @@ -275,6 +298,10 @@ impl Spline { /// control points took minutes). const MAX_SAMPLES: usize = 4000; +#[expect( + clippy::cast_precision_loss, + reason = "Knot indices are sampled as normalized f64 parameters; any precision loss would only be beyond 2^53 allocated control points." +)] pub(crate) fn clamped_uniform_knots(n: usize, degree: usize) -> Vec { let mut k = vec![0.0; degree + 1]; let inner = n.saturating_sub(degree + 1); @@ -292,7 +319,7 @@ pub(crate) fn find_span(n: usize, p: usize, u: f64, knots: &[f64]) -> usize { } let mut low = p; let mut high = n + 1; - let mut mid = (low + high) / 2; + let mut mid = usize::midpoint(low, high); let mut guard = 0; while guard < 200 { guard += 1; @@ -305,7 +332,7 @@ pub(crate) fn find_span(n: usize, p: usize, u: f64, knots: &[f64]) -> usize { } else { break; } - mid = (low + high) / 2; + mid = usize::midpoint(low, high); } mid } @@ -325,6 +352,11 @@ pub(crate) fn basis(span: usize, u: f64, p: usize, knots: &[f64]) -> Vec { /// `basis` into `n[..=p]`, with `left` and `right` as scratch; each must hold `p + 1` values or /// `n` stays as it was. +#[expect( + clippy::cast_possible_wrap, + clippy::cast_sign_loss, + reason = "Spline indices are bounded by slice lengths, and max(0) makes the converted index nonnegative." +)] fn basis_into(span: usize, u: f64, p: usize, knots: &[f64], n: &mut [f64], left: &mut [f64], right: &mut [f64]) { if n.len() <= p || left.len() <= p || right.len() <= p { return; @@ -358,6 +390,7 @@ fn basis_into(span: usize, u: f64, p: usize, knots: &[f64], n: &mut [f64], left: /// NaN, infinity or magnitudes above `1e100` (which could overflow) takes the full sweep, and so /// does a back-substitution row whose banded sum is zero (skipped zero terms can flip its sign). #[allow(clippy::needless_range_loop)] +#[expect(clippy::many_single_char_names, reason = "Gaussian elimination keeps conventional matrix/row/column notation.")] pub(crate) fn solve(mut a: Vec>, mut b: Vec) -> Option> { #[cfg(test)] if tests::DENSE_ORACLE.get() { diff --git a/crates/geom/src/spline/tests.rs b/crates/geom/src/spline/tests.rs index 6a81b141f..c9e19ccc9 100644 --- a/crates/geom/src/spline/tests.rs +++ b/crates/geom/src/spline/tests.rs @@ -1,6 +1,11 @@ use super::*; /// `basis` before it evaluated on the stack, kept as the reference. +#[expect( + clippy::cast_possible_wrap, + clippy::cast_sign_loss, + reason = "Spline indices are bounded by slice lengths, and max(0) makes the converted index nonnegative." +)] fn basis_ref(span: usize, u: f64, p: usize, knots: &[f64]) -> Vec { let mut n = vec![0.0; p + 1]; let mut left = vec![0.0; p + 1]; @@ -23,6 +28,7 @@ fn basis_ref(span: usize, u: f64, p: usize, knots: &[f64]) -> Vec { } /// `eval` before it evaluated on the stack, kept as the reference. +#[expect(clippy::many_single_char_names, reason = "The reference implementation keeps the NURBS equation notation used by the algorithm under test.")] fn eval_ref(s: &Spline, t: f64) -> Vec2 { let n = s.control.len() - 1; let (lo, hi) = s.domain(); @@ -41,21 +47,26 @@ fn eval_ref(s: &Spline, t: f64) -> Vec2 { } /// Deterministic pseudo-random numbers in `0..1`. +#[expect(clippy::cast_precision_loss, reason = "The generator keeps exactly 53 random bits, and 2^53 is exactly representable as f64.")] fn noise(seed: &mut u64) -> f64 { - *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + *seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); (*seed >> 11) as f64 / (1u64 << 53) as f64 } /// Splines of degree 1..=11 over 14 control points: clamped and unclamped (uniform) knots, /// unit and random weights. +#[expect( + clippy::cast_precision_loss, + reason = "The test uses 14 control points and degrees through 11, so every knot index is exactly representable as f64." +)] fn samples() -> Vec { let mut seed = 7; let mut out = Vec::new(); for degree in 1..=11 { - let control: Vec = (0..14).map(|i| Vec2::new(i as f64 * 3.0 + noise(&mut seed), 10.0 * noise(&mut seed) - 5.0)).collect(); + let control: Vec = (0..14).map(|i| Vec2::new(f64::from(i) * 3.0 + noise(&mut seed), 10.0 * noise(&mut seed) - 5.0)).collect(); let weights: Vec = (0..14).map(|_| 0.5 + 1.5 * noise(&mut seed)).collect(); let clamped = Spline::from_control(control.clone(), degree); - let uniform = Spline { knots: (0..control.len() + degree + 1).map(|i| i as f64 * 0.25).collect(), ..clamped.clone() }; + let uniform = Spline { knots: (0..=(control.len() + degree)).map(|i| i as f64 * 0.25).collect(), ..clamped.clone() }; for base in [clamped, uniform] { out.push(Spline { weights: weights.clone(), ..base.clone() }); out.push(base); @@ -70,7 +81,7 @@ fn stack_basis_matches_the_heap_basis_bit_for_bit() { assert!(s.is_valid()); let (lo, hi) = s.domain(); for i in -20..=1020 { - let t = lo + (hi - lo) * i as f64 / 1000.0; + let t = lo + (hi - lo) * f64::from(i) / 1000.0; let got = s.eval(t); let want = eval_ref(&s, t); assert_eq!((got.x.to_bits(), got.y.to_bits()), (want.x.to_bits(), want.y.to_bits()), "degree {} at {t}: {got:?} vs {want:?}", s.degree); @@ -87,14 +98,14 @@ fn basis_into_needs_room_for_every_function() { let knots = clamped_uniform_knots(6, 3); let (mut n, mut left, mut right) = ([0.5; 3], [0.0; 4], [0.0; 4]); basis_into(3, 0.5, 3, &knots, &mut n, &mut left, &mut right); - assert_eq!(n, [0.5; 3]); + assert_eq!(n.map(f64::to_bits), [0.5; 3].map(f64::to_bits)); } /// A cubic through 300 points of a sine wave, open or closed. fn wiggly(closed: bool) -> Spline { let fit: Vec = (0..300) .map(|i| { - let x = i as f64 / 299.0; + let x = f64::from(i) / 299.0; Vec2::new(x * 100.0, 10.0 * (x * 60.0).sin()) }) .collect(); @@ -108,6 +119,7 @@ fn fine_box(s: &Spline) -> Bounds2 { /// The box of `n + 1` samples evenly spaced in parameter over the domain, as `bounds` sampled /// before it spread its samples over the knot spans. +#[expect(clippy::cast_precision_loss, reason = "Test grids are capped at MAX_SAMPLES (4000), so sample indices are exactly representable as f64.")] fn uniform_box(s: &Spline, n: usize) -> Bounds2 { let (lo, hi) = s.domain(); Bounds2::from_points((0..=n).map(|i| s.eval(lo + (hi - lo) * i as f64 / n as f64))) @@ -118,7 +130,7 @@ fn uniform_box(s: &Spline, n: usize) -> Bounds2 { /// except for a peak of 50 at t = 0.50035, inside a span of width 1e-4 that no point of a /// uniform grid of up to 4000 hits (0.50025 and 0.5005 are the nearest). fn narrow_span() -> Spline { - let control = (0..7).map(|i| Vec2::new(i as f64, if i == 3 { 100.0 } else { 0.0 })).collect(); + let control = (0..7).map(|i| Vec2::new(f64::from(i), if i == 3 { 100.0 } else { 0.0 })).collect(); Spline { degree: 2, knots: vec![0.0, 0.0, 0.0, 0.5003, 0.5003, 0.5004, 0.5004, 1.0, 1.0, 1.0], control, ..Spline::default() } } @@ -132,14 +144,14 @@ fn an_off_grid_peak_in_a_narrow_span_is_within_a_percent() { s.control[4].y = 30.0; assert!(s.is_valid()); let (a, b) = (0.5003, 0.5004); - let peak = (0..=10_000).map(|i| s.eval(a + (b - a) * i as f64 / 10_000.0)).fold(Vec2::ZERO, |m, p| if p.y > m.y { p } else { m }); + let peak = (0..=10_000).map(|i| s.eval(a + (b - a) * f64::from(i) / 10_000.0)).fold(Vec2::ZERO, |m, p| if p.y > m.y { p } else { m }); assert!(peak.y > 58.0 && peak.y < 59.0, "{peak:?}"); let hull = Bounds2::from_points(s.control.iter().copied()); let diag = hull.min.dist(hull.max); let got = s.bounds(); assert!(got.max.y <= peak.y + 1e-9 * diag && got.max.y >= peak.y - 1e-2 * diag, "{got:?} vs peak {peak:?}"); // Four segments, the floor before, missed it by more than that. - let four = (0..=4).map(|i| s.eval(a + (b - a) * i as f64 / 4.0)).fold(f64::MIN, |m, p| m.max(p.y)); + let four = (0..=4).map(|i| s.eval(a + (b - a) * f64::from(i) / 4.0)).fold(f64::MIN, |m, p| m.max(p.y)); assert!(four < peak.y - 1e-2 * diag, "{four} vs {peak:?}"); } @@ -148,7 +160,7 @@ fn bounds_see_an_extreme_inside_a_narrow_knot_span() { let s = narrow_span(); assert!(s.is_valid()); let (a, b) = (0.5003, 0.5004); - let peak = (0..=1000).map(|i| s.eval(a + (b - a) * i as f64 / 1000.0)).fold(Vec2::ZERO, |m, p| if p.y > m.y { p } else { m }); + let peak = (0..=1000).map(|i| s.eval(a + (b - a) * f64::from(i) / 1000.0)).fold(Vec2::ZERO, |m, p| if p.y > m.y { p } else { m }); assert!((peak.x - 3.0).abs() < 1e-9 && (peak.y - 50.0).abs() < 1e-9, "{peak:?}"); let hull = Bounds2::from_points(s.control.iter().copied()); let diag = hull.min.dist(hull.max); @@ -165,6 +177,7 @@ fn bounds_see_an_extreme_inside_a_narrow_knot_span() { } #[test] +#[expect(clippy::cast_precision_loss, reason = "The test grids contain 1502 or 2502 points, so all sample indices are exact as f64.")] fn bounds_keep_their_cap_over_many_spans() { // 1500 spans: eight per span would pass the cap, so two; 2500 spans: more than the cap // allows two for, so the control box, which contains the curve. A smooth curve stays diff --git a/crates/geom/src/spline_fit.rs b/crates/geom/src/spline_fit.rs index 4abdc977c..f3ead5099 100644 --- a/crates/geom/src/spline_fit.rs +++ b/crates/geom/src/spline_fit.rs @@ -1,5 +1,5 @@ //! Fit-point splines: knot parametrisation (chord, square root, uniform), end tangents and fit -//! tolerance (least-squares approximation with fewer control points), as AutoCAD's SPLINE Fit +//! tolerance (least-squares approximation with fewer control points), as `AutoCAD`'s SPLINE Fit //! method offers them. Construction follows the textbook global interpolation and approximation //! schemes (Piegl & Tiller, *The NURBS Book*, ch. 9). @@ -24,6 +24,7 @@ impl KnotParam { pub const ALL: [KnotParam; 3] = [KnotParam::Chord, KnotParam::SqrtChord, KnotParam::Uniform]; /// The name as the prompt and the "Current settings" line show it. + #[must_use] pub fn name(self) -> &'static str { match self { KnotParam::Chord => "Chord", @@ -34,6 +35,7 @@ impl KnotParam { /// Parse a keyword or JSON value ("chord", "sqrt", "square root", "uniform", or 0/1/2 as in /// the SPLKNOTS setting). + #[must_use] pub fn parse(s: &str) -> Option { Some(match s.trim().to_ascii_lowercase().as_str() { "c" | "chord" | "0" => KnotParam::Chord, @@ -44,6 +46,7 @@ impl KnotParam { } /// The SPLKNOTS code (0 chord, 1 square root, 2 uniform). + #[must_use] pub fn code(self) -> i64 { match self { KnotParam::Chord => 0, @@ -81,6 +84,7 @@ pub struct FitOptions { impl FitOptions { /// Normalised tangents (zero or non-finite directions dropped) and a finite, non-negative /// tolerance: what a spline stores. + #[must_use] pub fn sanitized(self) -> FitOptions { let dir = |t: Option| t.filter(|v| v.x.is_finite() && v.y.is_finite() && v.len() > 1e-12).map(Vec2::normalized); FitOptions { @@ -107,26 +111,27 @@ impl Spline { /// control points. A fit point given twice in a row is a kink (SPLINEDIT Fit data Kink): the /// curve passes through it with a corner (a knot of full multiplicity) and the pieces on /// either side are fitted on their own. + #[must_use] pub fn fit_with(fit: &[Vec2], closed: bool, opts: FitOptions) -> Spline { let opts = opts.sanitized(); let kinked = if fit.len() <= MAX_KINK_POINTS { kinked_fit(fit, closed, opts) } else { None }; - let mut s = match kinked { - Some(s) => s, - None => { - // Repeats at the ends of an open curve are no corners: fit without them. - let (pts, _) = kinks(fit, false); - let mut s = if closed { closed_fit(&pts, opts.knots, opts.tolerance) } else { open_fit(&pts, opts) }; - if pts.len() != fit.len() && !closed { - s.fit = fit.to_vec(); - } - s + let mut s = if let Some(s) = kinked { + s + } else { + // Repeats at the ends of an open curve are no corners: fit without them. + let (pts, _) = kinks(fit, false); + let mut s = if closed { closed_fit(&pts, opts.knots, opts.tolerance) } else { open_fit(&pts, opts) }; + if pts.len() != fit.len() && !closed { + s.fit = fit.to_vec(); } + s }; s.fit_opts = if closed { FitOptions { start_tangent: None, end_tangent: None, ..opts } } else { opts }; s } /// Rebuild from new fit points with this spline's knot parametrisation, tangents and tolerance. + #[must_use] pub fn refit(&self, fit: &[Vec2], closed: bool) -> Spline { Spline::fit_with(fit, closed, self.fit_opts) } @@ -134,6 +139,7 @@ impl Spline { /// Which knot parametrisation produced this spline's knots from its fit points (DXF files /// keep the knots but not the parametrisation). Compares knot vectors only (no solving), so /// it is cheap for any number of fit points. Chord when nothing matches. + #[must_use] pub fn infer_knot_param(&self) -> KnotParam { if self.fit.len() < 3 { return self.fit_opts.knots; @@ -210,19 +216,19 @@ pub(crate) fn params(pts: &[Vec2], kind: KnotParam, closed: bool) -> Vec { let mut u = vec![0.0; count]; let mut total = 0.0; for i in 1..count { - total += pts.get(i - 1).zip(pts.get(i % n.max(1))).map(|(a, b)| kind.step(a.dist(*b))).unwrap_or(1.0); + total += pts.get(i - 1).zip(pts.get(i % n.max(1))).map_or(1.0, |(a, b)| kind.step(a.dist(*b))); if let Some(x) = u.get_mut(i) { *x = total; } } - for x in u.iter_mut() { + for x in &mut u { *x /= total.max(1e-300); } u } fn chord_length(pts: &[Vec2]) -> f64 { - pts.windows(2).map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0)).sum() + pts.windows(2).map(|w| w.first().zip(w.get(1)).map_or(0.0, |(a, b)| a.dist(*b))).sum() } fn open_fit(fit: &[Vec2], opts: FitOptions) -> Spline { @@ -262,6 +268,11 @@ fn open_fit(fit: &[Vec2], opts: FitOptions) -> Spline { /// Global interpolation: one control point per fit point plus one per end-derivative /// constraint, knots by averaging the parameters (an end with a derivative counts its /// parameter twice). +#[expect( + clippy::cast_precision_loss, + clippy::many_single_char_names, + reason = "Interpolation uses NURBS matrix notation, and its degree is capped at three, so p is exact as f64." +)] fn interpolate(fit: &[Vec2], u: &[f64], d0: Option, d1: Option) -> Option { let (p, knots) = interp_knots(u, d0.is_some(), d1.is_some()); let m = knots.len().checked_sub(p + 1)?; @@ -305,6 +316,7 @@ fn interpolate(fit: &[Vec2], u: &[f64], d0: Option, d1: Option) -> O /// Degree and clamped knots for interpolating at parameters `u`, with optional end derivatives: /// knots average the parameters, an end with a derivative counting its parameter twice. +#[expect(clippy::cast_precision_loss, reason = "The interpolation degree is capped at three, so p is exact as f64.")] fn interp_knots(u: &[f64], d0: bool, d1: bool) -> (usize, Vec) { let m = u.len() + usize::from(d0) + usize::from(d1); let p = 3.min(m.saturating_sub(1)).max(1); @@ -323,6 +335,13 @@ fn interp_knots(u: &[f64], d0: bool, d1: bool) -> (usize, Vec) { /// Clamped knots for a least-squares fit with `m` control points of degree `p` so every span /// holds parameters (The NURBS Book eq. 9.69). Needs `p < m < u.len()`. +#[expect( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + clippy::many_single_char_names, + reason = "Fit sizes are bounded by MAX_APPROX_POINTS, knot indices are nonnegative and clamped, and the equations use NURBS Book notation." +)] fn lsq_knots(u: &[f64], m: usize, p: usize) -> Vec { let n = u.len(); let d = n as f64 / m.saturating_sub(p).max(1) as f64; @@ -339,12 +358,18 @@ fn lsq_knots(u: &[f64], m: usize, p: usize) -> Vec { /// Periodic knots for `n` points with closed parameters `t` (`n + 1` values): knots[j] = /// t_(j-p), extended by whole periods on both sides. +#[expect( + clippy::cast_precision_loss, + clippy::cast_possible_wrap, + clippy::many_single_char_names, + reason = "Indices are bounded by slice lengths, period offsets are f64 by design, and the periodic equations use standard notation." +)] fn periodic_knots(t: &[f64], n: usize, p: usize) -> Vec { let tk = |i: isize| { let (q, r) = (i.div_euclid(n.max(1) as isize), i.rem_euclid(n.max(1) as isize) as usize); t.get(r).copied().unwrap_or(0.0) + q as f64 }; - (0..n + 2 * p + 1).map(|j| tk(j as isize - p as isize)).collect() + (0..=(n + 2 * p)).map(|j| tk(j as isize - p as isize)).collect() } /// Least-squares approximation within `tol`: the fewest control points (searched by bisection) @@ -357,7 +382,7 @@ fn approximate(fit: &[Vec2], u: &[f64], d0: Option, d1: Option, tol: let (mut lo, mut hi) = (p + 1, n.checked_sub(1)?); let mut best = None; while lo <= hi { - let mid = (lo + hi) / 2; + let mid = usize::midpoint(lo, hi); match least_squares(fit, u, mid, p, d0, d1) { Some(s) if max_deviation(&s, fit, u) <= tol => { best = Some(s); @@ -373,6 +398,11 @@ fn max_deviation(s: &Spline, fit: &[Vec2], u: &[f64]) -> f64 { fit.iter().zip(u).map(|(q, t)| s.eval(*t).dist(*q)).fold(0.0, f64::max) } +#[expect( + clippy::cast_precision_loss, + clippy::many_single_char_names, + reason = "Open least-squares fitting is cubic and keeps the NURBS Book matrix notation, so p is exact as f64." +)] fn least_squares(fit: &[Vec2], u: &[f64], m: usize, p: usize, d0: Option, d1: Option) -> Option { let n = fit.len(); if m <= p || m >= n { @@ -522,6 +552,11 @@ fn kinked_fit(fit: &[Vec2], closed: bool, opts: FitOptions) -> Option { /// A clamped, non-rational fitted piece raised to degree 3: interpolation through two or three /// points gives a single Bézier segment of lower degree, which is raised exactly. +#[expect( + clippy::cast_precision_loss, + clippy::many_single_char_names, + reason = "Degree elevation stops at three and keeps the Bézier coefficient notation, so all indices are exact as f64." +)] fn cubic(mut s: Spline) -> Option { if s.degree == 3 { return Some(s); @@ -555,7 +590,7 @@ fn approximate_closed(pts: &[Vec2], t: &[f64], p: usize, tol: f64) -> Option { best = Some(s); @@ -570,6 +605,13 @@ fn approximate_closed(pts: &[Vec2], t: &[f64], p: usize, tol: f64) -> Option Option { let n = pts.len(); if m <= p || m >= n || t.len() != n + 1 { @@ -620,6 +662,7 @@ fn periodic_least_squares(pts: &[Vec2], t: &[f64], m: usize, p: usize) -> Option Some(Spline { degree: p, knots, control, fit: pts.to_vec(), closed: true, ..Spline::default() }) } +#[expect(clippy::many_single_char_names, reason = "Closed interpolation keeps the NURBS Book parameter, degree and matrix notation.")] fn closed_fit(fit: &[Vec2], kind: KnotParam, tol: f64) -> Spline { let mut pts = fit.to_vec(); if pts.len() > 3 && pts.first().zip(pts.last()).is_some_and(|(a, b)| a.near(*b, 1e-12)) { @@ -748,7 +791,7 @@ mod tests { // Thirty noisy points along a gentle arc. let fit: Vec = (0..30) .map(|i| { - let t = i as f64 / 29.0; + let t = f64::from(i) / 29.0; Vec2::new(t * 10.0, (t * 3.0).sin() * 2.0 + if i % 2 == 0 { 0.01 } else { -0.01 }) }) .collect(); @@ -761,7 +804,7 @@ mod tests { assert!(max_deviation(&s, &fit, &u) <= tol + 1e-9); assert!(s.eval(0.0).near(fit[0], 1e-9) && s.eval(1.0).near(fit[29], 1e-9), "ends stay exact"); assert_eq!(s.fit, fit, "the fit points are kept"); - assert_eq!(s.fit_opts.tolerance, tol); + assert_eq!(s.fit_opts.tolerance.to_bits(), tol.to_bits()); // With tangents too. let t = Spline::fit_with( &fit, @@ -781,7 +824,7 @@ mod tests { // Forty slightly noisy points round a circle. let fit: Vec = (0..40) .map(|i| { - let a = i as f64 / 40.0 * std::f64::consts::TAU; + let a = f64::from(i) / 40.0 * std::f64::consts::TAU; let r = 5.0 + if i % 2 == 0 { 0.01 } else { -0.01 }; Vec2::new(a.cos() * r, a.sin() * r) }) @@ -796,7 +839,7 @@ mod tests { let (lo, hi) = s.domain(); assert!(s.eval(lo).near(s.eval(hi), 1e-9), "still closed"); assert_eq!(s.fit, fit); - assert_eq!(s.fit_opts.tolerance, tol); + assert_eq!(s.fit_opts.tolerance.to_bits(), tol.to_bits()); // Too tight a tolerance interpolates. let tiny = Spline::fit_with(&fit, true, FitOptions { tolerance: 1e-9, ..FitOptions::default() }); assert_eq!(tiny.control.len(), exact.control.len()); @@ -809,10 +852,14 @@ mod tests { fn on_curve(s: &Spline, q: Vec2) -> bool { let (lo, hi) = s.domain(); - (0..=4000).any(|i| s.eval(lo + (hi - lo) * i as f64 / 4000.0).dist(q) < 1e-2) + (0..=4000).any(|i| s.eval(lo + (hi - lo) * f64::from(i) / 4000.0).dist(q) < 1e-2) } #[test] + #[expect( + clippy::many_single_char_names, + reason = "The test names spline values and points with the same short notation as the fitting equations." + )] fn repeated_fit_points_make_kinks() { let fit = [Vec2::new(0.0, 0.0), Vec2::new(2.0, 2.0), Vec2::new(4.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(6.0, 2.0), Vec2::new(8.0, 0.0)]; let s = Spline::fit_with(&fit, false, FitOptions::default()); @@ -873,13 +920,17 @@ mod tests { let _ = Spline::fit_with(&pairs[..n], closed, FitOptions { tolerance: 0.1, ..FitOptions::default() }); } } - let tight: Vec = (0..8).map(|i| Vec2::new(i as f64 * 1e-13, 0.0)).collect(); + let tight: Vec = (0..8).map(|i| Vec2::new(f64::from(i) * 1e-13, 0.0)).collect(); let _ = Spline::fit_with(&tight, true, FitOptions { tolerance: 1.0, ..FitOptions::default() }); } /// Above the interpolation cap the fit points become control points instead of a dense /// system the size of their count squared (issue #702); just below it they still interpolate. #[test] + #[expect( + clippy::cast_precision_loss, + reason = "The generated test grids are bounded by MAX_INTERP_POINTS + 1, so their indices are exact as f64." + )] fn too_many_fit_points_are_not_interpolated() { let wave = |n: usize| -> Vec { (0..n).map(|i| Vec2::new((i * i) as f64 * 1e-3, (i % 5) as f64)).collect() }; let fit = wave(MAX_INTERP_POINTS + 1); diff --git a/crates/geom/src/tests.rs b/crates/geom/src/tests.rs index 57ffcd663..52aa42683 100644 --- a/crates/geom/src/tests.rs +++ b/crates/geom/src/tests.rs @@ -214,7 +214,7 @@ fn segment_offset() { let s = Segment::Arc { arc: Arc::new(Vec2::ZERO, 5.0, 0.0, PI), ccw: true }; let o = s.offset(1.0).unwrap(); if let Segment::Arc { arc, .. } = o { - assert!(close(arc.radius, 4.0)) + assert!(close(arc.radius, 4.0)); } else { panic!() } @@ -341,8 +341,8 @@ fn polyline_area_is_stable_far_from_the_origin() { fn shoelace_preserves_small_polygon_area_at_large_coordinates() { let o = 1.0e12; let corners = [Vec2::new(o, o), Vec2::new(o + 10.0, o), Vec2::new(o + 10.0, o + 10.0), Vec2::new(o, o + 10.0)]; - assert_eq!(shoelace(&corners), 100.0); - assert_eq!(shoelace(&corners.iter().rev().copied().collect::>()), -100.0); + assert_eq!(shoelace(&corners).to_bits(), 100.0_f64.to_bits()); + assert_eq!(shoelace(&corners.iter().rev().copied().collect::>()).to_bits(), (-100.0_f64).to_bits()); } #[test] diff --git a/crates/geom/src/vec.rs b/crates/geom/src/vec.rs index ba0f358e2..d21359e69 100644 --- a/crates/geom/src/vec.rs +++ b/crates/geom/src/vec.rs @@ -14,78 +14,100 @@ impl Vec2 { pub const X: Vec2 = Vec2 { x: 1.0, y: 0.0 }; pub const Y: Vec2 = Vec2 { x: 0.0, y: 1.0 }; + #[must_use] pub const fn new(x: f64, y: f64) -> Self { Vec2 { x, y } } /// Unit vector at `angle` radians. + #[must_use] pub fn from_angle(angle: f64) -> Self { Vec2::new(angle.cos(), angle.sin()) } + #[must_use] pub fn polar(center: Vec2, radius: f64, angle: f64) -> Self { center + Vec2::from_angle(angle) * radius } + #[must_use] pub fn dot(self, o: Vec2) -> f64 { self.x * o.x + self.y * o.y } /// z of the 3D cross product. + #[must_use] pub fn cross(self, o: Vec2) -> f64 { self.x * o.y - self.y * o.x } + #[must_use] pub fn len(self) -> f64 { self.x.hypot(self.y) } + #[must_use] pub fn len2(self) -> f64 { self.dot(self) } + #[must_use] pub fn dist(self, o: Vec2) -> f64 { (self - o).len() } + #[must_use] pub fn angle(self) -> f64 { crate::norm_angle(self.y.atan2(self.x)) } + #[must_use] pub fn angle_to(self, o: Vec2) -> f64 { (o - self).angle() } /// Unit vector, or zero for a zero-length vector. + #[must_use] pub fn normalized(self) -> Vec2 { let l = self.len(); if l > crate::EPS { self / l } else { Vec2::ZERO } } /// Rotated 90° counter-clockwise. + #[must_use] pub fn perp(self) -> Vec2 { Vec2::new(-self.y, self.x) } + #[must_use] pub fn rotate(self, a: f64) -> Vec2 { let (s, c) = a.sin_cos(); Vec2::new(self.x * c - self.y * s, self.x * s + self.y * c) } + #[must_use] pub fn rotate_about(self, center: Vec2, a: f64) -> Vec2 { center + (self - center).rotate(a) } + #[must_use] pub fn lerp(self, o: Vec2, t: f64) -> Vec2 { self + (o - self) * t } + #[must_use] pub fn mid(self, o: Vec2) -> Vec2 { Vec2::new(self.x.midpoint(o.x), self.y.midpoint(o.y)) } + #[must_use] pub fn is_finite(self) -> bool { self.x.is_finite() && self.y.is_finite() } + #[must_use] pub fn near(self, o: Vec2, tol: f64) -> bool { // Squaring very large finite values can overflow on both sides and make // unrelated points compare equal (infinity <= infinity). tol.is_finite() && tol >= 0.0 && self.dist(o) <= tol } + #[must_use] pub fn to3(self, z: f64) -> Vec3 { Vec3::new(self.x, self.y, z) } + #[must_use] pub fn min(self, o: Vec2) -> Vec2 { Vec2::new(self.x.min(o.x), self.y.min(o.y)) } + #[must_use] pub fn max(self, o: Vec2) -> Vec2 { Vec2::new(self.x.max(o.x), self.y.max(o.y)) } /// Mirror across the infinite line through `a` and `b`. + #[must_use] pub fn mirror(self, a: Vec2, b: Vec2) -> Vec2 { let d = (b - a).normalized(); if d == Vec2::ZERO { @@ -151,26 +173,33 @@ pub struct Vec3 { impl Vec3 { pub const ZERO: Vec3 = Vec3 { x: 0.0, y: 0.0, z: 0.0 }; pub const Z: Vec3 = Vec3 { x: 0.0, y: 0.0, z: 1.0 }; + #[must_use] pub const fn new(x: f64, y: f64, z: f64) -> Self { Vec3 { x, y, z } } + #[must_use] pub fn xy(self) -> Vec2 { Vec2::new(self.x, self.y) } + #[must_use] pub fn dot(self, o: Vec3) -> f64 { self.x * o.x + self.y * o.y + self.z * o.z } + #[must_use] pub fn cross(self, o: Vec3) -> Vec3 { Vec3::new(self.y * o.z - self.z * o.y, self.z * o.x - self.x * o.z, self.x * o.y - self.y * o.x) } + #[must_use] pub fn len(self) -> f64 { // Avoid overflowing the squared components of large finite vectors. self.x.hypot(self.y).hypot(self.z) } + #[must_use] pub fn normalized(self) -> Vec3 { let l = self.len(); if l > crate::EPS { self * (1.0 / l) } else { Vec3::ZERO } } + #[must_use] pub fn is_finite(self) -> bool { self.x.is_finite() && self.y.is_finite() && self.z.is_finite() } From 64f707968fed2308217bff386b5d275561f17fa0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Sun, 1 Nov 2026 19:43:35 +0100 Subject: [PATCH 2/4] test(geom): use assert_eq for NaN arc bound --- crates/geom/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/geom/src/tests.rs b/crates/geom/src/tests.rs index 52aa42683..8dc561337 100644 --- a/crates/geom/src/tests.rs +++ b/crates/geom/src/tests.rs @@ -237,7 +237,7 @@ fn polyline_tessellation_is_bounded() { fn arc_segments_bounded() { assert_eq!(arc_segments(0.0, 1.0, 0.1), 1); assert!(arc_segments(1e9, TAU, 1e-12) <= 4096); - assert!(arc_segments(f64::NAN, TAU, 0.1) == 1); + assert_eq!(arc_segments(f64::NAN, TAU, 0.1), 1); } #[test] From ff2163ddfe8d3b35f5454e5f6d4f2d433fae70dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Sun, 1 Nov 2026 23:42:36 +0100 Subject: [PATCH 3/4] style(geom): remove review churn --- crates/geom/src/bounds.rs | 11 ------- crates/geom/src/curve.rs | 62 ----------------------------------- crates/geom/src/fillet.rs | 3 -- crates/geom/src/intersect.rs | 6 ---- crates/geom/src/lib.rs | 8 +---- crates/geom/src/mat.rs | 19 ----------- crates/geom/src/nurbs.rs | 21 ------------ crates/geom/src/region.rs | 6 ---- crates/geom/src/spline.rs | 10 ------ crates/geom/src/spline_fit.rs | 7 ---- crates/geom/src/vec.rs | 29 ---------------- 11 files changed, 1 insertion(+), 181 deletions(-) diff --git a/crates/geom/src/bounds.rs b/crates/geom/src/bounds.rs index ad7f2549f..5efaca027 100644 --- a/crates/geom/src/bounds.rs +++ b/crates/geom/src/bounds.rs @@ -24,7 +24,6 @@ impl Default for Bounds2 { impl Bounds2 { pub const EMPTY: Bounds2 = Bounds2 { min: Vec2 { x: f64::INFINITY, y: f64::INFINITY }, max: Vec2 { x: f64::NEG_INFINITY, y: f64::NEG_INFINITY } }; - #[must_use] pub fn new(a: Vec2, b: Vec2) -> Self { Bounds2 { min: a.min(b), max: a.max(b) } } @@ -35,7 +34,6 @@ impl Bounds2 { } b } - #[must_use] pub fn is_empty(&self) -> bool { !(self.min.x <= self.max.x && self.min.y <= self.max.y) } @@ -45,7 +43,6 @@ impl Bounds2 { self.max = self.max.max(p); } } - #[must_use] pub fn union(&self, o: &Bounds2) -> Bounds2 { if o.is_empty() { return *self; @@ -55,15 +52,12 @@ impl Bounds2 { } Bounds2 { min: self.min.min(o.min), max: self.max.max(o.max) } } - #[must_use] pub fn width(&self) -> f64 { if self.is_empty() { 0.0 } else { span(self.min.x, self.max.x) } } - #[must_use] pub fn height(&self) -> f64 { if self.is_empty() { 0.0 } else { span(self.min.y, self.max.y) } } - #[must_use] pub fn center(&self) -> Vec2 { if self.is_empty() { return Vec2::ZERO; @@ -75,27 +69,22 @@ impl Bounds2 { }; Vec2::new(mid(self.min.x, self.max.x), mid(self.min.y, self.max.y)) } - #[must_use] pub fn contains(&self, p: Vec2) -> bool { p.x >= self.min.x && p.x <= self.max.x && p.y >= self.min.y && p.y <= self.max.y } /// True when `o` lies entirely inside. - #[must_use] pub fn contains_box(&self, o: &Bounds2) -> bool { !o.is_empty() && self.contains(o.min) && self.contains(o.max) } - #[must_use] pub fn intersects(&self, o: &Bounds2) -> bool { !(self.is_empty() || o.is_empty() || o.min.x > self.max.x || o.max.x < self.min.x || o.min.y > self.max.y || o.max.y < self.min.y) } - #[must_use] pub fn expand(&self, d: f64) -> Bounds2 { if self.is_empty() { return *self; } Bounds2 { min: self.min - Vec2::new(d, d), max: self.max + Vec2::new(d, d) } } - #[must_use] pub fn corners(&self) -> [Vec2; 4] { [self.min, Vec2::new(self.max.x, self.min.y), self.max, Vec2::new(self.min.x, self.max.y)] } diff --git a/crates/geom/src/curve.rs b/crates/geom/src/curve.rs index ddda27e82..7f3bd74c5 100644 --- a/crates/geom/src/curve.rs +++ b/crates/geom/src/curve.rs @@ -10,53 +10,42 @@ pub struct Line { } impl Line { - #[must_use] pub fn new(a: Vec2, b: Vec2) -> Self { Line { a, b } } - #[must_use] pub fn len(&self) -> f64 { self.a.dist(self.b) } - #[must_use] pub fn dir(&self) -> Vec2 { (self.b - self.a).normalized() } - #[must_use] pub fn mid(&self) -> Vec2 { self.a.mid(self.b) } /// Parameter (0..1 on the segment) of the projection of `p`. - #[must_use] pub fn param_of(&self, p: Vec2) -> f64 { let d = self.b - self.a; let l2 = d.len2(); if l2 <= EPS * EPS { 0.0 } else { (p - self.a).dot(d) / l2 } } - #[must_use] pub fn at(&self, t: f64) -> Vec2 { self.a.lerp(self.b, t) } /// Closest point on the segment. - #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { self.at(self.param_of(p).clamp(0.0, 1.0)) } /// Foot of the perpendicular on the infinite line. - #[must_use] pub fn project(&self, p: Vec2) -> Vec2 { self.at(self.param_of(p)) } - #[must_use] pub fn dist(&self, p: Vec2) -> f64 { self.closest(p).dist(p) } /// Signed side: > 0 left of a→b. - #[must_use] pub fn side(&self, p: Vec2) -> f64 { (self.b - self.a).cross(p - self.a) } - #[must_use] pub fn offset(&self, d: f64) -> Line { let n = (self.b - self.a).normalized().perp() * d; Line::new(self.a + n, self.b + n) @@ -73,41 +62,32 @@ pub struct Arc { } impl Arc { - #[must_use] pub fn new(center: Vec2, radius: f64, start: f64, end: f64) -> Self { Arc { center, radius: radius.abs(), start: norm_angle(start), end: norm_angle(end) } } - #[must_use] pub fn sweep(&self) -> f64 { ccw_sweep(self.start, self.end) } - #[must_use] pub fn start_point(&self) -> Vec2 { Vec2::polar(self.center, self.radius, self.start) } - #[must_use] pub fn end_point(&self) -> Vec2 { Vec2::polar(self.center, self.radius, self.end) } - #[must_use] pub fn mid_point(&self) -> Vec2 { Vec2::polar(self.center, self.radius, self.start + self.sweep() / 2.0) } - #[must_use] pub fn len(&self) -> f64 { self.radius * self.sweep() } - #[must_use] pub fn contains_angle(&self, a: f64) -> bool { angle_in_sweep(a, self.start, self.end) } /// Point at parameter `t` in 0..1 along the sweep. - #[must_use] pub fn at(&self, t: f64) -> Vec2 { Vec2::polar(self.center, self.radius, self.start + self.sweep() * t) } /// Arc through three points, or `None` when collinear. - #[must_use] pub fn from_3_points(p1: Vec2, p2: Vec2, p3: Vec2) -> Option { let c = Circle::from_3_points(p1, p2, p3)?; let a1 = c.center.angle_to(p1); @@ -117,11 +97,9 @@ impl Arc { if angle_in_sweep(a2, a1, a3) { Some(Arc::new(c.center, c.radius, a1, a3)) } else { Some(Arc::new(c.center, c.radius, a3, a1)) } } /// Arc from start point, center and end point (CCW). - #[must_use] pub fn from_start_center_end(s: Vec2, c: Vec2, e: Vec2) -> Arc { Arc::new(c, s.dist(c), c.angle_to(s), c.angle_to(e)) } - #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { let a = self.center.angle_to(p); if self.contains_angle(a) && p.dist(self.center) > EPS { @@ -132,7 +110,6 @@ impl Arc { if s.dist(p) <= e.dist(p) { s } else { e } } } - #[must_use] pub fn bounds(&self) -> Bounds2 { let mut b = Bounds2::from_points([self.start_point(), self.end_point()]); for k in 0..4 { @@ -161,11 +138,9 @@ pub struct Circle { } impl Circle { - #[must_use] pub fn new(center: Vec2, radius: f64) -> Self { Circle { center, radius: radius.abs() } } - #[must_use] pub fn from_3_points(p1: Vec2, p2: Vec2, p3: Vec2) -> Option { // Work in point-relative coordinates. Absolute coordinate squares lose the small // differences between points in drawings far from the origin. @@ -191,16 +166,13 @@ impl Circle { } Some(Circle::new(c, radius)) } - #[must_use] pub fn from_2_points(p1: Vec2, p2: Vec2) -> Circle { Circle::new(p1.mid(p2), p1.dist(p2) / 2.0) } - #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { let d = p - self.center; if d.len() < EPS { self.center + Vec2::X * self.radius } else { self.center + d.normalized() * self.radius } } - #[must_use] pub fn bounds(&self) -> Bounds2 { Bounds2::new(self.center - Vec2::new(self.radius, self.radius), self.center + Vec2::new(self.radius, self.radius)) } @@ -208,7 +180,6 @@ impl Circle { Arc { center: self.center, radius: self.radius, start: 0.0, end: TAU }.tessellate(tol, out); } /// Tangent points from external point `p`. - #[must_use] pub fn tangent_points(&self, p: Vec2) -> Vec { let d = p.dist(self.center); if d <= self.radius + EPS { @@ -222,7 +193,6 @@ impl Circle { /// up to two outer (belt) tangents and two inner (crossed) tangents. Empty for concentric /// circles or when one circle lies inside the other; tangents that touch both circles at the /// same point (circles touching each other) are left out. - #[must_use] #[expect(clippy::many_single_char_names, reason = "Circle-tangent equations use conventional r/v/d/u/c/h/n/p/q notation.")] pub fn common_tangents(&self, other: &Circle) -> Vec<(Vec2, Vec2)> { let (r1, r2) = (self.radius, other.radius); @@ -264,23 +234,18 @@ pub struct Ellipse { } impl Ellipse { - #[must_use] pub fn full(center: Vec2, major: Vec2, ratio: f64) -> Self { Ellipse { center, major, ratio, start: 0.0, end: TAU } } - #[must_use] pub fn is_full(&self) -> bool { (ccw_sweep(self.start, self.end) - TAU).abs() < 1e-9 } - #[must_use] pub fn minor(&self) -> Vec2 { self.major.perp() * self.ratio } - #[must_use] pub fn at_param(&self, t: f64) -> Vec2 { self.center + self.major * t.cos() + self.minor() * t.sin() } - #[must_use] pub fn sweep(&self) -> f64 { ccw_sweep(self.start, self.end) } @@ -310,7 +275,6 @@ impl Ellipse { out.push(self.at_param(self.start + sweep * i as f64 / n as f64)); } } - #[must_use] pub fn bounds(&self) -> Bounds2 { // Sampled bounds can cut off the true extrema, especially on a small arc or // a large drawing. The derivative of each coordinate gives two exact @@ -325,7 +289,6 @@ impl Ellipse { bounds } /// Parameter of the point on the ellipse nearest the direction of `p` (approximate). - #[must_use] pub fn param_of(&self, p: Vec2) -> f64 { let ma = self.major.len(); if ma < EPS { @@ -338,7 +301,6 @@ impl Ellipse { let mb = ma * self.ratio; norm_angle((y / mb.max(EPS)).atan2(x / ma)) } - #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { let mut pts = Vec::new(); self.tessellate(self.major.len() * 1e-3, &mut pts); @@ -373,7 +335,6 @@ pub enum Segment { } impl Segment { - #[must_use] pub fn start(&self) -> Vec2 { match self { Segment::Line(l) => l.a, @@ -381,7 +342,6 @@ impl Segment { Segment::Arc { arc, ccw: false } => arc.end_point(), } } - #[must_use] pub fn end(&self) -> Vec2 { match self { Segment::Line(l) => l.b, @@ -389,28 +349,24 @@ impl Segment { Segment::Arc { arc, ccw: false } => arc.start_point(), } } - #[must_use] pub fn len(&self) -> f64 { match self { Segment::Line(l) => l.len(), Segment::Arc { arc, .. } => arc.len(), } } - #[must_use] pub fn mid(&self) -> Vec2 { match self { Segment::Line(l) => l.mid(), Segment::Arc { arc, .. } => arc.mid_point(), } } - #[must_use] pub fn closest(&self, p: Vec2) -> Vec2 { match self { Segment::Line(l) => l.closest(p), Segment::Arc { arc, .. } => arc.closest(p), } } - #[must_use] pub fn bounds(&self) -> Bounds2 { match self { Segment::Line(l) => Bounds2::new(l.a, l.b), @@ -434,7 +390,6 @@ impl Segment { } } /// Point at parameter `t` (0..1) in segment direction. - #[must_use] pub fn at(&self, t: f64) -> Vec2 { match self { Segment::Line(l) => l.at(t), @@ -442,7 +397,6 @@ impl Segment { Segment::Arc { arc, ccw: false } => arc.at(1.0 - t), } } - #[must_use] pub fn reversed(&self) -> Segment { match *self { Segment::Line(l) => Segment::Line(Line::new(l.b, l.a)), @@ -450,7 +404,6 @@ impl Segment { } } /// Tangent direction (unit) at parameter t. - #[must_use] pub fn tangent(&self, t: f64) -> Vec2 { match self { Segment::Line(l) => l.dir(), @@ -462,7 +415,6 @@ impl Segment { } } /// Offset by `d` to the left of travel direction. `None` if an arc collapses. - #[must_use] pub fn offset(&self, d: f64) -> Option { match *self { Segment::Line(l) => Some(Segment::Line(l.offset(d))), @@ -491,18 +443,15 @@ pub struct PolyVertex { } impl PolyVertex { - #[must_use] pub fn new(p: Vec2) -> Self { PolyVertex { p, ..Default::default() } } - #[must_use] pub fn with_bulge(p: Vec2, bulge: f64) -> Self { PolyVertex { p, bulge, ..Default::default() } } } /// Convert a bulge segment to an arc. `None` for a straight (zero-bulge or degenerate) segment. -#[must_use] pub fn bulge_to_arc(a: Vec2, b: Vec2, bulge: f64) -> Option<(Arc, bool)> { if bulge.abs() < 1e-12 || !bulge.is_finite() || a.near(b, EPS) { return None; @@ -527,7 +476,6 @@ pub fn bulge_to_arc(a: Vec2, b: Vec2, bulge: f64) -> Option<(Arc, bool)> { } /// Bulge for an arc traversed from `a` to `b` with the given sweep (signed: + = CCW). -#[must_use] pub fn arc_to_bulge(signed_sweep: f64) -> f64 { (signed_sweep / 4.0).tan() } @@ -543,12 +491,10 @@ pub struct Polyline { pub const MAX_TESSELLATED_POINTS: usize = 4_000_000; impl Polyline { - #[must_use] pub fn from_points(pts: &[Vec2], closed: bool) -> Self { Polyline { vertices: pts.iter().map(|p| PolyVertex::new(*p)).collect(), closed } } /// The segments, including the closing segment when closed. - #[must_use] pub fn segments(&self) -> Vec { let n = self.vertices.len(); let mut out = Vec::with_capacity(n); @@ -568,7 +514,6 @@ impl Polyline { pub fn len(&self) -> f64 { self.segments().iter().map(Segment::len).sum() } - #[must_use] pub fn bounds(&self) -> Bounds2 { let mut b = Bounds2::from_points(self.vertices.iter().map(|v| v.p)); for s in self.segments() { @@ -576,7 +521,6 @@ impl Polyline { } b } - #[must_use] pub fn tessellate(&self, tol: f64) -> Vec { let mut budget = MAX_TESSELLATED_POINTS; self.tessellate_within(tol, &mut budget) @@ -605,7 +549,6 @@ impl Polyline { out } /// Signed area (CCW positive) of a closed polyline including bulge areas. - #[must_use] pub fn area(&self) -> f64 { // Integrate the chords exactly and add the signed circular-segment area // for every bulge. A tessellated shoelace loses precision on large arcs. @@ -633,7 +576,6 @@ impl Polyline { } twice_area / 2.0 } - #[must_use] pub fn closest(&self, p: Vec2) -> Option { let mut best: Option<(f64, Vec2)> = None; for s in self.segments() { @@ -646,7 +588,6 @@ impl Polyline { best.map(|(_, c)| c).or_else(|| self.vertices.first().map(|v| v.p)) } /// True if `p` is inside a closed polyline (even-odd on the tessellation). - #[must_use] pub fn contains(&self, p: Vec2) -> bool { point_in_polygon(&self.tessellate(1e-3), p) } @@ -685,13 +626,11 @@ impl Polyline { } /// Area centroid of a closed polygon. `None` at zero area. -#[must_use] pub fn polygon_centroid(pts: &[Vec2]) -> Option { Polyline::from_points(pts, true).centroid() } /// Signed polygon area (CCW positive). -#[must_use] pub fn shoelace(pts: &[Vec2]) -> f64 { let n = pts.len(); if n < 3 { @@ -712,7 +651,6 @@ pub fn shoelace(pts: &[Vec2]) -> f64 { } /// Even-odd point-in-polygon test. -#[must_use] pub fn point_in_polygon(poly: &[Vec2], p: Vec2) -> bool { let n = poly.len(); if n < 3 { diff --git a/crates/geom/src/fillet.rs b/crates/geom/src/fillet.rs index 74b06385b..bf5214cd7 100644 --- a/crates/geom/src/fillet.rs +++ b/crates/geom/src/fillet.rs @@ -49,7 +49,6 @@ struct Range { impl TanCurve { /// Point at parameter `t`. - #[must_use] pub fn point(&self, t: f64) -> Vec2 { match self { TanCurve::Line(l) => l.a + (l.b - l.a) * t, @@ -60,7 +59,6 @@ impl TanCurve { } /// First derivative at parameter `t`. - #[must_use] pub fn derivative(&self, t: f64) -> Vec2 { match self { TanCurve::Line(l) => l.b - l.a, @@ -240,7 +238,6 @@ fn refine(c1: &TanCurve, r1: &Range, d1: f64, c2: &TanCurve, r2: &Range, d2: f64 /// Circles of radius `r` tangent to both curves (`r = 0`: the points where they cross). `near` /// (the pick points) widens the search window for lines. Every distinct solution is returned; /// callers choose one, usually the nearest the picks. -#[must_use] pub fn tangent_circles(c1: &TanCurve, c2: &TanCurve, r: f64, near: &[Vec2]) -> Vec { if !(r.is_finite() && r >= 0.0) { return Vec::new(); diff --git a/crates/geom/src/intersect.rs b/crates/geom/src/intersect.rs index 4e7714b6e..12f1b2e9a 100644 --- a/crates/geom/src/intersect.rs +++ b/crates/geom/src/intersect.rs @@ -1,7 +1,6 @@ use crate::{Arc, Circle, EPS, Line, Segment, Vec2}; /// Intersection of two infinite lines through (a1,a2) and (b1,b2), with parameters on each. -#[must_use] pub fn line_line_infinite(a1: Vec2, a2: Vec2, b1: Vec2, b2: Vec2) -> Option<(Vec2, f64, f64)> { let r = a2 - a1; let s = b2 - b1; @@ -15,7 +14,6 @@ pub fn line_line_infinite(a1: Vec2, a2: Vec2, b1: Vec2, b2: Vec2) -> Option<(Vec } /// Intersection of two finite segments. -#[must_use] #[expect(clippy::many_single_char_names, reason = "Segment endpoints and parameters use conventional a/b/p/t/u geometric notation.")] pub fn line_line(a: &Line, b: &Line) -> Option { let (p, t, u) = line_line_infinite(a.a, a.b, b.a, b.b)?; @@ -24,7 +22,6 @@ pub fn line_line(a: &Line, b: &Line) -> Option { } /// Intersections of the infinite line through `l` with a circle. Returns points with line params. -#[must_use] #[expect(clippy::many_single_char_names, reason = "The line/circle quadratic uses conventional a/d/f/t mathematical notation.")] pub fn line_circle(l: &Line, c: &Circle) -> Vec<(Vec2, f64)> { let d = l.b - l.a; @@ -57,7 +54,6 @@ pub fn line_circle(l: &Line, c: &Circle) -> Vec<(Vec2, f64)> { } /// Intersections of two full circles. -#[must_use] pub fn circle_circle(c1: &Circle, c2: &Circle) -> Vec { let delta = c2.center - c1.center; let d = delta.len(); @@ -107,14 +103,12 @@ fn on_arc(a: &Arc, p: Vec2) -> bool { } /// Intersections between two segments (finite). -#[must_use] pub fn intersect_segments(s1: &Segment, s2: &Segment) -> Vec { intersect_segments_ext(s1, s2, false) } /// Intersections; with `extend` true, lines are infinite and arcs are full circles /// (used by TRIM/EXTEND edge mode and apparent intersections). -#[must_use] pub fn intersect_segments_ext(s1: &Segment, s2: &Segment, extend: bool) -> Vec { let tol = 1e-9; match (s1, s2) { diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 40b47d6d5..bc320f584 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -1,4 +1,4 @@ -//! `CADCraft` geometry: double-precision 2D/3D math for drafting. +//! CADCraft geometry: double-precision 2D/3D math for drafting. //! //! Everything a CAD kernel needs below the document model: vectors and affine transforms, //! bounding boxes, angles, lines, circular arcs (and polyline bulges), ellipses, NURBS splines, @@ -36,7 +36,6 @@ pub const TAU: f64 = std::f64::consts::TAU; pub const PI: f64 = std::f64::consts::PI; /// Normalize an angle to `[0, 2π)`. -#[must_use] pub fn norm_angle(a: f64) -> f64 { if !a.is_finite() { return 0.0; @@ -46,31 +45,26 @@ pub fn norm_angle(a: f64) -> f64 { } /// Counter-clockwise sweep from `start` to `end`, in `(0, 2π]`. -#[must_use] pub fn ccw_sweep(start: f64, end: f64) -> f64 { let s = norm_angle(end - start); if s <= EPS { TAU } else { s } } /// True when angle `a` lies on the CCW sweep from `start` to `end` (inclusive, with tolerance). -#[must_use] pub fn angle_in_sweep(a: f64, start: f64, end: f64) -> bool { let sweep = ccw_sweep(start, end); let d = norm_angle(a - start); d <= sweep + 1e-12 || (TAU - d) < 1e-12 } -#[must_use] pub fn deg(r: f64) -> f64 { r.to_degrees() } -#[must_use] pub fn rad(d: f64) -> f64 { d.to_radians() } /// Number of segments needed to approximate an arc of `radius` and `sweep` within `tol`. -#[must_use] #[expect( clippy::cast_possible_truncation, clippy::cast_sign_loss, diff --git a/crates/geom/src/mat.rs b/crates/geom/src/mat.rs index ec7a2075b..374712fc1 100644 --- a/crates/geom/src/mat.rs +++ b/crates/geom/src/mat.rs @@ -22,30 +22,24 @@ impl Default for Mat3 { impl Mat3 { pub const IDENTITY: Mat3 = Mat3 { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0 }; - #[must_use] pub fn translate(v: Vec2) -> Mat3 { Mat3 { e: v.x, f: v.y, ..Mat3::IDENTITY } } - #[must_use] pub fn scale(sx: f64, sy: f64) -> Mat3 { Mat3 { a: sx, d: sy, ..Mat3::IDENTITY } } - #[must_use] pub fn rotate(angle: f64) -> Mat3 { let (s, c) = angle.sin_cos(); Mat3 { a: c, b: s, c: -s, d: c, e: 0.0, f: 0.0 } } /// Scale about `base`. - #[must_use] pub fn scale_about(base: Vec2, s: f64) -> Mat3 { Mat3::translate(base).then_before(Mat3::scale(s, s)).then_before(Mat3::translate(-base)) } - #[must_use] pub fn rotate_about(base: Vec2, angle: f64) -> Mat3 { Mat3::translate(base).then_before(Mat3::rotate(angle)).then_before(Mat3::translate(-base)) } /// Reflection across the line through `p1`, `p2`. - #[must_use] pub fn mirror(p1: Vec2, p2: Vec2) -> Mat3 { let d = (p2 - p1).normalized(); if d == Vec2::ZERO { @@ -56,7 +50,6 @@ impl Mat3 { Mat3::translate(p1).then_before(r).then_before(Mat3::translate(-p1)) } /// `self * o`: apply `o` first, then `self`. - #[must_use] pub fn then_before(self, o: Mat3) -> Mat3 { Mat3 { a: self.a * o.a + self.c * o.b, @@ -68,23 +61,18 @@ impl Mat3 { } } /// Apply `self` first, then `o`. - #[must_use] pub fn then(self, o: Mat3) -> Mat3 { o.then_before(self) } - #[must_use] pub fn apply(&self, p: Vec2) -> Vec2 { Vec2::new(self.a * p.x + self.c * p.y + self.e, self.b * p.x + self.d * p.y + self.f) } - #[must_use] pub fn apply_vec(&self, v: Vec2) -> Vec2 { Vec2::new(self.a * v.x + self.c * v.y, self.b * v.x + self.d * v.y) } - #[must_use] pub fn det(&self) -> f64 { self.a * self.d - self.b * self.c } - #[must_use] #[expect(clippy::many_single_char_names, reason = "Matrix coefficients use the same a–f notation as Mat3 and the affine-transform formula.")] pub fn inverse(&self) -> Option { let det = self.det(); @@ -101,16 +89,13 @@ impl Mat3 { Some(Mat3 { a, b, c, d, e, f }) } /// Uniform scale factor (geometric mean of the axis scales). - #[must_use] pub fn scale_factor(&self) -> f64 { self.det().abs().sqrt() } /// Rotation angle of the transformed X axis. - #[must_use] pub fn rotation(&self) -> f64 { crate::norm_angle(self.b.atan2(self.a)) } - #[must_use] pub fn is_mirroring(&self) -> bool { self.det() < 0.0 } @@ -138,7 +123,6 @@ impl Default for Mat4 { impl Mat4 { pub const IDENTITY: Mat4 = Mat4 { m: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] }; - #[must_use] pub fn mul(&self, o: &Mat4) -> Mat4 { let mut r = [[0.0; 4]; 4]; for (i, row) in r.iter_mut().enumerate() { @@ -148,7 +132,6 @@ impl Mat4 { } Mat4 { m: r } } - #[must_use] pub fn apply(&self, p: Vec3) -> Vec3 { let m = &self.m; let w = m[3][0] * p.x + m[3][1] * p.y + m[3][2] * p.z + m[3][3]; @@ -159,12 +142,10 @@ impl Mat4 { (m[2][0] * p.x + m[2][1] * p.y + m[2][2] * p.z + m[2][3]) / w, ) } - #[must_use] pub fn from_mat3(t: &Mat3) -> Mat4 { Mat4 { m: [[t.a, t.c, 0.0, t.e], [t.b, t.d, 0.0, t.f], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] } } /// The "arbitrary axis algorithm" frame for an extrusion direction (DXF OCS → WCS). - #[must_use] pub fn ocs(normal: Vec3) -> Mat4 { let n = normal.normalized(); if n == Vec3::ZERO || (n.x.abs() < 1e-12 && n.y.abs() < 1e-12 && n.z > 0.0) { diff --git a/crates/geom/src/nurbs.rs b/crates/geom/src/nurbs.rs index 2c8e070f5..4d2e9a5a9 100644 --- a/crates/geom/src/nurbs.rs +++ b/crates/geom/src/nurbs.rs @@ -128,7 +128,6 @@ impl Spline { } /// True when the spline carries weights (a NURBS rather than a plain B-spline). - #[must_use] pub fn is_rational(&self) -> bool { !self.weights.is_empty() } @@ -155,7 +154,6 @@ impl Spline { } /// First derivative dC/dt (zero on an invalid spline). - #[must_use] pub fn derivative(&self, t: f64) -> Vec2 { if !self.is_valid() { return Vec2::ZERO; @@ -216,7 +214,6 @@ impl Spline { /// Unit tangent at `t` in the direction of increasing parameter; a central difference stands /// in where the derivative vanishes. Zero when the curve does not move at all. - #[must_use] pub fn unit_tangent(&self, t: f64) -> Vec2 { let d = self.derivative(t).normalized(); if d != Vec2::ZERO { @@ -229,7 +226,6 @@ impl Spline { /// Insert knot `t` once (Boehm's algorithm, in homogeneous coordinates). The result has no /// fit data and is open. - #[must_use] #[expect(clippy::many_single_char_names, reason = "Boehm knot insertion keeps the standard p/n/k/i/h/a equation notation.")] pub fn insert_knot(&self, t: f64) -> Option { if !self.is_valid() || !t.is_finite() || self.control.len() >= MAX_EDIT_CONTROL { @@ -298,7 +294,6 @@ impl Spline { } /// Split at parameter `t` into (before, after). `None` at the ends or on invalid input. - #[must_use] pub fn split_at(&self, t: f64) -> Option<(Spline, Spline)> { let (lo, hi) = self.domain(); if !(t > lo + 1e-12 && t < hi - 1e-12) { @@ -309,7 +304,6 @@ impl Spline { } /// The open piece between parameters `a < b`. - #[must_use] pub fn sub_between(&self, a: f64, b: f64) -> Option { let (lo, hi) = self.domain(); let mut s = self.clone(); @@ -326,7 +320,6 @@ impl Spline { /// The same curve with clamped ends (end knots repeated degree + 1 times), so it starts and /// ends on its first and last control points. Fit data is dropped. - #[must_use] pub fn clamped(&self) -> Option { if !self.is_valid() { return None; @@ -349,7 +342,6 @@ impl Spline { /// Reversed direction: control points, weights, fit points and knots (and the fit end /// tangents swap ends and turn round). - #[must_use] pub fn reversed(&self) -> Spline { let (lo, hi) = (self.knots.first().copied().unwrap_or(0.0), self.knots.last().copied().unwrap_or(1.0)); Spline { @@ -402,7 +394,6 @@ impl Spline { } /// The same curve at a higher (or equal) degree, clamped. - #[must_use] pub fn elevated(&self, degree: usize) -> Option { if degree < self.degree || degree > MAX_EDIT_DEGREE { return None; @@ -428,7 +419,6 @@ impl Spline { /// point becomes their midpoint). Degrees are matched by elevation, weights rescaled so the /// junction carries one weight, and `other`'s parameters follow on at a similar speed. The /// junction is a knot of multiplicity `degree`, so the curve passes through it exactly. - #[must_use] #[expect( clippy::many_single_char_names, reason = "Spline joining keeps the two curves, homogeneous points and knot spans in standard short notation." @@ -461,7 +451,6 @@ impl Spline { /// A straight line from `a` to `b` as a clamped spline of `degree` (evenly spaced control /// points, parameter = distance). - #[must_use] #[expect(clippy::cast_precision_loss, reason = "The degree is clamped by MAX_EDIT_DEGREE (25), so every control index is exact as f64.")] pub fn from_line(a: Vec2, b: Vec2, degree: usize) -> Spline { let p = degree.clamp(1, MAX_EDIT_DEGREE); @@ -476,7 +465,6 @@ impl Spline { /// The elliptical arc `center + u·cos θ + v·sin θ` for θ from `start` over `sweep` (negative /// runs clockwise) as an exact rational quadratic spline, in pieces of at most a quarter /// turn. Circular arcs are the case `|u| = |v|`, `u ⟂ v`. - #[must_use] #[expect( clippy::cast_precision_loss, clippy::cast_possible_truncation, @@ -513,7 +501,6 @@ impl Spline { } /// An ellipse or elliptical arc as an exact rational spline (counter-clockwise). - #[must_use] pub fn from_ellipse(e: &Ellipse) -> Option { let s = Spline::from_conic_arc(e.center, e.major, e.minor(), e.start, e.sweep())?; Some(Spline { closed: e.is_full(), ..s }) @@ -521,7 +508,6 @@ impl Spline { /// Run the spline on in a straight line along its end tangent by `dist` > 0: past the end /// (`at_end`) or before the start. The result is clamped, open and has no fit data. - #[must_use] pub fn extended(&self, at_end: bool, dist: f64) -> Option { if !(dist.is_finite() && dist > 0.0) || self.closed { return None; @@ -564,14 +550,12 @@ impl Spline { } /// Arc length between parameters `a` and `b` (adaptive Gauss–Legendre over each knot span). - #[must_use] pub fn length_between(&self, a: f64, b: f64) -> f64 { let l = self.integrated_length(a, b); if l.is_finite() { l } else { 0.0 } } /// Arc length of the whole spline. - #[must_use] pub fn length(&self) -> f64 { let (lo, hi) = self.domain(); self.length_between(lo, hi) @@ -598,7 +582,6 @@ impl Spline { /// The parameter `len` along the curve from parameter `from` (forward for positive `len`, /// backward for negative), clamped to the domain. - #[must_use] pub fn param_at_length(&self, from: f64, len: f64) -> f64 { let (lo, hi) = self.domain(); if !self.is_valid() { @@ -641,13 +624,11 @@ impl Spline { impl Ellipse { /// dP/dθ at parameter `t`. - #[must_use] pub fn derivative(&self, t: f64) -> Vec2 { self.minor() * t.cos() - self.major * t.sin() } /// Arc length from parameter `t0` counter-clockwise over `sweep` (radians, >= 0). - #[must_use] #[expect( clippy::cast_precision_loss, clippy::cast_possible_truncation, @@ -672,14 +653,12 @@ impl Ellipse { } /// Arc length of the ellipse or elliptical arc. - #[must_use] pub fn length(&self) -> f64 { self.arc_length_from(self.start, self.sweep()) } /// The parameter reached `len` along the ellipse from `t0`: counter-clockwise for positive /// `len`, clockwise for negative. `None` for a whole turn or more, or degenerate input. - #[must_use] pub fn param_at_length(&self, t0: f64, len: f64) -> Option { let full = self.arc_length_from(0.0, TAU); if !(t0.is_finite() && len.is_finite() && full > EPS) || len.abs() >= full { diff --git a/crates/geom/src/region.rs b/crates/geom/src/region.rs index 6c7578606..12ff47220 100644 --- a/crates/geom/src/region.rs +++ b/crates/geom/src/region.rs @@ -563,7 +563,6 @@ fn nearest_curve(polys: &[Vec], i: usize, e: Vec2, snap: f64, tol: f64, bu /// curve (which gains a vertex there), so the two meet exactly. A curve that is flattened /// into chords (an ellipse, a spline) lies up to the flattening tolerance off the true curve, /// so a line that ends on the true curve can stop just short of the chords. -#[must_use] #[expect(clippy::many_single_char_names, reason = "Endpoint snapping keeps conventional polyline, segment and point notation.")] pub fn snap_ends(polys: &[Vec], snap: f64, tol: f64) -> Vec> { let mut out: Vec> = polys.to_vec(); @@ -614,26 +613,22 @@ pub fn snap_ends(polys: &[Vec], snap: f64, tol: f64) -> Vec> { } /// The closed loop enclosing `p`, counter-clockwise, or `None`. -#[must_use] pub fn enclosing_loop(polys: &[Vec], p: Vec2, tol: f64) -> Option> { enclosing_loop_gap(polys, p, tol, 0.0) } /// [`enclosing_loop`], with gaps of up to `gap` between curve ends closed (HPGAPTOL). -#[must_use] pub fn enclosing_loop_gap(polys: &[Vec], p: Vec2, tol: f64, gap: f64) -> Option> { let g = build_gap(polys, tol, gap)?; points(&g, &outer_face(&g, p)?) } /// The closed loop enclosing `p` plus the islands inside it, or `None` when `p` isn't enclosed. -#[must_use] pub fn boundary_at(polys: &[Vec], p: Vec2, tol: f64) -> Option { boundary_at_gap(polys, p, tol, 0.0) } /// [`boundary_at`], with gaps of up to `gap` between curve ends closed (HPGAPTOL). -#[must_use] pub fn boundary_at_gap(polys: &[Vec], p: Vec2, tol: f64, gap: f64) -> Option { let g = build_gap(polys, tol, gap)?; let ids = outer_face(&g, p)?; @@ -649,7 +644,6 @@ pub fn boundary_at_gap(polys: &[Vec], p: Vec2, tol: f64, gap: f64) -> Opti /// 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). -#[must_use] #[expect(clippy::float_cmp, reason = "Exact x equality is required for the deterministic lexicographic tie-break.")] pub fn outline(polys: &[Vec], tol: f64, gap: f64) -> Option> { let g = build_gap(polys, tol, gap)?; diff --git a/crates/geom/src/spline.rs b/crates/geom/src/spline.rs index 8192cbb30..68e5d5b94 100644 --- a/crates/geom/src/spline.rs +++ b/crates/geom/src/spline.rs @@ -30,7 +30,6 @@ pub struct Spline { impl Spline { /// A clamped uniform spline over control points. - #[must_use] pub fn from_control(control: Vec, degree: usize) -> Spline { let n = control.len(); let degree = degree.clamp(1, n.saturating_sub(1).max(1)); @@ -40,7 +39,6 @@ impl Spline { /// Cubic interpolation through fit points (chord-length parametrisation, natural-ish ends /// via a clamped knot vector: solve the banded system for control points). - #[must_use] pub fn from_fit_points(fit: &[Vec2]) -> Spline { Spline::fit_with(fit, false, FitOptions::default()) } @@ -49,24 +47,20 @@ impl Spline { /// include the closing chord; the knot vector is the periodic (unclamped) extension and the /// first `degree` control points repeat at the end, so the curve has continuous tangent and /// curvature at the seam. A repeated closing fit point is dropped. - #[must_use] pub fn from_fit_points_closed(fit: &[Vec2]) -> Spline { Spline::fit_with(fit, true, FitOptions::default()) } /// Interpolation through fit points, open or closed (see `from_fit_points_closed`). - #[must_use] pub fn from_fit(fit: &[Vec2], closed: bool) -> Spline { Spline::fit_with(fit, closed, FitOptions::default()) } /// Closed with an unclamped (periodic) knot vector, as DXF flags it (group 70 bit 2). - #[must_use] pub fn is_periodic(&self) -> bool { self.closed && self.knots.first() != self.knots.get(self.degree) } - #[must_use] pub fn is_valid(&self) -> bool { let n = self.control.len(); n > self.degree @@ -76,7 +70,6 @@ impl Spline { && self.knots.windows(2).all(|w| w.first() <= w.get(1)) } - #[must_use] pub fn domain(&self) -> (f64, f64) { let lo = self.knots.get(self.degree).copied().unwrap_or(0.0); let hi = self.knots.get(self.control.len()).copied().unwrap_or(1.0); @@ -84,7 +77,6 @@ impl Spline { } /// Evaluate at parameter `t` (de Boor via basis functions). - #[must_use] pub fn eval(&self, t: f64) -> Vec2 { if !self.is_valid() { return self.control.first().copied().unwrap_or_default(); @@ -122,7 +114,6 @@ impl Spline { if wsum.abs() > 1e-300 { p / wsum } else { p } } - #[must_use] pub fn tessellate(&self, tol: f64) -> Vec { if !self.is_valid() { return self.control.clone(); @@ -175,7 +166,6 @@ impl Spline { /// is its control polygon, so its control box is exact; a degenerate spline gets its control /// box, which contains the curve (the box of the finite control points when one is not /// finite: `hull` skips it, but it would poison every sample). - #[must_use] #[expect( clippy::cast_precision_loss, clippy::cast_possible_truncation, diff --git a/crates/geom/src/spline_fit.rs b/crates/geom/src/spline_fit.rs index f3ead5099..720488e4e 100644 --- a/crates/geom/src/spline_fit.rs +++ b/crates/geom/src/spline_fit.rs @@ -24,7 +24,6 @@ impl KnotParam { pub const ALL: [KnotParam; 3] = [KnotParam::Chord, KnotParam::SqrtChord, KnotParam::Uniform]; /// The name as the prompt and the "Current settings" line show it. - #[must_use] pub fn name(self) -> &'static str { match self { KnotParam::Chord => "Chord", @@ -35,7 +34,6 @@ impl KnotParam { /// Parse a keyword or JSON value ("chord", "sqrt", "square root", "uniform", or 0/1/2 as in /// the SPLKNOTS setting). - #[must_use] pub fn parse(s: &str) -> Option { Some(match s.trim().to_ascii_lowercase().as_str() { "c" | "chord" | "0" => KnotParam::Chord, @@ -46,7 +44,6 @@ impl KnotParam { } /// The SPLKNOTS code (0 chord, 1 square root, 2 uniform). - #[must_use] pub fn code(self) -> i64 { match self { KnotParam::Chord => 0, @@ -84,7 +81,6 @@ pub struct FitOptions { impl FitOptions { /// Normalised tangents (zero or non-finite directions dropped) and a finite, non-negative /// tolerance: what a spline stores. - #[must_use] pub fn sanitized(self) -> FitOptions { let dir = |t: Option| t.filter(|v| v.x.is_finite() && v.y.is_finite() && v.len() > 1e-12).map(Vec2::normalized); FitOptions { @@ -111,7 +107,6 @@ impl Spline { /// control points. A fit point given twice in a row is a kink (SPLINEDIT Fit data Kink): the /// curve passes through it with a corner (a knot of full multiplicity) and the pieces on /// either side are fitted on their own. - #[must_use] pub fn fit_with(fit: &[Vec2], closed: bool, opts: FitOptions) -> Spline { let opts = opts.sanitized(); let kinked = if fit.len() <= MAX_KINK_POINTS { kinked_fit(fit, closed, opts) } else { None }; @@ -131,7 +126,6 @@ impl Spline { } /// Rebuild from new fit points with this spline's knot parametrisation, tangents and tolerance. - #[must_use] pub fn refit(&self, fit: &[Vec2], closed: bool) -> Spline { Spline::fit_with(fit, closed, self.fit_opts) } @@ -139,7 +133,6 @@ impl Spline { /// Which knot parametrisation produced this spline's knots from its fit points (DXF files /// keep the knots but not the parametrisation). Compares knot vectors only (no solving), so /// it is cheap for any number of fit points. Chord when nothing matches. - #[must_use] pub fn infer_knot_param(&self) -> KnotParam { if self.fit.len() < 3 { return self.fit_opts.knots; diff --git a/crates/geom/src/vec.rs b/crates/geom/src/vec.rs index d21359e69..ba0f358e2 100644 --- a/crates/geom/src/vec.rs +++ b/crates/geom/src/vec.rs @@ -14,100 +14,78 @@ impl Vec2 { pub const X: Vec2 = Vec2 { x: 1.0, y: 0.0 }; pub const Y: Vec2 = Vec2 { x: 0.0, y: 1.0 }; - #[must_use] pub const fn new(x: f64, y: f64) -> Self { Vec2 { x, y } } /// Unit vector at `angle` radians. - #[must_use] pub fn from_angle(angle: f64) -> Self { Vec2::new(angle.cos(), angle.sin()) } - #[must_use] pub fn polar(center: Vec2, radius: f64, angle: f64) -> Self { center + Vec2::from_angle(angle) * radius } - #[must_use] pub fn dot(self, o: Vec2) -> f64 { self.x * o.x + self.y * o.y } /// z of the 3D cross product. - #[must_use] pub fn cross(self, o: Vec2) -> f64 { self.x * o.y - self.y * o.x } - #[must_use] pub fn len(self) -> f64 { self.x.hypot(self.y) } - #[must_use] pub fn len2(self) -> f64 { self.dot(self) } - #[must_use] pub fn dist(self, o: Vec2) -> f64 { (self - o).len() } - #[must_use] pub fn angle(self) -> f64 { crate::norm_angle(self.y.atan2(self.x)) } - #[must_use] pub fn angle_to(self, o: Vec2) -> f64 { (o - self).angle() } /// Unit vector, or zero for a zero-length vector. - #[must_use] pub fn normalized(self) -> Vec2 { let l = self.len(); if l > crate::EPS { self / l } else { Vec2::ZERO } } /// Rotated 90° counter-clockwise. - #[must_use] pub fn perp(self) -> Vec2 { Vec2::new(-self.y, self.x) } - #[must_use] pub fn rotate(self, a: f64) -> Vec2 { let (s, c) = a.sin_cos(); Vec2::new(self.x * c - self.y * s, self.x * s + self.y * c) } - #[must_use] pub fn rotate_about(self, center: Vec2, a: f64) -> Vec2 { center + (self - center).rotate(a) } - #[must_use] pub fn lerp(self, o: Vec2, t: f64) -> Vec2 { self + (o - self) * t } - #[must_use] pub fn mid(self, o: Vec2) -> Vec2 { Vec2::new(self.x.midpoint(o.x), self.y.midpoint(o.y)) } - #[must_use] pub fn is_finite(self) -> bool { self.x.is_finite() && self.y.is_finite() } - #[must_use] pub fn near(self, o: Vec2, tol: f64) -> bool { // Squaring very large finite values can overflow on both sides and make // unrelated points compare equal (infinity <= infinity). tol.is_finite() && tol >= 0.0 && self.dist(o) <= tol } - #[must_use] pub fn to3(self, z: f64) -> Vec3 { Vec3::new(self.x, self.y, z) } - #[must_use] pub fn min(self, o: Vec2) -> Vec2 { Vec2::new(self.x.min(o.x), self.y.min(o.y)) } - #[must_use] pub fn max(self, o: Vec2) -> Vec2 { Vec2::new(self.x.max(o.x), self.y.max(o.y)) } /// Mirror across the infinite line through `a` and `b`. - #[must_use] pub fn mirror(self, a: Vec2, b: Vec2) -> Vec2 { let d = (b - a).normalized(); if d == Vec2::ZERO { @@ -173,33 +151,26 @@ pub struct Vec3 { impl Vec3 { pub const ZERO: Vec3 = Vec3 { x: 0.0, y: 0.0, z: 0.0 }; pub const Z: Vec3 = Vec3 { x: 0.0, y: 0.0, z: 1.0 }; - #[must_use] pub const fn new(x: f64, y: f64, z: f64) -> Self { Vec3 { x, y, z } } - #[must_use] pub fn xy(self) -> Vec2 { Vec2::new(self.x, self.y) } - #[must_use] pub fn dot(self, o: Vec3) -> f64 { self.x * o.x + self.y * o.y + self.z * o.z } - #[must_use] pub fn cross(self, o: Vec3) -> Vec3 { Vec3::new(self.y * o.z - self.z * o.y, self.z * o.x - self.x * o.z, self.x * o.y - self.y * o.x) } - #[must_use] pub fn len(self) -> f64 { // Avoid overflowing the squared components of large finite vectors. self.x.hypot(self.y).hypot(self.z) } - #[must_use] pub fn normalized(self) -> Vec3 { let l = self.len(); if l > crate::EPS { self * (1.0 / l) } else { Vec3::ZERO } } - #[must_use] pub fn is_finite(self) -> bool { self.x.is_finite() && self.y.is_finite() && self.z.is_finite() } From fefb973754d67cbf9bb34b3b9eade45749eab1b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Tue, 3 Nov 2026 14:13:43 +0100 Subject: [PATCH 4/4] fix(geom): move NURBS lint expectations to velocity --- crates/geom/src/nurbs.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/geom/src/nurbs.rs b/crates/geom/src/nurbs.rs index 4d2e9a5a9..4d9d5fabc 100644 --- a/crates/geom/src/nurbs.rs +++ b/crates/geom/src/nurbs.rs @@ -172,6 +172,11 @@ impl Spline { } /// [`Spline::derivative_unchecked`] before a value past f64's range is read as zero. + #[expect( + clippy::cast_precision_loss, + clippy::many_single_char_names, + reason = "The NURBS derivative keeps its standard equation notation, and MAX_DEGREE makes p exact as f64." + )] fn velocity(&self, t: f64) -> Vec2 { let p = self.degree; let Some(n) = self.control.len().checked_sub(1) else { return Vec2::ZERO };