Skip to main content

ifc_geometry/curve/
bspline.rs

1//! `IfcBSplineCurve` and its knotted / rational refinements.
2//!
3//! # What this module does and does not do
4//!
5//! It reads the NURBS *parameters*. It does not evaluate a basis function,
6//! does not de-Boor, does not insert a knot. Those belong to a geometry
7//! kernel. What this module does provide is the consistency checking a kernel
8//! would otherwise have to repeat, because every one of these invariants shows
9//! up in real files and every one of them produces a NaN or an out-of-bounds
10//! read rather than an error.
11//!
12//! # The invariants worth enforcing at the boundary
13//!
14//! - **Knot vector length.** `sum(KnotMultiplicities)` must equal
15//!   `ControlPoints + Degree + 1`. IFC stores knots in *compressed* form:
16//!   distinct values plus their multiplicities, not the repeated vector a
17//!   kernel wants. Getting this wrong is not detectable downstream, it just
18//!   evaluates garbage.
19//! - **Multiplicities and knots are parallel lists.** Different lengths mean
20//!   the file is corrupt, not that the shorter one defaults.
21//! - **Weights are positive and count-matched.** A zero weight divides by zero
22//!   at the corresponding control point; a negative one produces a curve that
23//!   flips through infinity. Both are legal IEEE arithmetic and neither is
24//!   legal geometry.
25//!
26//! # Why `ClosedCurve` and `SelfIntersect` are only informational
27//!
28//! They are `IfcLogical`, may be `.U.`, and are derived facts a file asserts
29//! rather than constraints it guarantees. They are exposed as `Option<bool>`
30//! so a consumer can use them as a hint and never as a precondition.
31
32use crate::error::GeometryResult;
33use crate::resource::point::CartesianPoint;
34use crate::resource::resolve;
35use crate::slots::Slots;
36use ifc_model::{Entity, EntityId, Model, Value};
37
38/// `IfcBSplineCurve` family attribute slots.
39///
40/// From IFC4 ADD2 TC1. Slots 0-4 come from `IfcBSplineCurve`, 5-7 from
41/// `IfcBSplineCurveWithKnots`, and 8 from
42/// `IfcRationalBSplineCurveWithKnots`. Inherited attributes come first, so a
43/// rational curve reads `Degree` at 0 and `WeightsData` at 8.
44pub(crate) mod slot {
45    /// `Degree`: `IfcInteger`, from `IfcBSplineCurve`.
46    pub const DEGREE: usize = 0;
47    /// `ControlPointsList`: `LIST [2:?] OF IfcCartesianPoint`.
48    pub const CONTROL_POINTS: usize = 1;
49    /// `CurveForm`: `IfcBSplineCurveForm`.
50    pub const CURVE_FORM: usize = 2;
51    /// `ClosedCurve`: `IfcLogical`.
52    pub const CLOSED_CURVE: usize = 3;
53    /// `SelfIntersect`: `IfcLogical`.
54    pub const SELF_INTERSECT: usize = 4;
55    /// `KnotMultiplicities`: from `IfcBSplineCurveWithKnots`.
56    pub const KNOT_MULTIPLICITIES: usize = 5;
57    /// `Knots`: distinct knot values, from `IfcBSplineCurveWithKnots`.
58    pub const KNOTS: usize = 6;
59    /// `KnotSpec`: `IfcKnotType`, from `IfcBSplineCurveWithKnots`.
60    pub const KNOT_SPEC: usize = 7;
61    /// `WeightsData`: from `IfcRationalBSplineCurveWithKnots`.
62    pub const WEIGHTS_DATA: usize = 8;
63}
64
65/// `IfcBSplineCurveForm`: what shape the curve was originally.
66///
67/// Purely informational. A `CIRCULAR_ARC` form does not guarantee the control
68/// points actually describe a circle, so it must never be used to substitute
69/// an analytic curve for the spline. It is worth keeping because it lets a
70/// consumer round-trip the hint and lets a UI say something useful.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum BSplineCurveForm {
73    /// The control points are a polyline.
74    Polyline,
75    /// Originally a circular arc.
76    CircularArc,
77    /// Originally an elliptic arc.
78    EllipticArc,
79    /// Originally a parabolic arc.
80    ParabolicArc,
81    /// Originally a hyperbolic arc.
82    HyperbolicArc,
83    /// No original form is claimed.
84    Unspecified,
85}
86
87impl BSplineCurveForm {
88    /// Parse the enumeration token, `None` if unrecognised.
89    pub fn from_token(token: &str) -> Option<Self> {
90        match token.to_ascii_uppercase().as_str() {
91            "POLYLINE_FORM" => Some(Self::Polyline),
92            "CIRCULAR_ARC" => Some(Self::CircularArc),
93            "ELLIPTIC_ARC" => Some(Self::EllipticArc),
94            "PARABOLIC_ARC" => Some(Self::ParabolicArc),
95            "HYPERBOLIC_ARC" => Some(Self::HyperbolicArc),
96            "UNSPECIFIED" => Some(Self::Unspecified),
97            _ => None,
98        }
99    }
100}
101
102/// `IfcKnotType`: the shape of the knot vector.
103///
104/// Also informational: the knots themselves are stored explicitly, so this
105/// only describes them. A kernel should trust the values, not the label.
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum KnotType {
108    /// Evenly spaced knots including the ends.
109    Uniform,
110    /// Uniform interior knots with clamped ends.
111    QuasiUniform,
112    /// Interior multiplicity equal to the degree; Bezier segments.
113    PiecewiseBezier,
114    /// Nothing is claimed about the knot vector.
115    Unspecified,
116}
117
118impl KnotType {
119    /// Parse the enumeration token, `None` if unrecognised.
120    pub fn from_token(token: &str) -> Option<Self> {
121        match token.to_ascii_uppercase().as_str() {
122            "UNIFORM_KNOTS" => Some(Self::Uniform),
123            "QUASI_UNIFORM_KNOTS" => Some(Self::QuasiUniform),
124            "PIECEWISE_BEZIER_KNOTS" => Some(Self::PiecewiseBezier),
125            "UNSPECIFIED" => Some(Self::Unspecified),
126            _ => None,
127        }
128    }
129}
130
131/// A borrowed view of any `IfcBSplineCurve` subtype.
132///
133/// The knot and weight accessors return `Ok(None)` when the entity is a
134/// plainer subtype that does not carry them, so one view serves the whole
135/// family without the caller re-dispatching on the type name.
136#[derive(Debug, Clone, Copy)]
137pub struct BSplineCurve<'m> {
138    slots: Slots<'m>,
139}
140
141impl<'m> BSplineCurve<'m> {
142    /// Wrap an entity known to be an `IfcBSplineCurve` subtype.
143    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
144        Self {
145            slots: Slots::new(id, entity),
146        }
147    }
148
149    /// The entity id.
150    pub fn id(&self) -> EntityId {
151        self.slots.id()
152    }
153
154    /// The polynomial degree, guaranteed to be at least 1 and smaller than
155    /// the number of control points.
156    ///
157    /// IFC requires `Degree <= UpperIndexOnControlPoints`; because the upper
158    /// index is `control_points.len() - 1`, `degree >= len` is invalid.
159    pub fn degree(&self) -> GeometryResult<usize> {
160        let raw = self.slots.req_i64(slot::DEGREE, "Degree")?;
161        if raw < 1 {
162            return Err(self
163                .slots
164                .degenerate(format!("Degree must be at least 1, found {raw}")));
165        }
166        let degree = usize::try_from(raw)
167            .map_err(|_| self.slots.degenerate("Degree exceeds platform limits"))?;
168        let control_count = self.control_point_refs()?.len();
169        if degree >= control_count {
170            return Err(self.slots.degenerate(format!(
171                "Degree {degree} must be smaller than the {control_count} control points"
172            )));
173        }
174        Ok(degree)
175    }
176
177    /// The `IfcCartesianPoint` control point references, in order.
178    ///
179    /// Order defines the curve; sorting or deduplicating them destroys it.
180    pub fn control_point_refs(&self) -> GeometryResult<Vec<EntityId>> {
181        let points = self
182            .slots
183            .req_ref_list(slot::CONTROL_POINTS, "ControlPointsList")?;
184        if points.len() < 2 {
185            return Err(self.slots.degenerate(format!(
186                "ControlPointsList needs at least 2 points, found {}",
187                points.len()
188            )));
189        }
190        Ok(points)
191    }
192
193    /// The control points as typed point views, resolved from the model.
194    ///
195    /// All or nothing: a missing control point changes the curve, so one bad
196    /// reference fails the call.
197    pub fn control_points<'v>(&self, model: &'v Model) -> GeometryResult<Vec<CartesianPoint<'v>>> {
198        resolve::cartesian_points(model, self.id(), &self.control_point_refs()?)
199    }
200
201    /// The declared original form, defaulting to `Unspecified`.
202    pub fn curve_form(&self) -> BSplineCurveForm {
203        self.slots
204            .opt_enum(slot::CURVE_FORM)
205            .and_then(BSplineCurveForm::from_token)
206            .unwrap_or(BSplineCurveForm::Unspecified)
207    }
208
209    /// The asserted `ClosedCurve` flag; `None` for `.U.` or absent.
210    ///
211    /// A hint only: nothing verifies that the first and last control points
212    /// coincide.
213    pub fn closed_curve(&self) -> Option<bool> {
214        self.slots.opt_bool(slot::CLOSED_CURVE)
215    }
216
217    /// The asserted `SelfIntersect` flag; `None` for `.U.` or absent.
218    pub fn self_intersect(&self) -> Option<bool> {
219        self.slots.opt_bool(slot::SELF_INTERSECT)
220    }
221
222    /// The declared knot type, defaulting to `Unspecified`.
223    pub fn knot_spec(&self) -> KnotType {
224        self.slots
225            .opt_enum(slot::KNOT_SPEC)
226            .and_then(KnotType::from_token)
227            .unwrap_or(KnotType::Unspecified)
228    }
229
230    /// Is this the knotted subtype?
231    pub fn has_knots(&self) -> bool {
232        self.slots.opt(slot::KNOTS).is_some()
233    }
234
235    /// Whether the entity declares the rational subtype.
236    ///
237    /// Subtype identity, not accidental trailing-slot presence, owns this
238    /// semantic. A malformed rational entity with missing weights must fail;
239    /// it must never be silently downgraded to a polynomial curve.
240    pub fn is_rational(&self) -> bool {
241        self.slots
242            .type_name()
243            .eq_ignore_ascii_case("IFCRATIONALBSPLINECURVEWITHKNOTS")
244    }
245
246    /// The compressed knot vector: distinct values with their multiplicities.
247    ///
248    /// Returns `Ok(None)` for a curve without knots. When present, the two
249    /// lists are validated to be the same length and the total multiplicity is
250    /// checked against `ControlPoints + Degree + 1`, which is the invariant
251    /// that silently produces garbage when violated.
252    pub fn knots(&self) -> GeometryResult<Option<KnotVector>> {
253        if !self.has_knots() {
254            return Ok(None);
255        }
256        let values = self.slots.req_f64_list(slot::KNOTS, "Knots")?;
257        let multiplicities = self.integer_list(slot::KNOT_MULTIPLICITIES, "KnotMultiplicities")?;
258
259        if values.len() != multiplicities.len() {
260            return Err(self.slots.degenerate(format!(
261                "Knots has {} entries but KnotMultiplicities has {}; \
262                 they are parallel lists",
263                values.len(),
264                multiplicities.len()
265            )));
266        }
267        if values.is_empty() {
268            return Err(self.slots.degenerate("Knots is empty"));
269        }
270        for (i, m) in multiplicities.iter().enumerate() {
271            if *m < 1 {
272                return Err(self.slots.degenerate(format!(
273                    "knot multiplicity {m} at position {i} is not positive"
274                )));
275            }
276        }
277        for (index, value) in values.iter().enumerate() {
278            if !value.is_finite() {
279                return Err(self
280                    .slots
281                    .degenerate(format!("Knots[{index}] must be finite, found {value}")));
282            }
283        }
284        // Knots must be strictly increasing: IFC stores each distinct value
285        // once, so a repeat means the multiplicity was written twice instead
286        // of being folded, which shifts the whole vector.
287        for pair in values.windows(2) {
288            if pair[1] <= pair[0] {
289                return Err(self.slots.degenerate(format!(
290                    "Knots must be strictly increasing; found {} after {}",
291                    pair[1], pair[0]
292                )));
293            }
294        }
295
296        let multiplicities = multiplicities
297            .into_iter()
298            .map(|value| {
299                usize::try_from(value).map_err(|_| {
300                    self.slots
301                        .degenerate("knot multiplicity exceeds platform limits")
302                })
303            })
304            .collect::<GeometryResult<Vec<_>>>()?;
305        let total = multiplicities.iter().try_fold(0usize, |total, &value| {
306            total.checked_add(value).ok_or_else(|| {
307                self.slots
308                    .degenerate("knot multiplicity total overflows usize")
309            })
310        })?;
311        let expected = self
312            .control_point_refs()?
313            .len()
314            .checked_add(self.degree()?)
315            .and_then(|value| value.checked_add(1))
316            .ok_or_else(|| self.slots.degenerate("expected knot count overflows usize"))?;
317        if total != expected {
318            return Err(self.slots.degenerate(format!(
319                "knot multiplicities sum to {total} but must equal \
320                 ControlPoints + Degree + 1 = {expected}"
321            )));
322        }
323
324        Ok(Some(KnotVector {
325            values,
326            multiplicities,
327        }))
328    }
329
330    /// The rational weights, one per control point, all finite and positive.
331    ///
332    /// Returns `Ok(None)` for a non-rational curve. A zero weight is a
333    /// division by zero at evaluation time and a negative one flips the curve
334    /// through infinity; both are rejected here rather than in the kernel.
335    pub fn weights(&self) -> GeometryResult<Option<Vec<f64>>> {
336        let supplied = self.slots.opt(slot::WEIGHTS_DATA).is_some();
337        match (self.is_rational(), supplied) {
338            (false, false) => return Ok(None),
339            (true, false) => {
340                return Err(self
341                    .slots
342                    .degenerate("rational B-spline curve is missing WeightsData"));
343            }
344            (false, true) => {
345                return Err(self
346                    .slots
347                    .degenerate("polynomial B-spline curve must not carry WeightsData"));
348            }
349            (true, true) => {}
350        }
351        let weights = self.slots.req_f64_list(slot::WEIGHTS_DATA, "WeightsData")?;
352        let control_points = self.control_point_refs()?.len();
353        if weights.len() != control_points {
354            return Err(self.slots.degenerate(format!(
355                "WeightsData has {} entries but there are {control_points} control points",
356                weights.len()
357            )));
358        }
359        for (i, w) in weights.iter().enumerate() {
360            if !w.is_finite() {
361                return Err(self
362                    .slots
363                    .degenerate(format!("weight {w} at control point {i} must be finite")));
364            }
365            if *w <= 0.0 {
366                return Err(self
367                    .slots
368                    .degenerate(format!("weight {w} at control point {i} must be positive")));
369            }
370        }
371        Ok(Some(weights))
372    }
373
374    /// Read a list of integers, rejecting reals.
375    ///
376    /// Multiplicities are counts. A real here means the file lied about a
377    /// count and rounding it would hide the corruption.
378    fn integer_list(&self, index: usize, name: &'static str) -> GeometryResult<Vec<i64>> {
379        let value = self.slots.req(index, name)?;
380        let items = value
381            .as_list()
382            .ok_or_else(|| self.slots.degenerate(format!("{name} must be a list")))?;
383        items
384            .iter()
385            .map(|v| match v.unwrap_typed() {
386                Value::Integer(i) => Ok(*i),
387                other => Err(self
388                    .slots
389                    .degenerate(format!("{name} entry is not an integer: {other:?}"))),
390            })
391            .collect()
392    }
393}
394
395/// A knot vector as IFC stores it: distinct values plus multiplicities.
396///
397/// Kept compressed because that is what the file says. [`Self::expanded`]
398/// produces the repeated vector a kernel wants, in one place, so no consumer
399/// re-implements the expansion.
400#[derive(Debug, Clone, PartialEq)]
401pub struct KnotVector {
402    /// The distinct knot values, finite and strictly increasing.
403    pub values: Vec<f64>,
404    /// How many times each value repeats; parallel to `values`.
405    pub multiplicities: Vec<usize>,
406}
407
408impl KnotVector {
409    /// The full, repeated knot vector.
410    ///
411    /// Length equals `ControlPoints + Degree + 1` for a valid curve, which
412    /// [`BSplineCurve::knots`] has already checked.
413    ///
414    /// Returns `None` when the multiplicities sum beyond `usize`, which only a
415    /// hostile or corrupt file achieves. Callers must refuse such a curve
416    /// rather than expand it; see [`Self::total_multiplicity`].
417    pub fn expanded(&self) -> Option<Vec<f64>> {
418        let total = self.total_multiplicity()?;
419        let mut out = Vec::with_capacity(total);
420        for (value, multiplicity) in self.values.iter().zip(&self.multiplicities) {
421            out.extend(std::iter::repeat_n(*value, *multiplicity));
422        }
423        Some(out)
424    }
425
426    /// The length the expanded vector would have.
427    ///
428    /// `None` on overflow. Multiplicities come straight from the file, so a
429    /// plain `sum()` here panics in debug and wraps in release on input a
430    /// hostile file fully controls.
431    pub fn total_multiplicity(&self) -> Option<usize> {
432        self.multiplicities
433            .iter()
434            .try_fold(0usize, |acc, m| acc.checked_add(*m))
435    }
436
437    /// Is the curve clamped, i.e. does it touch its first and last control
438    /// point?
439    ///
440    /// True when the end multiplicities equal `degree + 1`. Worth asking
441    /// because an unclamped curve starts somewhere in the middle of its
442    /// control polygon, which looks like a modelling error to anyone who has
443    /// only seen clamped splines.
444    pub fn is_clamped(&self, degree: usize) -> bool {
445        let want = degree + 1;
446        self.multiplicities.first() == Some(&want) && self.multiplicities.last() == Some(&want)
447    }
448}
449
450#[cfg(test)]
451mod tests {
452    use super::*;
453
454    fn refs(n: usize) -> Value {
455        Value::List((0..n).map(|i| Value::Ref(EntityId(i as u64 + 1))).collect())
456    }
457
458    fn integers(values: &[i64]) -> Value {
459        Value::List(values.iter().map(|i| Value::Integer(*i)).collect())
460    }
461
462    fn reals(values: &[f64]) -> Value {
463        Value::List(values.iter().map(|r| Value::Real(*r)).collect())
464    }
465
466    /// A degree-3 curve with 4 control points: knots 0 and 1, each x4.
467    fn with_knots(control_points: usize, multiplicities: &[i64], knots: &[f64]) -> Entity {
468        Entity::new(
469            "IFCBSPLINECURVEWITHKNOTS",
470            vec![
471                Value::Integer(3),
472                refs(control_points),
473                Value::Enum("UNSPECIFIED".into()),
474                Value::Bool(false),
475                Value::Bool(false),
476                integers(multiplicities),
477                reals(knots),
478                Value::Enum("UNSPECIFIED".into()),
479            ],
480        )
481    }
482
483    fn rational(control_points: usize, weights: &[f64]) -> Entity {
484        let mut attributes = with_knots(control_points, &[4, 4], &[0.0, 1.0]).attributes;
485        attributes.push(reals(weights));
486        Entity::new("IFCRATIONALBSPLINECURVEWITHKNOTS", attributes)
487    }
488
489    #[test]
490    fn control_points_resolve_in_order_and_fail_on_a_dangling_one() {
491        let e = with_knots(4, &[4, 4], &[0.0, 1.0]);
492        let view = BSplineCurve::new(EntityId(9), &e);
493        let model_with = |ids: &[u64]| {
494            let mut model = Model::new();
495            for &i in ids {
496                let point = Entity::new("IFCCARTESIANPOINT", vec![reals(&[i as f64, 0.0])]);
497                model.insert(EntityId(i), point);
498            }
499            model
500        };
501        let model = model_with(&[1, 2, 3, 4]);
502        let points = view.control_points(&model).unwrap();
503        assert_eq!(points[3].coordinates().unwrap(), vec![4.0, 0.0]);
504        let err = view.control_points(&model_with(&[1, 2, 4])).unwrap_err();
505        assert!(matches!(
506            err,
507            crate::GeometryError::MissingEntity {
508                referrer: EntityId(9),
509                missing: EntityId(3)
510            }
511        ));
512    }
513
514    #[test]
515    fn inherited_bspline_slots_are_read_before_the_subtype_own_slots() {
516        let e = with_knots(4, &[4, 4], &[0.0, 1.0]);
517        let view = BSplineCurve::new(EntityId(1), &e);
518        assert_eq!(view.degree().unwrap(), 3);
519        assert_eq!(view.control_point_refs().unwrap().len(), 4);
520        assert!(view.has_knots());
521        assert!(!view.is_rational());
522    }
523
524    #[test]
525    fn a_valid_knot_vector_expands_to_control_points_plus_degree_plus_one() {
526        let e = with_knots(4, &[4, 4], &[0.0, 1.0]);
527        let knots = BSplineCurve::new(EntityId(1), &e).knots().unwrap().unwrap();
528        assert_eq!(
529            knots.expanded(),
530            Some(vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0])
531        );
532        assert_eq!(knots.total_multiplicity(), Some(4 + 3 + 1));
533        assert!(knots.is_clamped(3));
534    }
535
536    #[test]
537    fn a_knot_multiplicity_sum_that_disagrees_with_the_degree_is_rejected() {
538        let e = with_knots(4, &[4, 3], &[0.0, 1.0]);
539        let err = BSplineCurve::new(EntityId(6), &e).knots().unwrap_err();
540        assert!(err.to_string().contains("must equal"), "got: {err}");
541        assert!(err.to_string().contains("#6"), "got: {err}");
542    }
543
544    /// A knot vector whose multiplicities sum past `usize` must report, not
545    /// panic. A plain `sum()` here aborts the process on input a file controls.
546    #[test]
547    fn multiplicities_summing_past_usize_report_rather_than_panic() {
548        let kv = KnotVector {
549            values: vec![0.0, 1.0],
550            multiplicities: vec![usize::MAX, 2],
551        };
552        assert_eq!(kv.total_multiplicity(), None);
553        assert_eq!(kv.expanded(), None);
554    }
555
556    #[test]
557    fn knots_and_multiplicities_of_different_lengths_are_rejected() {
558        let e = with_knots(4, &[4, 4], &[0.0, 0.5, 1.0]);
559        let err = BSplineCurve::new(EntityId(1), &e).knots().unwrap_err();
560        assert!(err.to_string().contains("parallel"), "got: {err}");
561    }
562
563    /// IFC stores each distinct knot once; a repeat means the file folded the
564    /// multiplicity wrongly and every later knot is shifted.
565    #[test]
566    fn non_increasing_knot_values_are_rejected() {
567        let e = with_knots(5, &[4, 1, 4], &[0.0, 1.0, 1.0]);
568        let err = BSplineCurve::new(EntityId(1), &e).knots().unwrap_err();
569        assert!(err.to_string().contains("increasing"), "got: {err}");
570    }
571
572    #[test]
573    fn non_finite_knot_values_are_rejected_by_the_typed_view() {
574        for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
575            let values = if bad.is_sign_negative() {
576                [bad, 1.0]
577            } else {
578                [0.0, bad]
579            };
580            let e = with_knots(4, &[4, 4], &values);
581            let err = BSplineCurve::new(EntityId(13), &e).knots().unwrap_err();
582            assert!(err.to_string().contains("finite"), "knot {bad}: {err}");
583        }
584    }
585
586    #[test]
587    fn an_unclamped_knot_vector_is_recognised_as_such() {
588        // Degree 3, 6 control points, all multiplicities 1: 10 knots.
589        let e = Entity::new(
590            "IFCBSPLINECURVEWITHKNOTS",
591            vec![
592                Value::Integer(3),
593                refs(6),
594                Value::Enum("UNSPECIFIED".into()),
595                Value::Bool(false),
596                Value::Bool(false),
597                integers(&[1; 10]),
598                reals(&[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]),
599                Value::Enum("UNIFORM_KNOTS".into()),
600            ],
601        );
602        let view = BSplineCurve::new(EntityId(1), &e);
603        let knots = view.knots().unwrap().unwrap();
604        assert!(!knots.is_clamped(3));
605        assert_eq!(view.knot_spec(), KnotType::Uniform);
606    }
607
608    #[test]
609    fn a_curve_without_knots_reports_none_rather_than_failing() {
610        let e = Entity::new(
611            "IFCBSPLINECURVE",
612            vec![
613                Value::Integer(3),
614                refs(4),
615                Value::Enum("UNSPECIFIED".into()),
616                Value::Bool(false),
617                Value::Bool(false),
618            ],
619        );
620        let view = BSplineCurve::new(EntityId(1), &e);
621        assert_eq!(view.knots().unwrap(), None);
622        assert_eq!(view.weights().unwrap(), None);
623    }
624
625    #[test]
626    fn rational_weights_are_read_from_the_slot_after_the_knot_attributes() {
627        let e = rational(4, &[1.0, 0.5, 0.5, 1.0]);
628        let view = BSplineCurve::new(EntityId(1), &e);
629        assert!(view.is_rational());
630        assert_eq!(view.weights().unwrap().unwrap(), vec![1.0, 0.5, 0.5, 1.0]);
631    }
632
633    /// A zero weight is a division by zero at the control point; IEEE will
634    /// happily produce an infinity rather than an error.
635    #[test]
636    fn a_zero_weight_is_degenerate() {
637        let e = rational(4, &[1.0, 0.0, 1.0, 1.0]);
638        let err = BSplineCurve::new(EntityId(2), &e).weights().unwrap_err();
639        assert!(err.to_string().contains("positive"), "got: {err}");
640    }
641
642    #[test]
643    fn a_negative_weight_is_degenerate() {
644        let e = rational(4, &[1.0, -1.0, 1.0, 1.0]);
645        assert!(BSplineCurve::new(EntityId(1), &e).weights().is_err());
646    }
647
648    #[test]
649    fn non_finite_weights_are_rejected_by_the_typed_view() {
650        for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
651            let e = rational(4, &[1.0, bad, 1.0, 1.0]);
652            let err = BSplineCurve::new(EntityId(14), &e).weights().unwrap_err();
653            assert!(err.to_string().contains("finite"), "weight {bad}: {err}");
654        }
655    }
656
657    #[test]
658    fn a_weight_count_that_differs_from_the_control_point_count_is_rejected() {
659        let e = rational(4, &[1.0, 1.0, 1.0]);
660        let err = BSplineCurve::new(EntityId(1), &e).weights().unwrap_err();
661        assert!(err.to_string().contains("control points"), "got: {err}");
662    }
663
664    #[test]
665    fn multiplicity_overflow_is_a_typed_error_not_a_panic() {
666        let e = with_knots(4, &[i64::MAX, i64::MAX, i64::MAX], &[0.0, 0.5, 1.0]);
667        let err = BSplineCurve::new(EntityId(8), &e).knots().unwrap_err();
668        assert!(err.to_string().contains("overflow"), "got: {err}");
669    }
670
671    #[test]
672    fn degree_must_not_exceed_the_control_point_upper_index() {
673        let mut e = with_knots(4, &[4, 4], &[0.0, 1.0]);
674        e.attributes[slot::DEGREE] = Value::Integer(4);
675        let err = BSplineCurve::new(EntityId(9), &e).degree().unwrap_err();
676        assert!(err.to_string().contains("control points"), "got: {err}");
677    }
678
679    #[test]
680    fn rational_subtype_requires_weights_and_polynomial_rejects_them() {
681        let attributes = with_knots(4, &[4, 4], &[0.0, 1.0]).attributes;
682        let rational = Entity::new("IFCRATIONALBSPLINECURVEWITHKNOTS", attributes.clone());
683        assert!(BSplineCurve::new(EntityId(10), &rational)
684            .weights()
685            .unwrap_err()
686            .to_string()
687            .contains("missing WeightsData"));
688
689        let mut polynomial_attributes = attributes;
690        polynomial_attributes.push(reals(&[1.0; 4]));
691        let polynomial = Entity::new("IFCBSPLINECURVEWITHKNOTS", polynomial_attributes);
692        assert!(BSplineCurve::new(EntityId(11), &polynomial)
693            .weights()
694            .unwrap_err()
695            .to_string()
696            .contains("must not carry WeightsData"));
697    }
698
699    #[test]
700    fn degree_zero_is_rejected_because_it_describes_no_curve() {
701        let mut e = with_knots(4, &[4, 4], &[0.0, 1.0]);
702        e.attributes[0] = Value::Integer(0);
703        assert!(BSplineCurve::new(EntityId(1), &e).degree().is_err());
704    }
705
706    /// The form is a hint about provenance and must never license swapping in
707    /// an analytic circle, so it is read but kept separate from the geometry.
708    #[test]
709    fn curve_form_tokens_parse_without_altering_the_control_points() {
710        assert_eq!(
711            BSplineCurveForm::from_token("CIRCULAR_ARC"),
712            Some(BSplineCurveForm::CircularArc)
713        );
714        assert_eq!(BSplineCurveForm::from_token("SPIRAL"), None);
715        assert_eq!(
716            KnotType::from_token("PIECEWISE_BEZIER_KNOTS"),
717            Some(KnotType::PiecewiseBezier)
718        );
719        assert_eq!(KnotType::from_token("WEIRD"), None);
720    }
721}