Skip to main content

cadkit_geom/
lib.rs

1//! Independent analytic geometry using `f64` coordinates in a caller-defined Cartesian plane.
2//!
3//! Lengths use caller units, areas use squared units, and angles are radians,
4//! positive counterclockwise from +x. Rings close implicitly without a repeated
5//! first vertex. Tolerances are explicit; display tessellation is not a measurement
6//! source. Enable `schemars` for JSON Schema generation. Serde support is always available.
7//!
8//! ```
9//! use cadkit_geom::{GeometryTolerance, LineSegment, Point2};
10//! let segment = LineSegment { start: Point2::new(0.0, 0.0), end: Point2::new(4.0, 0.0) };
11//! let offset = segment.offset(1.0, &GeometryTolerance::default())?;
12//! assert_eq!(offset.start, Point2::new(0.0, 1.0));
13//! # Ok::<(), cadkit_geom::GeometryError>(())
14//! ```
15
16mod boolean;
17mod calibration;
18mod contacts;
19mod curves;
20mod editing;
21mod intersections;
22mod nearest;
23mod nurbs;
24mod polygon;
25#[cfg(test)]
26mod scan_equivalence;
27
28pub use boolean::*;
29pub use calibration::*;
30pub use contacts::*;
31pub use curves::*;
32pub use editing::*;
33pub use intersections::*;
34pub use nearest::*;
35pub use nurbs::*;
36pub use polygon::*;
37use serde::{Deserialize, Serialize};
38
39/// Result of an operation in caller-defined coordinates, carrying a typed diagnostic on failure.
40pub type GeometryResult<T> = Result<T, GeometryError>;
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
43#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
44#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
45/// Stable, unit-independent reason codes; coordinate and tolerance context belongs to the
46/// diagnostic's operation.
47#[cfg_attr(feature = "schemars", schemars(transform = crate::unit_enum_schema))]
48pub enum GeometryReason {
49    /// A scalar is NaN or infinite.
50    NonFiniteNumber,
51    /// A required positive scalar is zero or negative.
52    NonPositiveValue,
53    /// The input lacks the required number of points.
54    InsufficientPoints,
55    /// A length or area is at or below the operation's tolerance.
56    BelowTolerance,
57    /// A parameter or option is outside its supported range.
58    InvalidParameterRange,
59    /// Polynomial degree is outside the supported profile.
60    UnsupportedDegree,
61    /// Axes lack sufficient length or angular independence.
62    DegenerateAxes,
63    /// Control points coincide within the linear tolerance.
64    CoincidentControlPoints,
65    /// The geometry structure or topology is invalid for the operation.
66    InvalidTopology,
67    /// A hole is not strictly contained inside the exterior.
68    HoleOutsideBoundary,
69    /// Holes intersect, touch or contain one another.
70    IntersectingHoles,
71    /// A transform is singular or numerically unstable.
72    SingularTransform,
73    /// This operation requires uniform scale and orthogonal axes.
74    SimilarityRequired,
75    /// A unique nearest point cannot be selected under the current profile.
76    AmbiguousNearestPoint,
77    /// Nearest-point evaluation is unsupported for this profile.
78    NearestNotSupported,
79    /// Certified analytic measurement is not implemented for this profile.
80    MeasurementNotSupported,
81    /// The curve pair has no supported intersection algorithm.
82    IntersectionNotSupported,
83    /// The tolerance cannot distinguish the intersection topology.
84    AmbiguousIntersection,
85    /// The editing operation does not support this geometry profile.
86    EditingNotSupported,
87    /// The dimensionless miter ratio exceeds the selected limit.
88    MiterLimitExceeded,
89    /// An offset collapses or reverses an edge.
90    OffsetCollapsed,
91    /// Boolean topology cannot be certified within the requested budgets.
92    BooleanAmbiguity,
93    /// The boolean dependency failed or produced invalid provenance.
94    BooleanKernelFailure,
95    /// The requested grid cannot fit the safe integer coordinate range.
96    QuantizationRangeExceeded,
97    /// An explicit resource count limit was exceeded.
98    ResourceLimit,
99    /// The geometry does not define an enclosed area.
100    NotClosed,
101    /// Approximation did not converge within its resource budget.
102    ApproximationLimit,
103    /// Numerical integration did not converge within its error budget.
104    IntegrationNotConverged,
105    /// Numerical uncertainty exceeds the requested coordinate or area budget.
106    NumericalErrorBudgetExceeded,
107    /// Control pairs cannot determine a stable affine fit.
108    CollinearControlPoints,
109    /// Calibration residual exceeds the caller's target-unit limit.
110    ResidualLimitExceeded,
111}
112
113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
114#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
115#[serde(rename_all = "camelCase", deny_unknown_fields)]
116/// Structured error context. Codes and field paths are stable; messages are English. Numerical
117/// units follow the failing operation.
118pub struct GeometryDiagnostic {
119    /// Stable reason code, independent of units.
120    pub reason: GeometryReason,
121    /// Machine-readable path to the failing field; coordinate units follow the operation.
122    pub field: String,
123    /// Stable operation identifier; no coordinate conversion is implied.
124    pub operation: String,
125    /// Human-readable English diagnostic; not a machine-readable reason code.
126    pub message: String,
127}
128impl std::fmt::Display for GeometryDiagnostic {
129    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        formatter.write_str(&self.message)
131    }
132}
133
134#[derive(Debug, Clone, PartialEq, thiserror::Error, Serialize, Deserialize)]
135#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
136#[serde(
137    tag = "code",
138    content = "details",
139    rename_all = "SCREAMING_SNAKE_CASE",
140    deny_unknown_fields
141)]
142/// Invalid input or an unsupported operation; diagnostics retain the operation's coordinate and
143/// tolerance context.
144pub enum GeometryError {
145    #[error("Invalid geometry: {0}")]
146    /// Invalid geometry or numerical budget failure; units follow the diagnostic operation.
147    Invalid(GeometryDiagnostic),
148    #[error("Unsupported geometry operation: {0}")]
149    /// Unsupported profile or exhausted algorithm/resource budget; units follow the diagnostic
150    /// operation.
151    Unsupported(GeometryDiagnostic),
152}
153impl GeometryError {
154    /// Construct an invalid-input diagnostic; numerical units follow the supplied operation.
155    pub fn invalid(
156        reason: GeometryReason,
157        field: &str,
158        operation: &str,
159        message: impl Into<String>,
160    ) -> Self {
161        Self::Invalid(GeometryDiagnostic {
162            reason,
163            field: field.into(),
164            operation: operation.into(),
165            message: message.into(),
166        })
167    }
168    /// Construct an unsupported-operation diagnostic; numerical units follow the supplied
169    /// operation.
170    pub fn unsupported(
171        reason: GeometryReason,
172        field: &str,
173        operation: &str,
174        message: impl Into<String>,
175    ) -> Self {
176        Self::Unsupported(GeometryDiagnostic {
177            reason,
178            field: field.into(),
179            operation: operation.into(),
180            message: message.into(),
181        })
182    }
183    /// Return structured diagnostic context without changing its units or stable reason.
184    pub fn diagnostic(&self) -> &GeometryDiagnostic {
185        match self {
186            Self::Invalid(detail) | Self::Unsupported(detail) => detail,
187        }
188    }
189    /// Attach field and operation context to a numerical diagnostic without changing its
190    /// reason or units.
191    pub fn at(mut self, field: &str, operation: &str) -> Self {
192        let detail = match &mut self {
193            Self::Invalid(detail) | Self::Unsupported(detail) => detail,
194        };
195        detail.field = field.into();
196        detail.operation = operation.into();
197        self
198    }
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
202#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
203#[serde(rename_all = "camelCase", deny_unknown_fields)]
204/// Independent positive finite budgets: coordinate units for length, radians for angles, squared
205/// units for area. Defaults are numerical starting values, not physical accuracy guarantees.
206pub struct GeometryTolerance {
207    /// Positive finite length tolerance in caller coordinate units; default 1e-8.
208    pub linear: f64,
209    /// Positive finite angular tolerance in radians; default 1e-10.
210    pub angular: f64,
211    /// Positive finite minimum valid area in squared coordinate units; default 1e-12. Boolean total
212    /// area error is a separate budget.
213    pub area: f64,
214}
215
216impl Default for GeometryTolerance {
217    fn default() -> Self {
218        Self {
219            linear: 1e-8,
220            angular: 1e-10,
221            area: 1e-12,
222        }
223    }
224}
225
226impl GeometryTolerance {
227    /// Validate finite values and the supported profile. Where supplied, tolerances use caller
228    /// units, radians and squared units; no repair or unit conversion is performed.
229    pub fn validate(self) -> GeometryResult<()> {
230        for (field, value) in [
231            ("linear", self.linear),
232            ("angular", self.angular),
233            ("area", self.area),
234        ] {
235            positive(value, "Tolerance").map_err(|error| error.at(field, "tolerance.validate"))?;
236        }
237        Ok(())
238    }
239}
240
241#[derive(Debug, Default, Clone, Copy, PartialEq, Serialize, Deserialize)]
242#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
243#[serde(deny_unknown_fields)]
244/// A point in the caller's Cartesian coordinate units. Construction is unchecked; validate before
245/// operations requiring finite values.
246pub struct Point2 {
247    /// Cartesian x component in caller coordinate units.
248    pub x: f64,
249    /// Cartesian y component in caller coordinate units.
250    pub y: f64,
251}
252
253impl Point2 {
254    /// Construct a Cartesian point in caller units without validation or tolerance adjustment.
255    pub const fn new(x: f64, y: f64) -> Self {
256        Self { x, y }
257    }
258    /// Validate finite values and the supported profile. Where supplied, tolerances use caller
259    /// units, radians and squared units; no repair or unit conversion is performed.
260    pub fn validate(self) -> GeometryResult<()> {
261        finite(self.x).map_err(|error| error.at("x", "point.validate"))?;
262        finite(self.y).map_err(|error| error.at("y", "point.validate"))
263    }
264    /// Euclidean distance in caller coordinate units; raw arithmetic applies no tolerance.
265    pub fn distance(self, other: Self) -> f64 {
266        (self.x - other.x).hypot(self.y - other.y)
267    }
268    /// Interpolate with dimensionless fraction t; 0 selects self and 1 selects other. Extrapolation
269    /// is permitted; no validation or tolerance is applied.
270    pub fn lerp(self, other: Self, t: f64) -> Self {
271        Self::new(
272            self.x + (other.x - self.x) * t,
273            self.y + (other.y - self.y) * t,
274        )
275    }
276    /// Translate by a displacement in the same Cartesian units; no validation or tolerance is
277    /// applied.
278    pub fn translated(self, delta: Vector2) -> Self {
279        Self::new(self.x + delta.x, self.y + delta.y)
280    }
281    /// Displacement from self to other in the same Cartesian units; no tolerance is applied.
282    pub fn vector_to(self, other: Self) -> Vector2 {
283        Vector2 {
284            x: other.x - self.x,
285            y: other.y - self.y,
286        }
287    }
288}
289
290#[derive(Debug, Default, Clone, Copy, PartialEq, Serialize, Deserialize)]
291#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
292#[serde(deny_unknown_fields)]
293/// Cartesian displacement in caller units. Raw arithmetic is unchecked and applies no tolerance.
294pub struct Vector2 {
295    /// Cartesian x component in caller coordinate units.
296    pub x: f64,
297    /// Cartesian y component in caller coordinate units.
298    pub y: f64,
299}
300
301impl Vector2 {
302    /// Length in caller coordinate units. Where supplied, the tolerance controls validation and
303    /// numerical integration; raw segment/vector length applies no tolerance.
304    pub fn length(self) -> f64 {
305        self.x.hypot(self.y)
306    }
307    /// Dot product in squared coordinate units; no normalization or tolerance is applied.
308    pub fn dot(self, other: Self) -> f64 {
309        self.x * other.x + self.y * other.y
310    }
311    /// Signed 2D cross product in squared units, positive for a counterclockwise turn; no tolerance
312    /// is applied.
313    pub fn cross(self, other: Self) -> f64 {
314        self.x * other.y - self.y * other.x
315    }
316    /// Multiply by a dimensionless factor, retaining coordinate units; no validation is applied.
317    pub fn scaled(self, scale: f64) -> Self {
318        Self {
319            x: self.x * scale,
320            y: self.y * scale,
321        }
322    }
323}
324
325#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
326#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
327#[serde(deny_unknown_fields)]
328/// Inclusive axis-aligned Cartesian bounds in caller units, with no implicit tolerance padding.
329pub struct Bounds2 {
330    /// Inclusive lower Cartesian corner in caller units.
331    pub min: Point2,
332    /// Inclusive upper Cartesian corner in caller units.
333    pub max: Point2,
334}
335
336impl Bounds2 {
337    /// Compute inclusive Cartesian bounds of a nonempty finite point set, in its coordinate units,
338    /// without tolerance padding.
339    pub fn from_points(points: &[Point2]) -> GeometryResult<Self> {
340        let first = *points.first().ok_or_else(|| {
341            GeometryError::invalid(
342                GeometryReason::InsufficientPoints,
343                "points",
344                "bounds",
345                "Empty point set",
346            )
347        })?;
348        first.validate()?;
349        let mut bounds = Self {
350            min: first,
351            max: first,
352        };
353        for p in points {
354            p.validate()?;
355            bounds.min.x = bounds.min.x.min(p.x);
356            bounds.min.y = bounds.min.y.min(p.y);
357            bounds.max.x = bounds.max.x.max(p.x);
358            bounds.max.y = bounds.max.y.max(p.y);
359        }
360        Ok(bounds)
361    }
362    /// Test inclusive bounds in caller coordinates without tolerance padding or input validation.
363    pub fn contains(self, p: Point2) -> bool {
364        p.x >= self.min.x && p.x <= self.max.x && p.y >= self.min.y && p.y <= self.max.y
365    }
366    /// Test inclusive box overlap in the same coordinate system without tolerance padding.
367    pub fn intersects(self, other: Self) -> bool {
368        self.min.x <= other.max.x
369            && self.max.x >= other.min.x
370            && self.min.y <= other.max.y
371            && self.max.y >= other.min.y
372    }
373}
374
375#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
376#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
377#[serde(deny_unknown_fields)]
378/// Affine Cartesian transform: x'=m11*x+m12*y+tx, y'=m21*x+m22*y+ty. Linear coefficients are
379/// dimensionless; translation uses target units.
380pub struct Transform2 {
381    /// Dimensionless coefficient mapping input x to output x.
382    pub m11: f64,
383    /// Dimensionless coefficient mapping input y to output x.
384    pub m12: f64,
385    /// Dimensionless coefficient mapping input x to output y.
386    pub m21: f64,
387    /// Dimensionless coefficient mapping input y to output y.
388    pub m22: f64,
389    /// Translation along output x, in target coordinate units.
390    pub tx: f64,
391    /// Translation along output y, in target coordinate units.
392    pub ty: f64,
393}
394
395impl Default for Transform2 {
396    fn default() -> Self {
397        Self::identity()
398    }
399}
400impl Transform2 {
401    /// Identity transform in the current Cartesian coordinate system, with dimensionless unit
402    /// scale.
403    pub const fn identity() -> Self {
404        Self {
405            m11: 1.,
406            m12: 0.,
407            m21: 0.,
408            m22: 1.,
409            tx: 0.,
410            ty: 0.,
411        }
412    }
413    /// Translation by x and y in target coordinate units; no tolerance or validation is applied.
414    pub fn translation(x: f64, y: f64) -> Self {
415        Self {
416            tx: x,
417            ty: y,
418            ..Self::identity()
419        }
420    }
421    /// Scale axes by dimensionless factors; negative factors reflect, and zero is allowed at
422    /// construction but rejected by inversion.
423    pub fn scale(x: f64, y: f64) -> Self {
424        Self {
425            m11: x,
426            m22: y,
427            ..Self::identity()
428        }
429    }
430    /// Counterclockwise rotation about the origin by angle radians; no tolerance or validation is
431    /// applied.
432    pub fn rotation(angle: f64) -> Self {
433        let (s, c) = angle.sin_cos();
434        Self {
435            m11: c,
436            m12: -s,
437            m21: s,
438            m22: c,
439            ..Self::identity()
440        }
441    }
442    /// Map a Cartesian point to target coordinates, including translation; no tolerance or
443    /// validation is applied.
444    pub fn apply_point(self, p: Point2) -> Point2 {
445        Point2::new(
446            self.m11 * p.x + self.m12 * p.y + self.tx,
447            self.m21 * p.x + self.m22 * p.y + self.ty,
448        )
449    }
450    /// Map a displacement to target units using only the linear part; no tolerance or validation is
451    /// applied.
452    pub fn apply_vector(self, v: Vector2) -> Vector2 {
453        Vector2 {
454            x: self.m11 * v.x + self.m12 * v.y,
455            y: self.m21 * v.x + self.m22 * v.y,
456        }
457    }
458    /// Dimensionless determinant of the linear part; negative values reverse orientation. No
459    /// validation is applied.
460    pub fn determinant(self) -> f64 {
461        self.m11 * self.m22 - self.m12 * self.m21
462    }
463    /// Validate finite values and the supported profile. Where supplied, tolerances use caller
464    /// units, radians and squared units; no repair or unit conversion is performed.
465    pub fn validate(self) -> GeometryResult<()> {
466        for (field, value) in [
467            ("m11", self.m11),
468            ("m12", self.m12),
469            ("m21", self.m21),
470            ("m22", self.m22),
471            ("tx", self.tx),
472            ("ty", self.ty),
473        ] {
474            finite(value).map_err(|error| error.at(field, "transform.validate"))?;
475        }
476        Ok(())
477    }
478    /// Invert the affine mapping after finite-value and conditioning checks using the supplied
479    /// tolerance; returns coordinates in the original source units.
480    pub fn inverse(self, tolerance: &GeometryTolerance) -> GeometryResult<Self> {
481        self.validate()?;
482        tolerance.validate()?;
483        let d = self.determinant();
484        let scale = self
485            .m11
486            .abs()
487            .max(self.m12.abs())
488            .max(self.m21.abs())
489            .max(self.m22.abs());
490        if scale == 0. || !d.is_finite() || d.abs() <= f64::EPSILON * scale * scale * 16. {
491            return Err(GeometryError::invalid(
492                GeometryReason::SingularTransform,
493                "transform",
494                "inverse",
495                "Singular or unstable transform",
496            ));
497        }
498        let mut inv = Self {
499            m11: self.m22 / d,
500            m12: -self.m12 / d,
501            m21: -self.m21 / d,
502            m22: self.m11 / d,
503            tx: 0.,
504            ty: 0.,
505        };
506        inv.tx = -(inv.m11 * self.tx + inv.m12 * self.ty);
507        inv.ty = -(inv.m21 * self.tx + inv.m22 * self.ty);
508        inv.validate()?;
509        Ok(inv)
510    }
511    /// Compose this transform followed by next; both act in the same coordinate convention.
512    pub fn then(self, next: Self) -> Self {
513        Self {
514            m11: next.m11 * self.m11 + next.m12 * self.m21,
515            m12: next.m11 * self.m12 + next.m12 * self.m22,
516            m21: next.m21 * self.m11 + next.m22 * self.m21,
517            m22: next.m21 * self.m12 + next.m22 * self.m22,
518            tx: next.m11 * self.tx + next.m12 * self.ty + next.tx,
519            ty: next.m21 * self.tx + next.m22 * self.ty + next.ty,
520        }
521    }
522    /// Return the positive dimensionless scale if axes define a similarity within the supplied
523    /// angular tolerance; reflection is permitted.
524    pub fn similarity_scale(self, t: &GeometryTolerance) -> GeometryResult<f64> {
525        self.validate()?;
526        t.validate()?;
527        let a = Vector2 {
528            x: self.m11,
529            y: self.m21,
530        };
531        let b = Vector2 {
532            x: self.m12,
533            y: self.m22,
534        };
535        let la = a.length();
536        let lb = b.length();
537        positive(la, "Scale")?;
538        positive(lb, "Scale")?;
539        if (la - lb).abs() > t.angular * la.max(lb)
540            || a.scaled(1. / la).dot(b.scaled(1. / lb)).abs() > t.angular
541        {
542            return Err(GeometryError::unsupported(
543                GeometryReason::SimilarityRequired,
544                "transform",
545                "similarity_scale",
546                "This curve requires a similarity transform",
547            ));
548        }
549        Ok(la)
550    }
551}
552
553/// Reject NaN and infinities without changing the scalar or its units; no tolerance is applied.
554pub fn finite(value: f64) -> GeometryResult<()> {
555    if value.is_finite() {
556        Ok(())
557    } else {
558        Err(GeometryError::invalid(
559            GeometryReason::NonFiniteNumber,
560            "value",
561            "finite",
562            "Number must be finite",
563        ))
564    }
565}
566/// Require a finite, strictly positive scalar in its original units. The label appears in the
567/// English error message; no tolerance is applied.
568pub fn positive(value: f64, label: &str) -> GeometryResult<()> {
569    finite(value)?;
570    if value > 0. {
571        Ok(())
572    } else {
573        Err(GeometryError::invalid(
574            GeometryReason::NonPositiveValue,
575            "value",
576            "positive",
577            format!("{label} must be positive"),
578        ))
579    }
580}
581
582// Internal shape invariants are checked again at access sites so malformed data
583// cannot turn an indexing mistake into a panic. Existing public validation runs first.
584fn missing_geometry() -> GeometryError {
585    GeometryError::invalid(
586        GeometryReason::InvalidTopology,
587        "structure",
588        "geometry.access",
589        "Geometry structure is missing a required element",
590    )
591}
592fn at<T, I: std::slice::SliceIndex<[T]>>(values: &[T], index: I) -> GeometryResult<&I::Output> {
593    values.get(index).ok_or_else(missing_geometry)
594}
595fn at_mut<T, I: std::slice::SliceIndex<[T]>>(
596    values: &mut [T],
597    index: I,
598) -> GeometryResult<&mut I::Output> {
599    values.get_mut(index).ok_or_else(missing_geometry)
600}
601fn last<T>(values: &[T]) -> GeometryResult<&T> {
602    values.last().ok_or_else(missing_geometry)
603}
604
605// Schemars represents documented unit variants as oneOf/const. Keep the original
606// compact enum representation while retaining English API documentation. This
607// transform is attached only to unit enums; it preserves variant order and values.
608#[cfg(feature = "schemars")]
609fn unit_enum_schema(schema: &mut schemars::Schema) {
610    let values = schema
611        .get("oneOf")
612        .and_then(|value| value.as_array())
613        .and_then(|variants| {
614            variants
615                .iter()
616                .map(|variant| variant.get("const").cloned())
617                .collect::<Option<Vec<_>>>()
618        });
619    if let Some(values) = values {
620        schema.remove("oneOf");
621        schema.insert("type".into(), "string".into());
622        schema.insert("enum".into(), values.into());
623    }
624}
625
626#[cfg(test)]
627mod checked_access_tests {
628    use super::*;
629
630    #[test]
631    fn missing_internal_elements_return_typed_errors() {
632        let mut values = [1_u8, 2];
633        for error in [
634            at(&values, 2).unwrap_err(),
635            at(&values, 1..3).unwrap_err(),
636            at_mut(&mut values, 2).unwrap_err(),
637            last::<u8>(&[]).unwrap_err(),
638        ] {
639            assert_eq!(error.diagnostic().reason, GeometryReason::InvalidTopology);
640            assert_eq!(error.diagnostic().operation, "geometry.access");
641        }
642    }
643}